text
stringlengths 54
60.6k
|
---|
<commit_before>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Author: Mikolaj Krzewicki, [email protected] *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTZMQsink.h"
#include "AliHLTErrorGuard.h"
#include "TDatime.h"
#include "TRandom3.h"
#include <TObject.h>
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
ClassImp(AliHLTZMQsink)
//______________________________________________________________________________
AliHLTZMQsink::AliHLTZMQsink() :
AliHLTComponent()
, fZMQcontext(NULL)
, fZMQout(NULL)
, fZMQsocketType(ZMQ_PUB)
, fZMQendpoint("@tcp://*:60201")
, fZMQpollIn(kFALSE)
, fPushbackDelayPeriod(-1)
, fIncludePrivateBlocks(kFALSE)
, fZMQneverBlock(kTRUE)
{
//ctor
}
//______________________________________________________________________________
AliHLTZMQsink::~AliHLTZMQsink()
{
//dtor
zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const Char_t* AliHLTZMQsink::GetComponentID()
{
//id
return "ZMQsink";
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsink::GetOutputDataType()
{
// default method as sink components do not produce output
AliHLTComponentDataType dt =
{sizeof(AliHLTComponentDataType),
kAliHLTVoidDataTypeID,
kAliHLTVoidDataOrigin};
return dt;
}
//______________________________________________________________________________
void AliHLTZMQsink::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
//what data types do we accept
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
void AliHLTZMQsink::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// default method as sink components do not produce output
constBase=0;
inputMultiplier=0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsink::Spawn()
{
//Spawn a new instance
return new AliHLTZMQsink();
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoInit( Int_t /*argc*/, const Char_t** /*argv*/ )
{
// see header file for class documentation
Int_t retCode=0;
//process arguments
ProcessOptionString(GetComponentArgs());
int rc = 0;
//init ZMQ stuff
fZMQcontext = zmq_ctx_new();
HLTMessage(Form("ctx create ptr %p errno %s",fZMQcontext,(rc<0)?strerror(errno):0));
if (!fZMQcontext) return -1;
fZMQout = zmq_socket(fZMQcontext, fZMQsocketType);
HLTMessage(Form("socket create ptr %p errno %s",fZMQout,(rc<0)?strerror(errno):0));
if (!fZMQout) return -1;
//set socket options
int lingerValue = 10;
rc = zmq_setsockopt(fZMQout, ZMQ_LINGER, &lingerValue, sizeof(int));
HLTMessage(Form("setopt ZMQ_LINGER=%i rc=%i errno=%s", lingerValue, rc, (rc<0)?strerror(errno):0));
int highWaterMarkSend = 100;
rc = zmq_setsockopt(fZMQout, ZMQ_SNDHWM, &highWaterMarkSend, sizeof(int));
HLTMessage(Form("setopt ZMQ_SNDHWM=%i rc=%i errno=%s",highWaterMarkSend, rc, (rc<0)?strerror(errno):0));
int highWaterMarkRecv = 100;
rc = zmq_setsockopt(fZMQout, ZMQ_RCVHWM, &highWaterMarkRecv, sizeof(int));
HLTMessage(Form("setopt ZMQ_RCVHWM=%i rc=%i errno=%s",highWaterMarkRecv, rc, (rc<0)?strerror(errno):0));
int rcvtimeo = 0;
rc = zmq_setsockopt(fZMQout, ZMQ_RCVTIMEO, &rcvtimeo, sizeof(int));
HLTMessage(Form("setopt ZMQ_RCVTIMEO=%i rc=%i errno=%s",rcvtimeo, rc, (rc<0)?strerror(errno):0));
int sndtimeo = 0;
rc = zmq_setsockopt(fZMQout, ZMQ_SNDTIMEO, &sndtimeo, sizeof(int));
HLTMessage(Form("setopt ZMQ_SNDTIMEO=%i rc=%i errno=%s",sndtimeo, rc, (rc<0)?strerror(errno):0));
//connect or bind, after setting socket options
HLTMessage(Form("ZMQ connect to %s",fZMQendpoint.Data()));
rc = alizmq_attach(fZMQout,fZMQendpoint.Data());
if (rc==-1) retCode=-1;
HLTMessage(Form("connect rc %i errno %s",rc,(rc<0)?strerror(errno):0));
return retCode;
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoDeinit()
{
// see header file for class documentation
return 0;
}
//______________________________________________________________________________
int AliHLTZMQsink::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* /*outputPtr*/,
AliHLTUInt32_t& /*size*/,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& /*edd*/ )
{
// see header file for class documentation
Int_t retCode=0;
//create a default selection of any data:
int requestTopicSize=-1;
char requestTopic[kAliHLTComponentDataTypeTopicSize];
memset(requestTopic, '*', kAliHLTComponentDataTypeTopicSize);
int requestSize=-1;
char request[kAliHLTComponentDataTypeTopicSize];
memset(request, '*', kAliHLTComponentDataTypeTopicSize);
int rc = 0;
Bool_t doSend = kTRUE;
//in case we reply to requests instead of just pushing/publishing
//we poll for requests
if (fZMQpollIn)
{
zmq_pollitem_t items[] = { { fZMQout, 0, ZMQ_POLLIN, 0 } };
zmq_poll(items, 1, 0);
if (items[0].revents & ZMQ_POLLIN)
{
int64_t more=0;
size_t moreSize=sizeof(more);
do //request could be multipart, get all parts
{
requestTopicSize = zmq_recv (fZMQout, requestTopic, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
requestSize = zmq_recv(fZMQout, request, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
}
} while (more==1);
}
else { doSend = kFALSE; }
}
//if enabled (option -pushback-period), send at most so often
if (fPushbackDelayPeriod>0)
{
TDatime time;
if ((Int_t)time.Get()-fLastPushbackDelayTime<fPushbackDelayPeriod)
{
doSend=kFALSE;
}
}
if (doSend)
{
//set the time of current push
if (fPushbackDelayPeriod>0)
{
TDatime time;
fLastPushbackDelayTime=time.Get();
}
//first make a map of selected blocks, and identify the last one
//so we can properly mark the last block for multipart ZMQ sending later
const AliHLTComponentBlockData* inputBlock = NULL;
std::vector<int> selectedBlockIdx;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//don't include provate data unless explicitly asked to
if (!fIncludePrivateBlocks)
{
if (!memcmp(inputBlock->fDataType.fOrigin, &kAliHLTDataOriginPrivate, kAliHLTComponentDataTypefOriginSize))
continue;
}
//check if the data type matches the request
char blockTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(inputBlock->fDataType, blockTopic);
if (Topicncmp(requestTopic, blockTopic, requestTopicSize))
{
selectedBlockIdx.push_back(iBlock);
}
}
//send the selected blocks
for (int iSelectedBlock = 0;
iSelectedBlock < selectedBlockIdx.size();
iSelectedBlock++)
{
inputBlock = &blocks[selectedBlockIdx[iSelectedBlock]];
AliHLTDataTopic blockTopic = *inputBlock;
//send:
// first part : AliHLTComponentDataType in string format
// second part: Payload
rc = zmq_send(fZMQout, &blockTopic, sizeof(blockTopic), ZMQ_SNDMORE);
HLTMessage(Form("send topic rc %i errno %s",rc,(rc<0)?strerror(errno):0));
int flags = 0;
if (fZMQneverBlock) flags = ZMQ_DONTWAIT;
if (iSelectedBlock < (selectedBlockIdx.size()-1)) flags = ZMQ_SNDMORE;
rc = zmq_send(fZMQout, inputBlock->fPtr, inputBlock->fSize, flags);
HLTMessage(Form("send data rc %i errno, %s",rc,(rc<0)?strerror(errno):""));
}
//send an empty message if we really need a reply (ZMQ_REP mode)
//only in case no blocks were selected
if (selectedBlockIdx.size() == 0 && fZMQsocketType==ZMQ_REP)
{
rc = zmq_send(fZMQout, 0, 0, ZMQ_SNDMORE);
HLTMessage(Form("send endframe rc %i errno %s",rc,(rc<0)?strerror(errno):0));
rc = zmq_send(fZMQout, 0, 0, 0);
HLTMessage(Form("send endframe rc %i errno %s",rc,(rc<0)?strerror(errno):0));
}
}
outputBlocks.clear();
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
//if (option.EqualTo("ZMQpollIn"))
//{
// fZMQpollIn = (value.EqualTo("0"))?kFALSE:kTRUE;
//}
if (option.EqualTo("ZMQsocketMode"))
{
if (value.EqualTo("PUB")) fZMQsocketType=ZMQ_PUB;
if (value.EqualTo("REP")) fZMQsocketType=ZMQ_REP;
if (value.EqualTo("PUSH")) fZMQsocketType=ZMQ_PUSH;
//always poll when REPlying
fZMQpollIn=(fZMQsocketType==ZMQ_REP)?kTRUE:kFALSE;
}
if (option.EqualTo("ZMQendpoint"))
{
fZMQendpoint = value;
}
if (option.EqualTo("pushback-period"))
{
HLTMessage(Form("Setting pushback delay to %i", atoi(value.Data())));
fPushbackDelayPeriod = atoi(value.Data());
}
if (option.EqualTo("IncludePrivateBlocks"))
{
fIncludePrivateBlocks=kTRUE;
}
if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOptionString(TString arguments)
{
//process passed options
HLTMessage("Argument string: %s\n", arguments.Data());
stringMap* options = TokenizeOptionString(arguments);
for (stringMap::iterator i=options->begin(); i!=options->end(); ++i)
{
HLTMessage(" %s : %s", i->first.data(), i->second.data());
ProcessOption(i->first,i->second);
}
delete options; //tidy up
return 1;
}
//______________________________________________________________________________
AliHLTZMQsink::stringMap* AliHLTZMQsink::TokenizeOptionString(const TString str)
{
//options have the form:
// -option value
// -option=value
// -option
// --option value
// --option=value
// --option
// option=value
// option value
// (value can also be a string like 'some string')
//
// options can be separated by ' ' or ',' arbitrarily combined, e.g:
//"-option option1=value1 --option2 value2, -option4=\'some string\'"
//optionRE by construction contains a pure option name as 3rd submatch (without --,-, =)
//valueRE does NOT match options
TPRegexp optionRE("(?:(-{1,2})|((?='?[^,=]+=?)))"
"((?(2)(?:(?(?=')'(?:[^'\\\\]++|\\.)*+'|[^, =]+))(?==?))"
"(?(1)[^, =]+(?=[= ,$])))");
TPRegexp valueRE("(?(?!(-{1,2}|[^, =]+=))"
"(?(?=')'(?:[^'\\\\]++|\\.)*+'"
"|[^, =]+))");
stringMap* options = new stringMap;
TArrayI pos;
const TString mods="";
Int_t start = 0;
while (1) {
Int_t prevStart=start;
TString optionStr="";
TString valueStr="";
//check if we have a new option in this field
Int_t nOption=optionRE.Match(str,mods,start,10,&pos);
if (nOption>0)
{
optionStr = str(pos[6],pos[7]-pos[6]);
optionStr=optionStr.Strip(TString::kBoth,'\'');
start=pos[1]; //update the current character to the end of match
}
//check if the next field is a value
Int_t nValue=valueRE.Match(str,mods,start,10,&pos);
if (nValue>0)
{
valueStr = str(pos[0],pos[1]-pos[0]);
valueStr=valueStr.Strip(TString::kBoth,'\'');
start=pos[1]; //update the current character to the end of match
}
//skip empty entries
if (nOption>0 || nValue>0)
{
(*options)[optionStr.Data()] = valueStr.Data();
}
if (start>=str.Length()-1 || start==prevStart ) break;
}
//for (stringMap::iterator i=options->begin(); i!=options->end(); ++i)
//{
// printf("%s : %s\n", i->first.data(), i->second.data());
//}
return options;
}
<commit_msg>use zmq_strerror() instead of standard one<commit_after>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Author: Mikolaj Krzewicki, [email protected] *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTZMQsink.h"
#include "AliHLTErrorGuard.h"
#include "TDatime.h"
#include "TRandom3.h"
#include <TObject.h>
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
ClassImp(AliHLTZMQsink)
//______________________________________________________________________________
AliHLTZMQsink::AliHLTZMQsink() :
AliHLTComponent()
, fZMQcontext(NULL)
, fZMQout(NULL)
, fZMQsocketType(ZMQ_PUB)
, fZMQendpoint("@tcp://*:60201")
, fZMQpollIn(kFALSE)
, fPushbackDelayPeriod(-1)
, fIncludePrivateBlocks(kFALSE)
, fZMQneverBlock(kTRUE)
{
//ctor
}
//______________________________________________________________________________
AliHLTZMQsink::~AliHLTZMQsink()
{
//dtor
zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const Char_t* AliHLTZMQsink::GetComponentID()
{
//id
return "ZMQsink";
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsink::GetOutputDataType()
{
// default method as sink components do not produce output
AliHLTComponentDataType dt =
{sizeof(AliHLTComponentDataType),
kAliHLTVoidDataTypeID,
kAliHLTVoidDataOrigin};
return dt;
}
//______________________________________________________________________________
void AliHLTZMQsink::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
//what data types do we accept
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
void AliHLTZMQsink::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// default method as sink components do not produce output
constBase=0;
inputMultiplier=0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsink::Spawn()
{
//Spawn a new instance
return new AliHLTZMQsink();
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoInit( Int_t /*argc*/, const Char_t** /*argv*/ )
{
// see header file for class documentation
Int_t retCode=0;
//process arguments
ProcessOptionString(GetComponentArgs());
int rc = 0;
//init ZMQ stuff
fZMQcontext = zmq_ctx_new();
HLTMessage(Form("ctx create ptr %p errno %s",fZMQcontext,(rc<0)?zmq_strerror(errno):0));
if (!fZMQcontext) return -1;
fZMQout = zmq_socket(fZMQcontext, fZMQsocketType);
HLTMessage(Form("socket create ptr %p errno %s",fZMQout,(rc<0)?zmq_strerror(errno):0));
if (!fZMQout) return -1;
//set socket options
int lingerValue = 10;
rc = zmq_setsockopt(fZMQout, ZMQ_LINGER, &lingerValue, sizeof(int));
HLTMessage(Form("setopt ZMQ_LINGER=%i rc=%i errno=%s", lingerValue, rc, (rc<0)?zmq_strerror(errno):0));
int highWaterMarkSend = 100;
rc = zmq_setsockopt(fZMQout, ZMQ_SNDHWM, &highWaterMarkSend, sizeof(int));
HLTMessage(Form("setopt ZMQ_SNDHWM=%i rc=%i errno=%s",highWaterMarkSend, rc, (rc<0)?zmq_strerror(errno):0));
int highWaterMarkRecv = 100;
rc = zmq_setsockopt(fZMQout, ZMQ_RCVHWM, &highWaterMarkRecv, sizeof(int));
HLTMessage(Form("setopt ZMQ_RCVHWM=%i rc=%i errno=%s",highWaterMarkRecv, rc, (rc<0)?zmq_strerror(errno):0));
int rcvtimeo = 0;
rc = zmq_setsockopt(fZMQout, ZMQ_RCVTIMEO, &rcvtimeo, sizeof(int));
HLTMessage(Form("setopt ZMQ_RCVTIMEO=%i rc=%i errno=%s",rcvtimeo, rc, (rc<0)?zmq_strerror(errno):0));
int sndtimeo = 0;
rc = zmq_setsockopt(fZMQout, ZMQ_SNDTIMEO, &sndtimeo, sizeof(int));
HLTMessage(Form("setopt ZMQ_SNDTIMEO=%i rc=%i errno=%s",sndtimeo, rc, (rc<0)?zmq_strerror(errno):0));
//connect or bind, after setting socket options
HLTMessage(Form("ZMQ connect to %s",fZMQendpoint.Data()));
rc = alizmq_attach(fZMQout,fZMQendpoint.Data());
if (rc==-1) retCode=-1;
HLTMessage(Form("connect rc %i errno %s",rc,(rc<0)?zmq_strerror(errno):0));
return retCode;
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoDeinit()
{
// see header file for class documentation
return 0;
}
//______________________________________________________________________________
int AliHLTZMQsink::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* /*outputPtr*/,
AliHLTUInt32_t& /*size*/,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& /*edd*/ )
{
// see header file for class documentation
Int_t retCode=0;
//create a default selection of any data:
int requestTopicSize=-1;
char requestTopic[kAliHLTComponentDataTypeTopicSize];
memset(requestTopic, '*', kAliHLTComponentDataTypeTopicSize);
int requestSize=-1;
char request[kAliHLTComponentDataTypeTopicSize];
memset(request, '*', kAliHLTComponentDataTypeTopicSize);
int rc = 0;
Bool_t doSend = kTRUE;
//in case we reply to requests instead of just pushing/publishing
//we poll for requests
if (fZMQpollIn)
{
zmq_pollitem_t items[] = { { fZMQout, 0, ZMQ_POLLIN, 0 } };
zmq_poll(items, 1, 0);
if (items[0].revents & ZMQ_POLLIN)
{
int64_t more=0;
size_t moreSize=sizeof(more);
do //request could be multipart, get all parts
{
requestTopicSize = zmq_recv (fZMQout, requestTopic, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
requestSize = zmq_recv(fZMQout, request, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
}
} while (more==1);
}
else { doSend = kFALSE; }
}
//if enabled (option -pushback-period), send at most so often
if (fPushbackDelayPeriod>0)
{
TDatime time;
if ((Int_t)time.Get()-fLastPushbackDelayTime<fPushbackDelayPeriod)
{
doSend=kFALSE;
}
}
if (doSend)
{
//set the time of current push
if (fPushbackDelayPeriod>0)
{
TDatime time;
fLastPushbackDelayTime=time.Get();
}
//first make a map of selected blocks, and identify the last one
//so we can properly mark the last block for multipart ZMQ sending later
const AliHLTComponentBlockData* inputBlock = NULL;
std::vector<int> selectedBlockIdx;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//don't include provate data unless explicitly asked to
if (!fIncludePrivateBlocks)
{
if (!memcmp(inputBlock->fDataType.fOrigin, &kAliHLTDataOriginPrivate, kAliHLTComponentDataTypefOriginSize))
continue;
}
//check if the data type matches the request
char blockTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(inputBlock->fDataType, blockTopic);
if (Topicncmp(requestTopic, blockTopic, requestTopicSize))
{
selectedBlockIdx.push_back(iBlock);
}
}
//send the selected blocks
for (int iSelectedBlock = 0;
iSelectedBlock < selectedBlockIdx.size();
iSelectedBlock++)
{
inputBlock = &blocks[selectedBlockIdx[iSelectedBlock]];
AliHLTDataTopic blockTopic = *inputBlock;
//send:
// first part : AliHLTComponentDataType in string format
// second part: Payload
rc = zmq_send(fZMQout, &blockTopic, sizeof(blockTopic), ZMQ_SNDMORE);
HLTMessage(Form("send topic rc %i errno %s",rc,(rc<0)?zmq_strerror(errno):0));
int flags = 0;
if (fZMQneverBlock) flags = ZMQ_DONTWAIT;
if (iSelectedBlock < (selectedBlockIdx.size()-1)) flags = ZMQ_SNDMORE;
rc = zmq_send(fZMQout, inputBlock->fPtr, inputBlock->fSize, flags);
HLTMessage(Form("send data rc %i errno, %s",rc,(rc<0)?zmq_strerror(errno):""));
}
//send an empty message if we really need a reply (ZMQ_REP mode)
//only in case no blocks were selected
if (selectedBlockIdx.size() == 0 && fZMQsocketType==ZMQ_REP)
{
rc = zmq_send(fZMQout, 0, 0, ZMQ_SNDMORE);
HLTMessage(Form("send endframe rc %i errno %s",rc,(rc<0)?zmq_strerror(errno):0));
rc = zmq_send(fZMQout, 0, 0, 0);
HLTMessage(Form("send endframe rc %i errno %s",rc,(rc<0)?zmq_strerror(errno):0));
}
}
outputBlocks.clear();
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
//if (option.EqualTo("ZMQpollIn"))
//{
// fZMQpollIn = (value.EqualTo("0"))?kFALSE:kTRUE;
//}
if (option.EqualTo("ZMQsocketMode"))
{
if (value.EqualTo("PUB")) fZMQsocketType=ZMQ_PUB;
if (value.EqualTo("REP")) fZMQsocketType=ZMQ_REP;
if (value.EqualTo("PUSH")) fZMQsocketType=ZMQ_PUSH;
//always poll when REPlying
fZMQpollIn=(fZMQsocketType==ZMQ_REP)?kTRUE:kFALSE;
}
if (option.EqualTo("ZMQendpoint"))
{
fZMQendpoint = value;
}
if (option.EqualTo("pushback-period"))
{
HLTMessage(Form("Setting pushback delay to %i", atoi(value.Data())));
fPushbackDelayPeriod = atoi(value.Data());
}
if (option.EqualTo("IncludePrivateBlocks"))
{
fIncludePrivateBlocks=kTRUE;
}
if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOptionString(TString arguments)
{
//process passed options
HLTMessage("Argument string: %s\n", arguments.Data());
stringMap* options = TokenizeOptionString(arguments);
for (stringMap::iterator i=options->begin(); i!=options->end(); ++i)
{
HLTMessage(" %s : %s", i->first.data(), i->second.data());
ProcessOption(i->first,i->second);
}
delete options; //tidy up
return 1;
}
//______________________________________________________________________________
AliHLTZMQsink::stringMap* AliHLTZMQsink::TokenizeOptionString(const TString str)
{
//options have the form:
// -option value
// -option=value
// -option
// --option value
// --option=value
// --option
// option=value
// option value
// (value can also be a string like 'some string')
//
// options can be separated by ' ' or ',' arbitrarily combined, e.g:
//"-option option1=value1 --option2 value2, -option4=\'some string\'"
//optionRE by construction contains a pure option name as 3rd submatch (without --,-, =)
//valueRE does NOT match options
TPRegexp optionRE("(?:(-{1,2})|((?='?[^,=]+=?)))"
"((?(2)(?:(?(?=')'(?:[^'\\\\]++|\\.)*+'|[^, =]+))(?==?))"
"(?(1)[^, =]+(?=[= ,$])))");
TPRegexp valueRE("(?(?!(-{1,2}|[^, =]+=))"
"(?(?=')'(?:[^'\\\\]++|\\.)*+'"
"|[^, =]+))");
stringMap* options = new stringMap;
TArrayI pos;
const TString mods="";
Int_t start = 0;
while (1) {
Int_t prevStart=start;
TString optionStr="";
TString valueStr="";
//check if we have a new option in this field
Int_t nOption=optionRE.Match(str,mods,start,10,&pos);
if (nOption>0)
{
optionStr = str(pos[6],pos[7]-pos[6]);
optionStr=optionStr.Strip(TString::kBoth,'\'');
start=pos[1]; //update the current character to the end of match
}
//check if the next field is a value
Int_t nValue=valueRE.Match(str,mods,start,10,&pos);
if (nValue>0)
{
valueStr = str(pos[0],pos[1]-pos[0]);
valueStr=valueStr.Strip(TString::kBoth,'\'');
start=pos[1]; //update the current character to the end of match
}
//skip empty entries
if (nOption>0 || nValue>0)
{
(*options)[optionStr.Data()] = valueStr.Data();
}
if (start>=str.Length()-1 || start==prevStart ) break;
}
//for (stringMap::iterator i=options->begin(); i!=options->end(); ++i)
//{
// printf("%s : %s\n", i->first.data(), i->second.data());
//}
return options;
}
<|endoftext|> |
<commit_before>/* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "common/texture_manager.h"
#include "common/halfling_sys.h"
#include "common/d3d_util.h"
#include "DDSTextureLoader.h"
namespace Common {
TextureManager::~TextureManager() {
for (auto bucket = m_textureCache.begin(); bucket != m_textureCache.end(); ++bucket) {
for (auto bucketIter = bucket->second.begin(); bucketIter != bucket->second.end(); ++bucketIter) {
ReleaseCOM(bucketIter->second);
}
}
}
ID3D11ShaderResourceView * TextureManager::GetSRVFromFile(ID3D11Device *device, const std::wstring filePath, D3D11_USAGE usage, uint bindFlags, uint cpuAccessFlags, uint miscFlags, bool forceSRGB) {
if (filePath.compare(filePath.length() - 4, std::string::npos, L".dds") == 0 || filePath.compare(filePath.length() - 4, std::string::npos, L".DDS") == 0) {
return GetSRVFromDDSFile(device, filePath, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB);
} else {
return nullptr;
}
}
ID3D11ShaderResourceView *TextureManager::GetSRVFromDDSFile(ID3D11Device *device, const std::wstring filePath, D3D11_USAGE usage, uint bindFlags, uint cpuAccessFlags, uint miscFlags, bool forceSRGB) {
// First check the cache
auto bucket = m_textureCache.find(filePath);
if (bucket != m_textureCache.end()) {
for (auto iter = bucket->second.begin(); iter != bucket->second.end(); ++iter) {
if (usage == iter->first.Usage &&
bindFlags == iter->first.BindFlags &&
cpuAccessFlags == iter->first.CpuAccessFlags &&
miscFlags == iter->first.MiscFlags &&
forceSRGB == iter->first.ForceSRGB) {
return iter->second;
}
}
}
// Else create it from scratch
ID3D11ShaderResourceView *newSRV;
HR(DirectX::CreateDDSTextureFromFileEx(device, filePath.c_str(), 0, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, nullptr, &newSRV));
// Store the new SRV in cache
TextureParams newParams {usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB};
m_textureCache[filePath].push_back(std::pair<TextureParams, ID3D11ShaderResourceView *>(newParams, newSRV));
// Finally return the SRV
return newSRV;
}
} // End of namespace Common
<commit_msg>COMMON: Fix file extension comparisons<commit_after>/* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "common/texture_manager.h"
#include "common/halfling_sys.h"
#include "common/d3d_util.h"
#include "DDSTextureLoader.h"
namespace Common {
TextureManager::~TextureManager() {
for (auto bucket = m_textureCache.begin(); bucket != m_textureCache.end(); ++bucket) {
for (auto bucketIter = bucket->second.begin(); bucketIter != bucket->second.end(); ++bucketIter) {
ReleaseCOM(bucketIter->second);
}
}
}
ID3D11ShaderResourceView * TextureManager::GetSRVFromFile(ID3D11Device *device, const std::wstring filePath, D3D11_USAGE usage, uint bindFlags, uint cpuAccessFlags, uint miscFlags, bool forceSRGB) {
if (filePath.compare(filePath.length() - 5, 4, L".dds") == 0 || filePath.compare(filePath.length() - 5, 4, L".DDS") == 0) {
return GetSRVFromDDSFile(device, filePath, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB);
} else {
return nullptr;
}
}
ID3D11ShaderResourceView *TextureManager::GetSRVFromDDSFile(ID3D11Device *device, const std::wstring filePath, D3D11_USAGE usage, uint bindFlags, uint cpuAccessFlags, uint miscFlags, bool forceSRGB) {
// First check the cache
auto bucket = m_textureCache.find(filePath);
if (bucket != m_textureCache.end()) {
for (auto iter = bucket->second.begin(); iter != bucket->second.end(); ++iter) {
if (usage == iter->first.Usage &&
bindFlags == iter->first.BindFlags &&
cpuAccessFlags == iter->first.CpuAccessFlags &&
miscFlags == iter->first.MiscFlags &&
forceSRGB == iter->first.ForceSRGB) {
return iter->second;
}
}
}
// Else create it from scratch
ID3D11ShaderResourceView *newSRV;
HR(DirectX::CreateDDSTextureFromFileEx(device, filePath.c_str(), 0, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, nullptr, &newSRV));
// Store the new SRV in cache
TextureParams newParams {usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB};
m_textureCache[filePath].push_back(std::pair<TextureParams, ID3D11ShaderResourceView *>(newParams, newSRV));
// Finally return the SRV
return newSRV;
}
} // End of namespace Common
<|endoftext|> |
<commit_before>#include "scheduler_pinned_base.h"
#include "simulator.h"
#include "core_manager.h"
#include "performance_model.h"
#include "os_compat.h"
#include <sstream>
// Pinned scheduler.
// Each thread has is pinned to a specific core (m_thread_affinity).
// Cores are handed out to new threads in round-robin fashion.
// If multiple threads share a core, they are time-shared with a configurable quantum
SchedulerPinnedBase::SchedulerPinnedBase(ThreadManager *thread_manager, SubsecondTime quantum)
: SchedulerDynamic(thread_manager)
, m_quantum(quantum)
, m_last_periodic(SubsecondTime::Zero())
, m_core_thread_running(Sim()->getConfig()->getApplicationCores(), INVALID_THREAD_ID)
, m_quantum_left(Sim()->getConfig()->getApplicationCores(), SubsecondTime::Zero())
{
}
core_id_t SchedulerPinnedBase::findFreeCoreForThread(thread_id_t thread_id)
{
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id) && m_core_thread_running[core_id] == INVALID_THREAD_ID)
{
return core_id;
}
}
return INVALID_CORE_ID;
}
core_id_t SchedulerPinnedBase::threadCreate(thread_id_t thread_id)
{
if (m_thread_info.size() <= (size_t)thread_id)
m_thread_info.resize(m_thread_info.size() + 16);
if (m_thread_info[thread_id].hasAffinity())
{
// Thread already has an affinity set at/before creation
}
else
{
threadSetInitialAffinity(thread_id);
}
// The first thread scheduled on this core can start immediately, the others have to wait
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_CORE_ID)
{
m_thread_info[thread_id].setCoreRunning(free_core_id);
m_core_thread_running[free_core_id] = thread_id;
m_quantum_left[free_core_id] = m_quantum;
return free_core_id;
}
else
{
m_thread_info[thread_id].setCoreRunning(INVALID_CORE_ID);
return INVALID_CORE_ID;
}
}
void SchedulerPinnedBase::threadYield(thread_id_t thread_id)
{
core_id_t core_id = m_thread_info[thread_id].getCoreRunning();
if (core_id != INVALID_CORE_ID)
{
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
SubsecondTime time = core->getPerformanceModel()->getElapsedTime();
m_quantum_left[core_id] = SubsecondTime::Zero();
reschedule(time, core_id, false);
if (!m_thread_info[thread_id].hasAffinity(core_id))
{
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_CORE_ID)
{
// We have just been moved to a different core(s), and one of them is free. Schedule us there now.
reschedule(time, free_core_id, false);
}
}
}
}
bool SchedulerPinnedBase::threadSetAffinity(thread_id_t calling_thread_id, thread_id_t thread_id, size_t cpusetsize, const cpu_set_t *mask)
{
if (m_thread_info.size() <= (size_t)thread_id)
m_thread_info.resize(thread_id + 16);
if (!mask)
{
// No mask given: free to schedule anywhere.
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
m_thread_info[thread_id].addAffinity(core_id);
}
}
else
{
m_thread_info[thread_id].clearAffinity();
bool any = false;
for(unsigned int cpu = 0; cpu < 8 * cpusetsize; ++cpu)
{
if (CPU_ISSET_S(cpu, cpusetsize, mask))
{
LOG_ASSERT_ERROR(cpu < Sim()->getConfig()->getApplicationCores(), "Invalid core %d found in sched_setaffinity() mask", cpu);
any = true;
m_thread_info[thread_id].addAffinity(cpu);
}
}
LOG_ASSERT_ERROR(any, "No valid core found in sched_setaffinity() mask");
}
// We're setting the affinity of a thread that isn't yet created. Do nothing else for now.
if (thread_id >= (thread_id_t)Sim()->getThreadManager()->getNumThreads())
return true;
if (thread_id == calling_thread_id)
{
threadYield(thread_id);
}
else if (m_thread_info[thread_id].isRunning() // Thread is running
&& !m_thread_info[thread_id].hasAffinity(m_thread_info[thread_id].getCoreRunning())) // but not where we want it to
{
// Reschedule the thread as soon as possible
m_quantum_left[m_thread_info[thread_id].getCoreRunning()] = SubsecondTime::Zero();
}
else if (m_threads_runnable[thread_id] // Thread is runnable
&& !m_thread_info[thread_id].isRunning()) // Thread is not running (we can't preempt it outside of the barrier)
{
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID) // Thread's new core is free
{
// We have just been moved to a different core, and that core is free. Schedule us there now.
Core *core = Sim()->getCoreManager()->getCoreFromID(free_core_id);
SubsecondTime time = core->getPerformanceModel()->getElapsedTime();
reschedule(time, free_core_id, false);
}
}
return true;
}
bool SchedulerPinnedBase::threadGetAffinity(thread_id_t thread_id, size_t cpusetsize, cpu_set_t *mask)
{
if (cpusetsize*8 < Sim()->getConfig()->getApplicationCores())
{
// Not enough space to return result
return false;
}
CPU_ZERO_S(cpusetsize, mask);
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id))
CPU_SET_S(core_id, cpusetsize, mask);
}
return true;
}
void SchedulerPinnedBase::threadStart(thread_id_t thread_id, SubsecondTime time)
{
// Thread transitioned out of INITIALIZING, if it did not get a core assigned by threadCreate but there is a free one now, schedule it there
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID)
reschedule(time, free_core_id, false);
}
void SchedulerPinnedBase::threadStall(thread_id_t thread_id, ThreadManager::stall_type_t reason, SubsecondTime time)
{
// If the running thread becomes unrunnable, schedule someone else
if (m_thread_info[thread_id].isRunning())
reschedule(time, m_thread_info[thread_id].getCoreRunning(), false);
}
void SchedulerPinnedBase::threadResume(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time)
{
// If our core is currently idle, schedule us now
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID)
reschedule(time, free_core_id, false);
}
void SchedulerPinnedBase::threadExit(thread_id_t thread_id, SubsecondTime time)
{
// If the running thread becomes unrunnable, schedule someone else
if (m_thread_info[thread_id].isRunning())
reschedule(time, m_thread_info[thread_id].getCoreRunning(), false);
}
void SchedulerPinnedBase::periodic(SubsecondTime time)
{
SubsecondTime delta = time - m_last_periodic;
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (delta > m_quantum_left[core_id] || m_core_thread_running[core_id] == INVALID_THREAD_ID)
{
reschedule(time, core_id, true);
}
else
{
m_quantum_left[core_id] -= delta;
}
}
m_last_periodic = time;
}
void SchedulerPinnedBase::reschedule(SubsecondTime time, core_id_t core_id, bool is_periodic)
{
if (m_core_thread_running[core_id] != INVALID_THREAD_ID
&& Sim()->getThreadManager()->getThreadState(m_core_thread_running[core_id]) == Core::INITIALIZING)
{
// Thread on this core is starting up, don't reschedule it for now
return;
}
thread_id_t new_thread_id = INVALID_THREAD_ID;
SubsecondTime min_last_scheduled = SubsecondTime::MaxTime();
for(thread_id_t thread_id = 0; thread_id < (thread_id_t)m_threads_runnable.size(); ++thread_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id) // Thread is allowed to run on this core
&& m_threads_runnable[thread_id] == true // Thread is not stalled
&& (!m_thread_info[thread_id].isRunning() // Thread is not already running somewhere else
|| m_thread_info[thread_id].getCoreRunning() == core_id)
)
{
// Find thread that was scheduled the longest time ago
if (m_thread_info[thread_id].getLastScheduled() < min_last_scheduled)
{
new_thread_id = thread_id;
min_last_scheduled = m_thread_info[thread_id].getLastScheduled();
}
}
}
if (m_core_thread_running[core_id] != new_thread_id)
{
// If a thread was running on this core, and we'll schedule another one, unschedule the current one
thread_id_t thread_now = m_core_thread_running[core_id];
if (thread_now != INVALID_THREAD_ID)
{
m_thread_info[thread_now].setCoreRunning(INVALID_CORE_ID);
m_thread_info[thread_now].setLastScheduled(time);
moveThread(thread_now, INVALID_CORE_ID, time);
}
// Set core as running this thread *before* we call moveThread(), otherwise the HOOK_THREAD_RESUME callback for this
// thread might see an empty core, causing a recursive loop of reschedulings
m_core_thread_running[core_id] = new_thread_id;
// If we found a new thread to schedule, move it here
if (new_thread_id != INVALID_THREAD_ID)
{
// If thread was running somewhere else: let that core know
if (m_thread_info[new_thread_id].isRunning())
m_core_thread_running[m_thread_info[new_thread_id].getCoreRunning()] = INVALID_THREAD_ID;
// Move thread to this core
m_thread_info[new_thread_id].setCoreRunning(core_id);
moveThread(new_thread_id, core_id, time);
}
}
m_quantum_left[core_id] = m_quantum;
}
String SchedulerPinnedBase::ThreadInfo::getAffinityString() const
{
std::stringstream ss;
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (hasAffinity(core_id))
{
if (ss.str().size() > 0)
ss << ",";
ss << core_id;
}
}
return String(ss.str().c_str());
}
void SchedulerPinnedBase::printState()
{
printf("thread state:");
for(thread_id_t thread_id = 0; thread_id < (thread_id_t)Sim()->getThreadManager()->getNumThreads(); ++thread_id)
{
char state;
switch(Sim()->getThreadManager()->getThreadState(thread_id))
{
case Core::INITIALIZING:
state = 'I';
break;
case Core::RUNNING:
state = 'R';
break;
case Core::STALLED:
state = 'S';
break;
case Core::SLEEPING:
state = 's';
break;
case Core::WAKING_UP:
state = 'W';
break;
case Core::IDLE:
state = 'I';
break;
case Core::BROKEN:
state = 'B';
break;
case Core::NUM_STATES:
default:
state = '?';
break;
}
if (m_thread_info[thread_id].isRunning())
{
printf(" %c@%d", state, m_thread_info[thread_id].getCoreRunning());
}
else
{
printf(" %c%c%s", state, m_threads_runnable[thread_id] ? '+' : '_', m_thread_info[thread_id].getAffinityString().c_str());
}
}
printf(" -- core state:");
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_core_thread_running[core_id] == INVALID_THREAD_ID)
printf(" __");
else
printf(" %2d", m_core_thread_running[core_id]);
}
printf("\n");
}
<commit_msg>[scheduler] Update last-scheduled time for running thread when rescheduling, fixes a spinning thread not being rescheduled in favor of newly created threads<commit_after>#include "scheduler_pinned_base.h"
#include "simulator.h"
#include "core_manager.h"
#include "performance_model.h"
#include "os_compat.h"
#include <sstream>
// Pinned scheduler.
// Each thread has is pinned to a specific core (m_thread_affinity).
// Cores are handed out to new threads in round-robin fashion.
// If multiple threads share a core, they are time-shared with a configurable quantum
SchedulerPinnedBase::SchedulerPinnedBase(ThreadManager *thread_manager, SubsecondTime quantum)
: SchedulerDynamic(thread_manager)
, m_quantum(quantum)
, m_last_periodic(SubsecondTime::Zero())
, m_core_thread_running(Sim()->getConfig()->getApplicationCores(), INVALID_THREAD_ID)
, m_quantum_left(Sim()->getConfig()->getApplicationCores(), SubsecondTime::Zero())
{
}
core_id_t SchedulerPinnedBase::findFreeCoreForThread(thread_id_t thread_id)
{
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id) && m_core_thread_running[core_id] == INVALID_THREAD_ID)
{
return core_id;
}
}
return INVALID_CORE_ID;
}
core_id_t SchedulerPinnedBase::threadCreate(thread_id_t thread_id)
{
if (m_thread_info.size() <= (size_t)thread_id)
m_thread_info.resize(m_thread_info.size() + 16);
if (m_thread_info[thread_id].hasAffinity())
{
// Thread already has an affinity set at/before creation
}
else
{
threadSetInitialAffinity(thread_id);
}
// The first thread scheduled on this core can start immediately, the others have to wait
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_CORE_ID)
{
m_thread_info[thread_id].setCoreRunning(free_core_id);
m_core_thread_running[free_core_id] = thread_id;
m_quantum_left[free_core_id] = m_quantum;
return free_core_id;
}
else
{
m_thread_info[thread_id].setCoreRunning(INVALID_CORE_ID);
return INVALID_CORE_ID;
}
}
void SchedulerPinnedBase::threadYield(thread_id_t thread_id)
{
core_id_t core_id = m_thread_info[thread_id].getCoreRunning();
if (core_id != INVALID_CORE_ID)
{
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
SubsecondTime time = core->getPerformanceModel()->getElapsedTime();
m_quantum_left[core_id] = SubsecondTime::Zero();
reschedule(time, core_id, false);
if (!m_thread_info[thread_id].hasAffinity(core_id))
{
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_CORE_ID)
{
// We have just been moved to a different core(s), and one of them is free. Schedule us there now.
reschedule(time, free_core_id, false);
}
}
}
}
bool SchedulerPinnedBase::threadSetAffinity(thread_id_t calling_thread_id, thread_id_t thread_id, size_t cpusetsize, const cpu_set_t *mask)
{
if (m_thread_info.size() <= (size_t)thread_id)
m_thread_info.resize(thread_id + 16);
if (!mask)
{
// No mask given: free to schedule anywhere.
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
m_thread_info[thread_id].addAffinity(core_id);
}
}
else
{
m_thread_info[thread_id].clearAffinity();
bool any = false;
for(unsigned int cpu = 0; cpu < 8 * cpusetsize; ++cpu)
{
if (CPU_ISSET_S(cpu, cpusetsize, mask))
{
LOG_ASSERT_ERROR(cpu < Sim()->getConfig()->getApplicationCores(), "Invalid core %d found in sched_setaffinity() mask", cpu);
any = true;
m_thread_info[thread_id].addAffinity(cpu);
}
}
LOG_ASSERT_ERROR(any, "No valid core found in sched_setaffinity() mask");
}
// We're setting the affinity of a thread that isn't yet created. Do nothing else for now.
if (thread_id >= (thread_id_t)Sim()->getThreadManager()->getNumThreads())
return true;
if (thread_id == calling_thread_id)
{
threadYield(thread_id);
}
else if (m_thread_info[thread_id].isRunning() // Thread is running
&& !m_thread_info[thread_id].hasAffinity(m_thread_info[thread_id].getCoreRunning())) // but not where we want it to
{
// Reschedule the thread as soon as possible
m_quantum_left[m_thread_info[thread_id].getCoreRunning()] = SubsecondTime::Zero();
}
else if (m_threads_runnable[thread_id] // Thread is runnable
&& !m_thread_info[thread_id].isRunning()) // Thread is not running (we can't preempt it outside of the barrier)
{
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID) // Thread's new core is free
{
// We have just been moved to a different core, and that core is free. Schedule us there now.
Core *core = Sim()->getCoreManager()->getCoreFromID(free_core_id);
SubsecondTime time = core->getPerformanceModel()->getElapsedTime();
reschedule(time, free_core_id, false);
}
}
return true;
}
bool SchedulerPinnedBase::threadGetAffinity(thread_id_t thread_id, size_t cpusetsize, cpu_set_t *mask)
{
if (cpusetsize*8 < Sim()->getConfig()->getApplicationCores())
{
// Not enough space to return result
return false;
}
CPU_ZERO_S(cpusetsize, mask);
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id))
CPU_SET_S(core_id, cpusetsize, mask);
}
return true;
}
void SchedulerPinnedBase::threadStart(thread_id_t thread_id, SubsecondTime time)
{
// Thread transitioned out of INITIALIZING, if it did not get a core assigned by threadCreate but there is a free one now, schedule it there
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID)
reschedule(time, free_core_id, false);
}
void SchedulerPinnedBase::threadStall(thread_id_t thread_id, ThreadManager::stall_type_t reason, SubsecondTime time)
{
// If the running thread becomes unrunnable, schedule someone else
if (m_thread_info[thread_id].isRunning())
reschedule(time, m_thread_info[thread_id].getCoreRunning(), false);
}
void SchedulerPinnedBase::threadResume(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time)
{
// If our core is currently idle, schedule us now
core_id_t free_core_id = findFreeCoreForThread(thread_id);
if (free_core_id != INVALID_THREAD_ID)
reschedule(time, free_core_id, false);
}
void SchedulerPinnedBase::threadExit(thread_id_t thread_id, SubsecondTime time)
{
// If the running thread becomes unrunnable, schedule someone else
if (m_thread_info[thread_id].isRunning())
reschedule(time, m_thread_info[thread_id].getCoreRunning(), false);
}
void SchedulerPinnedBase::periodic(SubsecondTime time)
{
SubsecondTime delta = time - m_last_periodic;
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (delta > m_quantum_left[core_id] || m_core_thread_running[core_id] == INVALID_THREAD_ID)
{
reschedule(time, core_id, true);
}
else
{
m_quantum_left[core_id] -= delta;
}
}
m_last_periodic = time;
}
void SchedulerPinnedBase::reschedule(SubsecondTime time, core_id_t core_id, bool is_periodic)
{
if (m_core_thread_running[core_id] != INVALID_THREAD_ID
&& Sim()->getThreadManager()->getThreadState(m_core_thread_running[core_id]) == Core::INITIALIZING)
{
// Thread on this core is starting up, don't reschedule it for now
return;
}
thread_id_t new_thread_id = INVALID_THREAD_ID;
SubsecondTime min_last_scheduled = SubsecondTime::MaxTime();
for(thread_id_t thread_id = 0; thread_id < (thread_id_t)m_threads_runnable.size(); ++thread_id)
{
if (m_thread_info[thread_id].hasAffinity(core_id) // Thread is allowed to run on this core
&& m_threads_runnable[thread_id] == true // Thread is not stalled
&& (!m_thread_info[thread_id].isRunning() // Thread is not already running somewhere else
|| m_thread_info[thread_id].getCoreRunning() == core_id)
)
{
// If thread is running here now, update its last-scheduled time to now
if (thread_id == m_core_thread_running[core_id])
{
m_thread_info[thread_id].setLastScheduled(time);
}
// Find thread that was scheduled the longest time ago
if (m_thread_info[thread_id].getLastScheduled() < min_last_scheduled)
{
new_thread_id = thread_id;
min_last_scheduled = m_thread_info[thread_id].getLastScheduled();
}
}
}
if (m_core_thread_running[core_id] != new_thread_id)
{
// If a thread was running on this core, and we'll schedule another one, unschedule the current one
thread_id_t thread_now = m_core_thread_running[core_id];
if (thread_now != INVALID_THREAD_ID)
{
m_thread_info[thread_now].setCoreRunning(INVALID_CORE_ID);
m_thread_info[thread_now].setLastScheduled(time);
moveThread(thread_now, INVALID_CORE_ID, time);
}
// Set core as running this thread *before* we call moveThread(), otherwise the HOOK_THREAD_RESUME callback for this
// thread might see an empty core, causing a recursive loop of reschedulings
m_core_thread_running[core_id] = new_thread_id;
// If we found a new thread to schedule, move it here
if (new_thread_id != INVALID_THREAD_ID)
{
// If thread was running somewhere else: let that core know
if (m_thread_info[new_thread_id].isRunning())
m_core_thread_running[m_thread_info[new_thread_id].getCoreRunning()] = INVALID_THREAD_ID;
// Move thread to this core
m_thread_info[new_thread_id].setCoreRunning(core_id);
moveThread(new_thread_id, core_id, time);
}
}
m_quantum_left[core_id] = m_quantum;
}
String SchedulerPinnedBase::ThreadInfo::getAffinityString() const
{
std::stringstream ss;
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (hasAffinity(core_id))
{
if (ss.str().size() > 0)
ss << ",";
ss << core_id;
}
}
return String(ss.str().c_str());
}
void SchedulerPinnedBase::printState()
{
printf("thread state:");
for(thread_id_t thread_id = 0; thread_id < (thread_id_t)Sim()->getThreadManager()->getNumThreads(); ++thread_id)
{
char state;
switch(Sim()->getThreadManager()->getThreadState(thread_id))
{
case Core::INITIALIZING:
state = 'I';
break;
case Core::RUNNING:
state = 'R';
break;
case Core::STALLED:
state = 'S';
break;
case Core::SLEEPING:
state = 's';
break;
case Core::WAKING_UP:
state = 'W';
break;
case Core::IDLE:
state = 'I';
break;
case Core::BROKEN:
state = 'B';
break;
case Core::NUM_STATES:
default:
state = '?';
break;
}
if (m_thread_info[thread_id].isRunning())
{
printf(" %c@%d", state, m_thread_info[thread_id].getCoreRunning());
}
else
{
printf(" %c%c%s", state, m_threads_runnable[thread_id] ? '+' : '_', m_thread_info[thread_id].getAffinityString().c_str());
}
}
printf(" -- core state:");
for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id)
{
if (m_core_thread_running[core_id] == INVALID_THREAD_ID)
printf(" __");
else
printf(" %2d", m_core_thread_running[core_id]);
}
printf("\n");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: interaction.hxx,v $
* $Revision: 1.6 $
*
* 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 _COMPHELPER_INTERACTION_HXX_
#define _COMPHELPER_INTERACTION_HXX_
#include <comphelper/uno3.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/task/XInteractionApprove.hpp>
#include <com/sun/star/task/XInteractionDisapprove.hpp>
#include <com/sun/star/task/XInteractionAbort.hpp>
#include <com/sun/star/task/XInteractionRetry.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include "comphelper/comphelperdllapi.h"
//.........................................................................
namespace comphelper
{
//.........................................................................
//=========================================================================
//= OInteractionSelect
//=========================================================================
/** base class for concrete XInteractionContinuation implementations.<p/>
Instances of the classes maintain a flag indicating if the handler was called.
*/
class OInteractionSelect
{
sal_Bool m_bSelected : 1; /// indicates if the select event occured
protected:
OInteractionSelect() : m_bSelected(sal_False) { }
public:
/// determines whether or not this handler was selected
sal_Bool wasSelected() const { return m_bSelected; }
/// resets the state to "not selected", so you may reuse the handler
void reset() { m_bSelected = sal_False; }
protected:
void implSelected() { m_bSelected = sal_True; }
};
//=========================================================================
//= OInteraction
//=========================================================================
/** template for instantiating concret interaction handlers<p/>
the template argument must eb an interface derived from XInteractionContinuation
*/
template <class INTERACTION>
class OInteraction
:public ::cppu::WeakImplHelper1< INTERACTION >
,public OInteractionSelect
{
public:
OInteraction() { }
// XInteractionContinuation
virtual void SAL_CALL select( ) throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
template <class INTERACTION>
void SAL_CALL OInteraction< INTERACTION >::select( ) throw(::com::sun::star::uno::RuntimeException)
{
implSelected();
}
//=========================================================================
//= OInteractionApprove
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionApprove > OInteractionApprove;
//=========================================================================
//= OInteractionDispprove
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionDisapprove > OInteractionDisapprove;
//=========================================================================
//= OInteractionAbort
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionAbort > OInteractionAbort;
//=========================================================================
//= OInteractionRetry
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionRetry > OInteractionRetry;
//=========================================================================
//= OInteractionRequest
//=========================================================================
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::task::XInteractionRequest
> OInteractionRequest_Base;
/** implements an interaction request (<type scope="com.sun.star.task">XInteractionRequest</type>)<p/>
at run time, you can freely add any interaction continuation objects
*/
class COMPHELPER_DLLPUBLIC OInteractionRequest : public OInteractionRequest_Base
{
::com::sun::star::uno::Any
m_aRequest; /// the request we represent
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >
m_aContinuations; /// all registered continuations
public:
OInteractionRequest(const ::com::sun::star::uno::Any& _rRequestDescription);
/// add a new continuation
void addContinuation(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >& _rxContinuation);
/// clear all continuations
void clearContinuations();
// XInteractionRequest
virtual ::com::sun::star::uno::Any SAL_CALL getRequest( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations( ) throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // _COMPHELPER_INTERACTION_HXX_
<commit_msg>INTEGRATION: CWS dba30c (1.6.20); FILE MERGED 2008/05/13 06:50:00 fs 1.6.20.1: joining changes from CWS odbmacros3 to CWS dba30c: 2008/05/11 20:59:01 fs 1.6.8.1: +OInteractionPassword<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: interaction.hxx,v $
* $Revision: 1.7 $
*
* 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 _COMPHELPER_INTERACTION_HXX_
#define _COMPHELPER_INTERACTION_HXX_
#include <comphelper/uno3.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/task/XInteractionApprove.hpp>
#include <com/sun/star/task/XInteractionDisapprove.hpp>
#include <com/sun/star/task/XInteractionAbort.hpp>
#include <com/sun/star/task/XInteractionRetry.hpp>
#include <com/sun/star/task/XInteractionPassword.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include "comphelper/comphelperdllapi.h"
//.........................................................................
namespace comphelper
{
//.........................................................................
//=========================================================================
//= OInteractionSelect
//=========================================================================
/** base class for concrete XInteractionContinuation implementations.<p/>
Instances of the classes maintain a flag indicating if the handler was called.
*/
class OInteractionSelect
{
sal_Bool m_bSelected : 1; /// indicates if the select event occured
protected:
OInteractionSelect() : m_bSelected(sal_False) { }
public:
/// determines whether or not this handler was selected
sal_Bool wasSelected() const { return m_bSelected; }
/// resets the state to "not selected", so you may reuse the handler
void reset() { m_bSelected = sal_False; }
protected:
void implSelected() { m_bSelected = sal_True; }
};
//=========================================================================
//= OInteraction
//=========================================================================
/** template for instantiating concret interaction handlers<p/>
the template argument must eb an interface derived from XInteractionContinuation
*/
template <class INTERACTION>
class OInteraction
:public ::cppu::WeakImplHelper1< INTERACTION >
,public OInteractionSelect
{
public:
OInteraction() { }
// XInteractionContinuation
virtual void SAL_CALL select( ) throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
template <class INTERACTION>
void SAL_CALL OInteraction< INTERACTION >::select( ) throw(::com::sun::star::uno::RuntimeException)
{
implSelected();
}
//=========================================================================
//= OInteractionApprove
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionApprove > OInteractionApprove;
//=========================================================================
//= OInteractionDispprove
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionDisapprove > OInteractionDisapprove;
//=========================================================================
//= OInteractionAbort
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionAbort > OInteractionAbort;
//=========================================================================
//= OInteractionRetry
//=========================================================================
typedef OInteraction< ::com::sun::star::task::XInteractionRetry > OInteractionRetry;
//=========================================================================
//= OInteractionPassword
//=========================================================================
class COMPHELPER_DLLPUBLIC OInteractionPassword : public OInteraction< ::com::sun::star::task::XInteractionPassword >
{
public:
OInteractionPassword()
{
}
OInteractionPassword( const ::rtl::OUString& _rInitialPassword )
:m_sPassword( _rInitialPassword )
{
}
// XInteractionPassword
virtual void SAL_CALL setPassword( const ::rtl::OUString& _Password ) throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getPassword( ) throw (::com::sun::star::uno::RuntimeException);
private:
::rtl::OUString m_sPassword;
};
//=========================================================================
//= OInteractionRequest
//=========================================================================
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::task::XInteractionRequest
> OInteractionRequest_Base;
/** implements an interaction request (<type scope="com.sun.star.task">XInteractionRequest</type>)<p/>
at run time, you can freely add any interaction continuation objects
*/
class COMPHELPER_DLLPUBLIC OInteractionRequest : public OInteractionRequest_Base
{
::com::sun::star::uno::Any
m_aRequest; /// the request we represent
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >
m_aContinuations; /// all registered continuations
public:
OInteractionRequest(const ::com::sun::star::uno::Any& _rRequestDescription);
/// add a new continuation
void addContinuation(const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >& _rxContinuation);
/// clear all continuations
void clearContinuations();
// XInteractionRequest
virtual ::com::sun::star::uno::Any SAL_CALL getRequest( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations( ) throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // _COMPHELPER_INTERACTION_HXX_
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::DefaultDevice;
template <int DataLayout>
static void test_evals()
{
Tensor<float, 2, DataLayout> input(3, 3);
Tensor<float, 1, DataLayout> kernel(2);
input.setRandom();
kernel.setRandom();
Tensor<float, 2, DataLayout> result(2,3);
result.setZero();
Eigen::array<Tensor<float, 2>::Index, 1> dims3{{0}};
typedef TensorEvaluator<decltype(input.convolve(kernel, dims3)), DefaultDevice> Evaluator;
Evaluator eval(input.convolve(kernel, dims3), DefaultDevice());
eval.evalTo(result.data());
EIGEN_STATIC_ASSERT(Evaluator::NumDims==2ul, YOU_MADE_A_PROGRAMMING_MISTAKE);
VERIFY_IS_EQUAL(eval.dimensions()[0], 2);
VERIFY_IS_EQUAL(eval.dimensions()[1], 3);
VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0) + input(1,0)*kernel(1)); // index 0
VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0) + input(1,1)*kernel(1)); // index 2
VERIFY_IS_APPROX(result(0,2), input(0,2)*kernel(0) + input(1,2)*kernel(1)); // index 4
VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0) + input(2,0)*kernel(1)); // index 1
VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0) + input(2,1)*kernel(1)); // index 3
VERIFY_IS_APPROX(result(1,2), input(1,2)*kernel(0) + input(2,2)*kernel(1)); // index 5
}
template <int DataLayout>
static void test_expr()
{
Tensor<float, 2, DataLayout> input(3, 3);
Tensor<float, 2, DataLayout> kernel(2, 2);
input.setRandom();
kernel.setRandom();
Tensor<float, 2, DataLayout> result(2,2);
Eigen::array<ptrdiff_t, 2> dims({0, 1});
result = input.convolve(kernel, dims);
VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0,0) + input(0,1)*kernel(0,1) +
input(1,0)*kernel(1,0) + input(1,1)*kernel(1,1));
VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0,0) + input(0,2)*kernel(0,1) +
input(1,1)*kernel(1,0) + input(1,2)*kernel(1,1));
VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0,0) + input(1,1)*kernel(0,1) +
input(2,0)*kernel(1,0) + input(2,1)*kernel(1,1));
VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0,0) + input(1,2)*kernel(0,1) +
input(2,1)*kernel(1,0) + input(2,2)*kernel(1,1));
}
template <int DataLayout>
static void test_modes() {
Tensor<float, 1, DataLayout> input(3);
Tensor<float, 1, DataLayout> kernel(3);
input(0) = 1.0f;
input(1) = 2.0f;
input(2) = 3.0f;
kernel(0) = 0.5f;
kernel(1) = 1.0f;
kernel(2) = 0.0f;
const Eigen::array<ptrdiff_t, 1> dims({0});
Eigen::array<std::pair<ptrdiff_t, ptrdiff_t>, 1> padding;
// Emulate VALID mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(0, 0);
Tensor<float, 1, DataLayout> valid(1);
valid = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(valid.dimension(0), 1);
VERIFY_IS_APPROX(valid(0), 2.5f);
// Emulate SAME mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(1, 1);
Tensor<float, 1, DataLayout> same(3);
same = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(same.dimension(0), 3);
VERIFY_IS_APPROX(same(0), 1.0f);
VERIFY_IS_APPROX(same(1), 2.5f);
VERIFY_IS_APPROX(same(2), 4.0f);
// Emulate FULL mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(2, 2);
Tensor<float, 1, DataLayout> full(5);
full = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(full.dimension(0), 5);
VERIFY_IS_APPROX(full(0), 0.0f);
VERIFY_IS_APPROX(full(1), 1.0f);
VERIFY_IS_APPROX(full(2), 2.5f);
VERIFY_IS_APPROX(full(3), 4.0f);
VERIFY_IS_APPROX(full(4), 1.5f);
}
template <int DataLayout>
static void test_strides() {
Tensor<float, 1, DataLayout> input(13);
Tensor<float, 1, DataLayout> kernel(3);
input.setRandom();
kernel.setRandom();
const Eigen::array<ptrdiff_t, 1> dims({0});
const Eigen::array<ptrdiff_t, 1> stride_of_3({3});
const Eigen::array<ptrdiff_t, 1> stride_of_2({2});
Tensor<float, 1, DataLayout> result;
result = input.stride(stride_of_3).convolve(kernel, dims).stride(stride_of_2);
VERIFY_IS_EQUAL(result.dimension(0), 2);
VERIFY_IS_APPROX(result(0), (input(0)*kernel(0) + input(3)*kernel(1) +
input(6)*kernel(2)));
VERIFY_IS_APPROX(result(1), (input(6)*kernel(0) + input(9)*kernel(1) +
input(12)*kernel(2)));
}
void test_cxx11_tensor_convolution()
{
CALL_SUBTEST(test_evals<ColMajor>());
CALL_SUBTEST(test_evals<RowMajor>());
CALL_SUBTEST(test_expr<ColMajor>());
CALL_SUBTEST(test_expr<RowMajor>());
CALL_SUBTEST(test_modes<ColMajor>());
CALL_SUBTEST(test_modes<RowMajor>());
CALL_SUBTEST(test_strides<ColMajor>());
CALL_SUBTEST(test_strides<RowMajor>());
}
<commit_msg>Updated the cxx11_tensor_convolution test to avoid using cxx11 features. This should enable the test to compile with gcc 4.7 and older<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::DefaultDevice;
template <int DataLayout>
static void test_evals()
{
Tensor<float, 2, DataLayout> input(3, 3);
Tensor<float, 1, DataLayout> kernel(2);
input.setRandom();
kernel.setRandom();
Tensor<float, 2, DataLayout> result(2,3);
result.setZero();
Eigen::array<Tensor<float, 2>::Index, 1> dims3{{0}};
typedef TensorEvaluator<decltype(input.convolve(kernel, dims3)), DefaultDevice> Evaluator;
Evaluator eval(input.convolve(kernel, dims3), DefaultDevice());
eval.evalTo(result.data());
EIGEN_STATIC_ASSERT(Evaluator::NumDims==2ul, YOU_MADE_A_PROGRAMMING_MISTAKE);
VERIFY_IS_EQUAL(eval.dimensions()[0], 2);
VERIFY_IS_EQUAL(eval.dimensions()[1], 3);
VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0) + input(1,0)*kernel(1)); // index 0
VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0) + input(1,1)*kernel(1)); // index 2
VERIFY_IS_APPROX(result(0,2), input(0,2)*kernel(0) + input(1,2)*kernel(1)); // index 4
VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0) + input(2,0)*kernel(1)); // index 1
VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0) + input(2,1)*kernel(1)); // index 3
VERIFY_IS_APPROX(result(1,2), input(1,2)*kernel(0) + input(2,2)*kernel(1)); // index 5
}
template <int DataLayout>
static void test_expr()
{
Tensor<float, 2, DataLayout> input(3, 3);
Tensor<float, 2, DataLayout> kernel(2, 2);
input.setRandom();
kernel.setRandom();
Tensor<float, 2, DataLayout> result(2,2);
Eigen::array<ptrdiff_t, 2> dims;
dims[0] = 0;
dims[1] = 1;
result = input.convolve(kernel, dims);
VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0,0) + input(0,1)*kernel(0,1) +
input(1,0)*kernel(1,0) + input(1,1)*kernel(1,1));
VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0,0) + input(0,2)*kernel(0,1) +
input(1,1)*kernel(1,0) + input(1,2)*kernel(1,1));
VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0,0) + input(1,1)*kernel(0,1) +
input(2,0)*kernel(1,0) + input(2,1)*kernel(1,1));
VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0,0) + input(1,2)*kernel(0,1) +
input(2,1)*kernel(1,0) + input(2,2)*kernel(1,1));
}
template <int DataLayout>
static void test_modes() {
Tensor<float, 1, DataLayout> input(3);
Tensor<float, 1, DataLayout> kernel(3);
input(0) = 1.0f;
input(1) = 2.0f;
input(2) = 3.0f;
kernel(0) = 0.5f;
kernel(1) = 1.0f;
kernel(2) = 0.0f;
Eigen::array<ptrdiff_t, 1> dims;
dims[0] = 0;
Eigen::array<std::pair<ptrdiff_t, ptrdiff_t>, 1> padding;
// Emulate VALID mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(0, 0);
Tensor<float, 1, DataLayout> valid(1);
valid = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(valid.dimension(0), 1);
VERIFY_IS_APPROX(valid(0), 2.5f);
// Emulate SAME mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(1, 1);
Tensor<float, 1, DataLayout> same(3);
same = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(same.dimension(0), 3);
VERIFY_IS_APPROX(same(0), 1.0f);
VERIFY_IS_APPROX(same(1), 2.5f);
VERIFY_IS_APPROX(same(2), 4.0f);
// Emulate FULL mode (as defined in
// http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
padding[0] = std::make_pair(2, 2);
Tensor<float, 1, DataLayout> full(5);
full = input.pad(padding).convolve(kernel, dims);
VERIFY_IS_EQUAL(full.dimension(0), 5);
VERIFY_IS_APPROX(full(0), 0.0f);
VERIFY_IS_APPROX(full(1), 1.0f);
VERIFY_IS_APPROX(full(2), 2.5f);
VERIFY_IS_APPROX(full(3), 4.0f);
VERIFY_IS_APPROX(full(4), 1.5f);
}
template <int DataLayout>
static void test_strides() {
Tensor<float, 1, DataLayout> input(13);
Tensor<float, 1, DataLayout> kernel(3);
input.setRandom();
kernel.setRandom();
Eigen::array<ptrdiff_t, 1> dims;
dims[0] = 0;
Eigen::array<ptrdiff_t, 1> stride_of_3;
stride_of_3[0] = 3;
Eigen::array<ptrdiff_t, 1> stride_of_2;
stride_of_2[0] = 2;
Tensor<float, 1, DataLayout> result;
result = input.stride(stride_of_3).convolve(kernel, dims).stride(stride_of_2);
VERIFY_IS_EQUAL(result.dimension(0), 2);
VERIFY_IS_APPROX(result(0), (input(0)*kernel(0) + input(3)*kernel(1) +
input(6)*kernel(2)));
VERIFY_IS_APPROX(result(1), (input(6)*kernel(0) + input(9)*kernel(1) +
input(12)*kernel(2)));
}
void test_cxx11_tensor_convolution()
{
CALL_SUBTEST(test_evals<ColMajor>());
CALL_SUBTEST(test_evals<RowMajor>());
CALL_SUBTEST(test_expr<ColMajor>());
CALL_SUBTEST(test_expr<RowMajor>());
CALL_SUBTEST(test_modes<ColMajor>());
CALL_SUBTEST(test_modes<RowMajor>());
CALL_SUBTEST(test_strides<ColMajor>());
CALL_SUBTEST(test_strides<RowMajor>());
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// 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/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <Eigen/CXX11/Tensor>
#include "thread/threadpool.h"
using Eigen::Tensor;
void test_cxx11_tensor_thread_pool()
{
Eigen::Tensor<float, 3> in1(Eigen::array<ptrdiff_t, 3>(2,3,7));
Eigen::Tensor<float, 3> in2(Eigen::array<ptrdiff_t, 3>(2,3,7));
Eigen::Tensor<float, 3> out(Eigen::array<ptrdiff_t, 3>(2,3,7));
in1.setRandom();
in2.setRandom();
ThreadPool thread_pool(2);
thread_pool.StartWorkers();
Eigen::ThreadPoolDevice thread_pool_device(&thread_pool, 3);
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(Eigen::array<ptrdiff_t, 3>(i,j,k)), in1(Eigen::array<ptrdiff_t, 3>(i,j,k)) + in2(Eigen::array<ptrdiff_t, 3>(i,j,k)) * 3.14f);
}
}
}
}
<commit_msg>Pulled latest changes from the main branch<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// 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/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
void test_cxx11_tensor_thread_pool()
{
Eigen::Tensor<float, 3> in1(Eigen::array<ptrdiff_t, 3>(2,3,7));
Eigen::Tensor<float, 3> in2(Eigen::array<ptrdiff_t, 3>(2,3,7));
Eigen::Tensor<float, 3> out(Eigen::array<ptrdiff_t, 3>(2,3,7));
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(3);
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(Eigen::array<ptrdiff_t, 3>(i,j,k)), in1(Eigen::array<ptrdiff_t, 3>(i,j,k)) + in2(Eigen::array<ptrdiff_t, 3>(i,j,k)) * 3.14f);
}
}
}
}
<|endoftext|> |
<commit_before>#include "StableHeaders.h"
#include "PluginAPI.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include <QtXml>
#include <iostream>
#include <vector>
std::string WStringToString(const std::wstring &str)
{
std::vector<char> c((str.length()+1)*4);
wcstombs(&c[0], str.c_str(), c.size()-1);
return &c[0];
}
std::string GetErrorString(int error)
{
#ifdef WIN32
void *lpMsgBuf = 0;
HRESULT hresult = HRESULT_FROM_WIN32(error);
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0, hresult, 0 /*Default language*/, (LPTSTR) &lpMsgBuf, 0, 0);
// Copy message to C++ -style string, since the data need to be freed before return.
#ifdef UNICODE
std::wstringstream ss;
#else
std::stringstream ss;
#endif
ss << (LPTSTR)lpMsgBuf << "(" << error << ")";
LocalFree(lpMsgBuf);
#ifdef UNICODE
return WStringToString(ss.str());
#else
return ss.str();
#endif
#else
std::stringstream ss;
ss << strerror(error) << "(" << error << ")";
return ss.str();
#endif
}
PluginAPI::PluginAPI(Foundation::Framework *owner_)
:owner(owner_)
{
}
typedef void (*TundraPluginMainSignature)(Foundation::Framework *owner);
void PluginAPI::LoadPlugin(const QString &filename)
{
#ifdef _DEBUG
QString path = "plugins/" + filename.trimmed() + "d.dll";
#else
QString path = "plugins/" + filename.trimmed() + ".dll";
#endif
path = path.replace("/", "\\");
LogInfo("Loading up plugin \"" + filename + "\".");
///\todo Cross-platform -> void* & dlopen.
HMODULE module = LoadLibraryA(path.toStdString().c_str());
if (module == NULL)
{
DWORD errorCode = GetLastError(); ///\todo ToString.
LogError("Failed to load plugin from file \"" + path + "\": Error " + GetErrorString(errorCode).c_str() + "!");
return;
}
TundraPluginMainSignature mainEntryPoint = (TundraPluginMainSignature)GetProcAddress(module, "TundraPluginMain");
if (mainEntryPoint == NULL)
{
DWORD errorCode = GetLastError(); ///\todo ToString.
LogError("Failed to find plugin startup function 'TundraPluginMain' from plugin file \"" + path + "\": Error " + GetErrorString(errorCode).c_str() + "!");
return;
}
LogInfo("Starting up plugin \"" + path + "\".");
mainEntryPoint(owner);
}
void PluginAPI::LoadPluginsFromXML(const QString &pluginListFilename)
{
QDomDocument doc("plugins");
QFile file(pluginListFilename);
if (!file.open(QIODevice::ReadOnly))
return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomNode n = docElem.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement(); // try to convert the node to an element.
if (!e.isNull() && e.tagName() == "plugin" && e.hasAttribute("path"))
{
QString pluginPath = e.attribute("path");
LoadPlugin(pluginPath);
}
n = n.nextSibling();
}
}
<commit_msg>Added missing error reporting to plugins.xml parsing.<commit_after>#include "StableHeaders.h"
#include "PluginAPI.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include <QtXml>
#include <iostream>
#include <vector>
std::string WStringToString(const std::wstring &str)
{
std::vector<char> c((str.length()+1)*4);
wcstombs(&c[0], str.c_str(), c.size()-1);
return &c[0];
}
std::string GetErrorString(int error)
{
#ifdef WIN32
void *lpMsgBuf = 0;
HRESULT hresult = HRESULT_FROM_WIN32(error);
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0, hresult, 0 /*Default language*/, (LPTSTR) &lpMsgBuf, 0, 0);
// Copy message to C++ -style string, since the data need to be freed before return.
#ifdef UNICODE
std::wstringstream ss;
#else
std::stringstream ss;
#endif
ss << (LPTSTR)lpMsgBuf << "(" << error << ")";
LocalFree(lpMsgBuf);
#ifdef UNICODE
return WStringToString(ss.str());
#else
return ss.str();
#endif
#else
std::stringstream ss;
ss << strerror(error) << "(" << error << ")";
return ss.str();
#endif
}
PluginAPI::PluginAPI(Foundation::Framework *owner_)
:owner(owner_)
{
}
typedef void (*TundraPluginMainSignature)(Foundation::Framework *owner);
void PluginAPI::LoadPlugin(const QString &filename)
{
#ifdef _DEBUG
QString path = "plugins/" + filename.trimmed() + "d.dll";
#else
QString path = "plugins/" + filename.trimmed() + ".dll";
#endif
path = path.replace("/", "\\");
LogInfo("Loading up plugin \"" + filename + "\".");
///\todo Cross-platform -> void* & dlopen.
HMODULE module = LoadLibraryA(path.toStdString().c_str());
if (module == NULL)
{
DWORD errorCode = GetLastError(); ///\todo ToString.
LogError("Failed to load plugin from file \"" + path + "\": Error " + GetErrorString(errorCode).c_str() + "!");
return;
}
TundraPluginMainSignature mainEntryPoint = (TundraPluginMainSignature)GetProcAddress(module, "TundraPluginMain");
if (mainEntryPoint == NULL)
{
DWORD errorCode = GetLastError(); ///\todo ToString.
LogError("Failed to find plugin startup function 'TundraPluginMain' from plugin file \"" + path + "\": Error " + GetErrorString(errorCode).c_str() + "!");
return;
}
LogInfo("Starting up plugin \"" + path + "\".");
mainEntryPoint(owner);
}
void PluginAPI::LoadPluginsFromXML(const QString &pluginListFilename)
{
QDomDocument doc("plugins");
QFile file(pluginListFilename);
if (!file.open(QIODevice::ReadOnly))
{
LogError("PluginAPI::LoadPluginsFromXML: Failed to open file \"" + pluginListFilename + "\"!");
return;
}
if (!doc.setContent(&file))
{
LogError("PluginAPI::LoadPluginsFromXML: Failed to parse XML file \"" + pluginListFilename + "\"!");
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomNode n = docElem.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement(); // try to convert the node to an element.
if (!e.isNull() && e.tagName() == "plugin" && e.hasAttribute("path"))
{
QString pluginPath = e.attribute("path");
LoadPlugin(pluginPath);
}
n = n.nextSibling();
}
}
<|endoftext|> |
<commit_before>#pragma once
/// This class prevents its inheritors from being copied.
class NonCopyable
{
protected:
NonCopyable() noexcept = default;
~NonCopyable() = default;
NonCopyable(NonCopyable&&) noexcept = default;
NonCopyable& operator=(NonCopyable&&) noexcept = default;
private:
NonCopyable(const NonCopyable&) noexcept = delete;
NonCopyable& operator=(const NonCopyable&) noexcept = delete;
};
<commit_msg>Delete NonCopyable since it's no longer relevant<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016, Integrity Project Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Integrity Project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE
*/
/*
* sarray.inl
*
* Implementation code of the cSArray class.
*
* Author: Elad Raz <[email protected]>
*/
#include "xStl/types.h"
#include "xStl/data/array.h"
#include "xStl/except/exception.h"
#include "xStl/utils/algorithm.h"
#include "xStl/stream/basicIO.h"
#include "xStl/os/os.h"
static void __memcpy(void* dest,
const void* src,
uint size
/*cWaitable wait*/)
{
// reimplementing memcpy to avoid reentry
cOS::memcpy(dest, src, size);
}
template <class T>
cSArray<T>::cSArray(uint numberOfElements /* = 0*/,
uint pageSize /* = 0*/) :
cArray<T>(numberOfElements, pageSize)
{
}
template <class T>
cSArray<T>::cSArray(const T* staticArray,
uint length,
uint pageSize /* = 0 */) :
cArray<T>(length, pageSize)
{
ASSERT(staticArray != NULL);
// Copy the array using memcpy
__memcpy(this->m_array, staticArray, this->m_size * sizeof(T));
}
template <class T>
cSArray<T>::cSArray(const cSArray & other)
{
// Create empty array
cSArray<T>::initArray(other.m_pageSize);
// Create a new empty array at a default size and set the data
cSArray<T>::copyFrom(other);
}
template <class T>
void cSArray<T>::copyFrom(const cArray<T> &other)
{
/* Fast copy array */
this->freeArray();
changeSize(other.getSize());
__memcpy(this->m_array, other.getBuffer(), this->m_size * sizeof(T));
}
template <class T>
void cSArray<T>::changeSize(uint newSize,
bool preserveMemory /*= true*/)
{
if ((newSize != 0) && (preserveMemory))
{
uint new_alloc = this->pageRound(newSize);
T* buffer;
/* Create a new buffer and copy the data to it, if needed */
if ((uint)t_abs((int)new_alloc - (int)this->m_alocatedArray) >=
this->m_pageSize)
{
/* Need to realloc the buffer */
buffer = new T[new_alloc];
if (buffer == NULL)
{
XSTL_THROW(cException, EXCEPTION_OUT_OF_MEM);
}
if (this->m_array != NULL)
{
__memcpy(buffer, this->m_array,
t_min(newSize, this->m_size) * sizeof(T));
delete [] this->m_array;
}
/* Assign the new array */
this->m_array = buffer;
this->m_size = newSize;
this->m_alocatedArray = new_alloc;
} else
{
/* Just increase the space needed */
this->m_size = newSize;
}
} else
{
cArray<T>::changeSize(newSize, preserveMemory);
}
}
template <class T>
void cSArray<T>::append(const T& object)
{
changeSize(this->m_size + 1);
__memcpy(this->m_array + this->m_size - 1, &object, sizeof(T));
}
template <class T>
void cSArray<T>::append(const cArray<T>& array)
{
// Save the rest of the bytes left.
uint org_size = this->m_size;
uint add_size = array.getSize();
// Change the size to the size of both array.
changeSize(this->m_size + array.getSize());
// Copy the elements
__memcpy(this->m_array + org_size, array.getBuffer(), sizeof(T)*add_size);
}
template <class T>
void cSArray<T>::copyRange(cArray<T>& other,
uint startLocation,
uint count)
{
changeSize(count, false);
__memcpy(this->m_array, other.getBuffer() + startLocation, count * sizeof(T));
}
template <class T>
cSArray<T>& cSArray<T>::operator = (const cSArray<T>& other)
{
if (this != &other)
{
// If and only if, the class are DIFFRENT then
// preform the assignment.
copyFrom(other);
return *this;
}
return *this;
}
template <class T>
cSArray<T> cSArray<T>::operator + (const cSArray<T>& other)
{
// Create new object, append the data and return it.
return (cSArray<T>(*this) += other);
}
template <class T>
cSArray<T> cSArray<T>::operator + (const T & object)
{
// Create new object, append the data and return it.
return (cSArray<T>(*this) += object);
}
template <class T>
cSArray<T>& cSArray<T>::operator +=(const cSArray<T>& other)
{
append(other);
return *this;
}
template <class T>
cSArray<T>& cSArray<T>::operator +=(const T & object)
{
append(object);
return *this;
}
template <class T>
bool cSArray<T>::operator == (const cSArray<T>& other) const
{
if (other.m_size != this->m_size)
return false;
return memcmp(this->m_array, other.m_array,
sizeof(T) * this->m_size) == 0;
}
template <class T>
bool cSArray<T>::operator < (const cSArray<T>& other) const
{
if (other.m_size != this->m_size)
return this->m_size < other.m_size;
return memcmp(this->m_array, other.m_array,
sizeof(T) * this->m_size) < 0;
}
template <class T>
bool cSArray<T>::isValid() const
{
return true;
}
// gcc work around. gcc can't access internal function of declared class
// in order to overide this behavior we will use global static functions that
// implemens streamReadUint32/streamWriteUint32 and pipeRead/pipeWrite with interface
#ifdef XSTL_LINUX
extern "C" void gccLinuxStreamReadUint32(basicInput& inputStream, uint32& dword);
extern "C" void gccLinuxStreamWriteUint32(basicOutput& outputStream, uint32& dword);
extern "C" uint gccLinuxStreamPipeRead(basicInput& inputStream, void *buffer, const uint length);
extern "C" void gccLinuxStreamPipeWrite(basicOutput& outputStream, void *buffer, const uint length);
#endif
template <class T>
void cSArray<T>::deserialize(basicInput& inputStream)
{
uint32 count;
#ifdef XSTL_LINUX
gccLinuxStreamReadUint32(inputStream, count);
#else
inputStream.streamReadUint32(count);
#endif
changeSize(count, false);
#ifdef XSTL_LINUX
gccLinuxStreamPipeRead(inputStream, (void*)this->m_array, sizeof(T) * count);
#else
inputStream.pipeRead((void*)this->m_array, sizeof(T) * count);
#endif
}
template <class T>
void cSArray<T>::serialize(basicOutput& outputStream) const
{
uint32 size = (uint32)(this->m_size);
// 64 bit size protection
#ifdef XSTL_64BIT
if (this->m_size > 0xFFFFFFFFL)
{
XSTL_THROW(cException, EXCEPTION_OUT_OF_RANGE);
}
#endif
#ifdef XSTL_LINUX
gccLinuxStreamWriteUint32(outputStream, size);
gccLinuxStreamPipeWrite(outputStream, (void*)this->m_array, sizeof(T) * size);
#else
outputStream.streamWriteUint32(size);
outputStream.pipeWrite((void*)this->m_array, sizeof(T) * size);
#endif
}
<commit_msg>xStl: sarray: Removing unneeded __memcpy<commit_after>/*
* Copyright (c) 2008-2016, Integrity Project Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Integrity Project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE
*/
/*
* sarray.inl
*
* Implementation code of the cSArray class.
*
* Author: Elad Raz <[email protected]>
*/
#include "xStl/types.h"
#include "xStl/data/array.h"
#include "xStl/except/exception.h"
#include "xStl/utils/algorithm.h"
#include "xStl/stream/basicIO.h"
#include "xStl/os/os.h"
template <class T>
cSArray<T>::cSArray(uint numberOfElements /* = 0*/,
uint pageSize /* = 0*/) :
cArray<T>(numberOfElements, pageSize)
{
}
template <class T>
cSArray<T>::cSArray(const T* staticArray,
uint length,
uint pageSize /* = 0 */) :
cArray<T>(length, pageSize)
{
ASSERT(staticArray != NULL);
// Copy the array using memcpy
cOS::memcpy(this->m_array, staticArray, this->m_size * sizeof(T));
}
template <class T>
cSArray<T>::cSArray(const cSArray & other)
{
// Create empty array
cSArray<T>::initArray(other.m_pageSize);
// Create a new empty array at a default size and set the data
cSArray<T>::copyFrom(other);
}
template <class T>
void cSArray<T>::copyFrom(const cArray<T> &other)
{
/* Fast copy array */
this->freeArray();
changeSize(other.getSize());
cOS::memcpy(this->m_array, other.getBuffer(), this->m_size * sizeof(T));
}
template <class T>
void cSArray<T>::changeSize(uint newSize,
bool preserveMemory /*= true*/)
{
if ((newSize != 0) && (preserveMemory))
{
uint new_alloc = this->pageRound(newSize);
T* buffer;
/* Create a new buffer and copy the data to it, if needed */
if ((uint)t_abs((int)new_alloc - (int)this->m_alocatedArray) >=
this->m_pageSize)
{
/* Need to realloc the buffer */
buffer = new T[new_alloc];
if (buffer == NULL)
{
XSTL_THROW(cException, EXCEPTION_OUT_OF_MEM);
}
if (this->m_array != NULL)
{
cOS::memcpy(buffer, this->m_array,
t_min(newSize, this->m_size) * sizeof(T));
delete [] this->m_array;
}
/* Assign the new array */
this->m_array = buffer;
this->m_size = newSize;
this->m_alocatedArray = new_alloc;
} else
{
/* Just increase the space needed */
this->m_size = newSize;
}
} else
{
cArray<T>::changeSize(newSize, preserveMemory);
}
}
template <class T>
void cSArray<T>::append(const T& object)
{
changeSize(this->m_size + 1);
cOS::memcpy(this->m_array + this->m_size - 1, &object, sizeof(T));
}
template <class T>
void cSArray<T>::append(const cArray<T>& array)
{
// Save the rest of the bytes left.
uint org_size = this->m_size;
uint add_size = array.getSize();
// Change the size to the size of both array.
changeSize(this->m_size + array.getSize());
// Copy the elements
cOS::memcpy(this->m_array + org_size, array.getBuffer(), sizeof(T)*add_size);
}
template <class T>
void cSArray<T>::copyRange(cArray<T>& other,
uint startLocation,
uint count)
{
changeSize(count, false);
cOS::memcpy(this->m_array, other.getBuffer() + startLocation, count * sizeof(T));
}
template <class T>
cSArray<T>& cSArray<T>::operator = (const cSArray<T>& other)
{
if (this != &other)
{
// If and only if, the class are DIFFRENT then
// preform the assignment.
copyFrom(other);
return *this;
}
return *this;
}
template <class T>
cSArray<T> cSArray<T>::operator + (const cSArray<T>& other)
{
// Create new object, append the data and return it.
return (cSArray<T>(*this) += other);
}
template <class T>
cSArray<T> cSArray<T>::operator + (const T & object)
{
// Create new object, append the data and return it.
return (cSArray<T>(*this) += object);
}
template <class T>
cSArray<T>& cSArray<T>::operator +=(const cSArray<T>& other)
{
append(other);
return *this;
}
template <class T>
cSArray<T>& cSArray<T>::operator +=(const T & object)
{
append(object);
return *this;
}
template <class T>
bool cSArray<T>::operator == (const cSArray<T>& other) const
{
if (other.m_size != this->m_size)
return false;
return memcmp(this->m_array, other.m_array,
sizeof(T) * this->m_size) == 0;
}
template <class T>
bool cSArray<T>::operator < (const cSArray<T>& other) const
{
if (other.m_size != this->m_size)
return this->m_size < other.m_size;
return memcmp(this->m_array, other.m_array,
sizeof(T) * this->m_size) < 0;
}
template <class T>
bool cSArray<T>::isValid() const
{
return true;
}
// gcc work around. gcc can't access internal function of declared class
// in order to overide this behavior we will use global static functions that
// implemens streamReadUint32/streamWriteUint32 and pipeRead/pipeWrite with interface
#ifdef XSTL_LINUX
extern "C" void gccLinuxStreamReadUint32(basicInput& inputStream, uint32& dword);
extern "C" void gccLinuxStreamWriteUint32(basicOutput& outputStream, uint32& dword);
extern "C" uint gccLinuxStreamPipeRead(basicInput& inputStream, void *buffer, const uint length);
extern "C" void gccLinuxStreamPipeWrite(basicOutput& outputStream, void *buffer, const uint length);
#endif
template <class T>
void cSArray<T>::deserialize(basicInput& inputStream)
{
uint32 count;
#ifdef XSTL_LINUX
gccLinuxStreamReadUint32(inputStream, count);
#else
inputStream.streamReadUint32(count);
#endif
changeSize(count, false);
#ifdef XSTL_LINUX
gccLinuxStreamPipeRead(inputStream, (void*)this->m_array, sizeof(T) * count);
#else
inputStream.pipeRead((void*)this->m_array, sizeof(T) * count);
#endif
}
template <class T>
void cSArray<T>::serialize(basicOutput& outputStream) const
{
uint32 size = (uint32)(this->m_size);
// 64 bit size protection
#ifdef XSTL_64BIT
if (this->m_size > 0xFFFFFFFFL)
{
XSTL_THROW(cException, EXCEPTION_OUT_OF_RANGE);
}
#endif
#ifdef XSTL_LINUX
gccLinuxStreamWriteUint32(outputStream, size);
gccLinuxStreamPipeWrite(outputStream, (void*)this->m_array, sizeof(T) * size);
#else
outputStream.streamWriteUint32(size);
outputStream.pipeWrite((void*)this->m_array, sizeof(T) * size);
#endif
}
<|endoftext|> |
<commit_before>#include "Audio.h"
#include <limits.h>
#include <FMOD\fmod.hpp>
struct AudioObject
{
FMOD::Channel* sound;
};
FMOD::System* system;
void Audio_Init()
{
FMOD::System_Create(&system);
if (system)
{
system->init(32, FMOD_INIT_NORMAL, 0);
}
}
void Audio_Destroy()
{
if (system)
system->release();
}
void Audio_Update(float dt)
{
if (system)
system->update();
}
void Audio_Play(char* filename, AudioObject* pAudioObject, float volume /*= 0.5f*/, bool loop /*= false*/)
{
pAudioObject = new AudioObject();
pAudioObject->sound = nullptr;
FMOD::Sound* sound;
system->createSound(filename, FMOD_SOFTWARE, 0, &sound);
sound->setLoopCount(INT_MAX * (int)loop);
system->playSound(FMOD_CHANNEL_FREE, sound, false, &pAudioObject->sound);
pAudioObject->sound->setVolume(volume);
}
void Audio_Cleanup(AudioObject* pAudioObject)
{
pAudioObject->sound->stop();
FMOD::Sound* sound;
pAudioObject->sound->getCurrentSound(&sound);
sound->release();
}
bool Audio_IsPlaying(AudioObject* pAudioObject)
{
bool success = false;
if (pAudioObject == nullptr || pAudioObject->sound == nullptr)
return success;
pAudioObject->sound->isPlaying(&success);
return success;
}
void Audio_StopPlaying(AudioObject* pAudioObject)
{
if (pAudioObject == nullptr || pAudioObject->sound == nullptr)
return;
pAudioObject->sound->stop();
}<commit_msg>Maybe we loop now, who knows.<commit_after>#include "Audio.h"
#include <limits.h>
#include <FMOD\fmod.hpp>
struct AudioObject
{
FMOD::Channel* sound;
};
FMOD::System* system;
void Audio_Init()
{
FMOD::System_Create(&system);
if (system)
{
system->init(32, FMOD_INIT_NORMAL, 0);
}
}
void Audio_Destroy()
{
if (system)
system->release();
}
void Audio_Update(float dt)
{
if (system)
system->update();
}
void Audio_Play(char* filename, AudioObject* pAudioObject, float volume /*= 0.5f*/, bool loop /*= false*/)
{
pAudioObject = new AudioObject();
pAudioObject->sound = nullptr;
FMOD::Sound* sound;
system->createSound(filename, FMOD_SOFTWARE, 0, &sound);
sound->setLoopCount(INT_MAX * (int)loop);
sound->setMode(loop ? FMOD_LOOP_NORMAL : FMOD_LOOP_OFF);
system->playSound(FMOD_CHANNEL_FREE, sound, false, &pAudioObject->sound);
pAudioObject->sound->setVolume(volume);
}
void Audio_Cleanup(AudioObject* pAudioObject)
{
pAudioObject->sound->stop();
FMOD::Sound* sound;
pAudioObject->sound->getCurrentSound(&sound);
sound->release();
}
bool Audio_IsPlaying(AudioObject* pAudioObject)
{
bool success = false;
if (pAudioObject == nullptr || pAudioObject->sound == nullptr)
return success;
pAudioObject->sound->isPlaying(&success);
return success;
}
void Audio_StopPlaying(AudioObject* pAudioObject)
{
if (pAudioObject == nullptr || pAudioObject->sound == nullptr)
return;
pAudioObject->sound->stop();
}<|endoftext|> |
<commit_before>#pragma once
#include <barcode/filetree.hpp>
#include <fstream>
#include <hydra/component/roomcomponent.hpp>
class PathingMapMenu{
public:
PathingMapMenu();
~PathingMapMenu();
void render(bool &closeBool, float delta, int sizeX, int sizeY);
//bool selected[32][32] = {false};
private:
};
<commit_msg>removed unused array comment<commit_after>#pragma once
#include <barcode/filetree.hpp>
#include <fstream>
#include <hydra/component/roomcomponent.hpp>
class PathingMapMenu{
public:
PathingMapMenu();
~PathingMapMenu();
void render(bool &closeBool, float delta, int sizeX, int sizeY);
private:
};
<|endoftext|> |
<commit_before>// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPSolver.h"
// includes
// std
#include <limits>
#include <cmath>
// RBDyn
#include <RBDyn/MultiBody.h>
#include <RBDyn/MultiBodyConfig.h>
// Tasks
#include "QL.h"
namespace tasks
{
namespace qp
{
// Value add to the diagonal to ensure positive matrix
static const double DIAG_CONSTANT = 1e-5;
/**
* QPSolver
*/
QPSolver::QPSolver(bool silent):
constr_(),
eqConstr_(),
inEqConstr_(),
boundConstr_(),
tasks_(),
nrEq_(0),
A1_(),B1_(),
nrInEq_(0),
A2_(),B2_(),
XL_(),XU_(),
Q_(),C_(),
res_(),
silent_(silent)
{
lssol_.warm(false);
}
bool QPSolver::update(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
return updateLSSOL(mb, mbc);
}
bool QPSolver::updateQLD(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
preUpdate(mb, mbc);
bool success = false;
double iter = 1e-8;
while(!success && iter < 1e-3)
{
success = qld_.solve(Q_, C_,
A1_.block(0, 0, nrEq_, data_.nrVars_), B1_.head(nrEq_),
A2_.block(0, 0, nrInEq_, data_.nrVars_), B2_.head(nrInEq_),
XL_, XU_, iter);
iter *= 10.;
}
postUpdate(mb, mbc, success, qld_.result());
/*
while(!success && iter < 1e-3)
{
success = solveQP(A1_.cols(), A1_.rows(), A2_.rows(),
Q_, C_, A1_, B1_, A2_, B2_, XL_, XU_, res_, iter, silent_);
iter *= 10.;
}
postUpdate(mb, mbc, success, res_);
*/
return success;
}
bool QPSolver::updateLSSOL(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
preUpdate(mb, mbc);
bool success = lssol_.solve(Q_, C_,
A1_.block(0, 0, nrEq_, data_.nrVars_), B1_.head(nrEq_),
A2_.block(0, 0, nrInEq_, data_.nrVars_), B2_.head(nrInEq_),
XL_, XU_);
postUpdate(mb, mbc, success, lssol_.result());
return success;
}
void QPSolver::updateEqConstrSize()
{
int nbEq = 0;
for(std::size_t i = 0; i < eqConstr_.size(); ++i)
{
nbEq += eqConstr_[i]->maxEq();
}
nrEq_ = 0;
A1_.resize(nbEq, data_.nrVars_);
B1_.resize(nbEq);
updateSolverSize(data_.nrVars_, nbEq, int(B2_.rows()));
}
void QPSolver::updateInEqConstrSize()
{
int nbInEq = 0;
for(std::size_t i = 0; i < inEqConstr_.size(); ++i)
{
nbInEq += inEqConstr_[i]->maxInEq();
}
nrInEq_ = 0;
A2_.resize(nbInEq, data_.nrVars_);
B2_.resize(nbInEq);
updateSolverSize(data_.nrVars_, int(B1_.rows()), nbInEq);
}
void QPSolver::nrVars(const rbd::MultiBody& mb,
std::vector<UnilateralContact> uni,
std::vector<BilateralContact> bi)
{
data_.alphaD_ = mb.nrDof();
data_.lambda_ = 0;
data_.torque_ = (mb.nrDof() - mb.joint(0).dof());
data_.uniCont_ = uni;
data_.biCont_ = bi;
// counting unilateral contact
for(const UnilateralContact& c: data_.uniCont_)
{
for(std::size_t i = 0; i < c.points.size(); ++i)
{
data_.lambda_ += c.nrLambda(int(i));
}
}
data_.lambdaUni_ = data_.lambda_;
// counting bilateral contact
for(const BilateralContact& c: data_.biCont_)
{
for(std::size_t i = 0; i < c.points.size(); ++i)
{
data_.lambda_ += c.nrLambda(int(i));
}
}
data_.lambdaBi_ = data_.lambda_ - data_.lambdaUni_;
data_.nrVars_ = data_.alphaD_ + data_.lambda_ + data_.torque_;
if(XL_.rows() != data_.nrVars_)
{
XL_.resize(data_.nrVars_);
XU_.resize(data_.nrVars_);
Q_.resize(data_.nrVars_, data_.nrVars_);
C_.resize(data_.nrVars_);
res_.resize(data_.nrVars_);
torqueRes_.resize(mb.nrDof());
if(mb.joint(0).type() == rbd::Joint::Free)
{
torqueRes_.segment(0, mb.joint(0).dof()).setZero();
}
}
for(Task* t: tasks_)
{
t->updateNrVars(mb, data_);
}
for(Constraint* c: constr_)
{
c->updateNrVars(mb, data_);
}
updateSolverSize(data_.nrVars_, static_cast<int>(B1_.rows()),
static_cast<int>(B2_.rows()));
}
int QPSolver::nrVars() const
{
return data_.nrVars_;
}
void QPSolver::addEqualityConstraint(Equality* co)
{
eqConstr_.push_back(co);
}
void QPSolver::removeEqualityConstraint(Equality* co)
{
eqConstr_.erase(std::find(eqConstr_.begin(), eqConstr_.end(), co));
}
int QPSolver::nrEqualityConstraints() const
{
return static_cast<int>(eqConstr_.size());
}
void QPSolver::addInequalityConstraint(Inequality* co)
{
inEqConstr_.push_back(co);
}
void QPSolver::removeInequalityConstraint(Inequality* co)
{
inEqConstr_.erase(std::find(inEqConstr_.begin(), inEqConstr_.end(), co));
}
int QPSolver::nrInequalityConstraints() const
{
return static_cast<int>(inEqConstr_.size());
}
void QPSolver::addBoundConstraint(Bound* co)
{
boundConstr_.push_back(co);
}
void QPSolver::removeBoundConstraint(Bound* co)
{
boundConstr_.erase(std::find(boundConstr_.begin(), boundConstr_.end(), co));
}
int QPSolver::nrBoundConstraints() const
{
return static_cast<int>(boundConstr_.size());
}
void QPSolver::addConstraint(Constraint* co)
{
if(std::find(constr_.begin(), constr_.end(), co) == constr_.end())
{
constr_.push_back(co);
}
}
void QPSolver::removeConstraint(Constraint* co)
{
auto it = std::find(constr_.begin(), constr_.end(), co);
if(it != constr_.end())
{
constr_.erase(it);
}
}
int QPSolver::nrConstraints() const
{
return static_cast<int>(constr_.size());
}
void QPSolver::addTask(Task* task)
{
if(std::find(tasks_.begin(), tasks_.end(), task) == tasks_.end())
{
tasks_.push_back(task);
}
}
void QPSolver::removeTask(Task* task)
{
auto it = std::find(tasks_.begin(), tasks_.end(), task);
if(it != tasks_.end())
{
tasks_.erase(it);
}
}
int QPSolver::nrTasks() const
{
return static_cast<int>(tasks_.size());
}
void QPSolver::resetTasks()
{
tasks_.clear();
}
const Eigen::VectorXd& QPSolver::result() const
{
return res_;
}
Eigen::VectorXd QPSolver::alphaDVec() const
{
return res_.head(data_.alphaD_);
}
Eigen::VectorXd QPSolver::lambdaVec() const
{
return res_.segment(data_.alphaD_, data_.lambda_);
}
Eigen::VectorXd QPSolver::torqueVec() const
{
return res_.tail(data_.torque_);
}
void QPSolver::updateSolverSize(int nrVar, int nrEq, int nrIneq)
{
updateLSSOLSize(nrVar, nrEq, nrIneq);
}
void QPSolver::updateQLDSize(int nrVar, int nrEq, int nrIneq)
{
qld_.problem(nrVar, nrEq, nrIneq);
}
void QPSolver::updateLSSOLSize(int nrVar, int nrEq, int nrIneq)
{
lssol_.problem(nrVar, nrEq, nrIneq);
// warning, if the user change the number of dof of the robot those lines
// don't have any sense
/*
lssol_.result().head(data_.alphaD_) = res_.head(data_.alphaD_);
lssol_.result().tail(data_.torque_) = res_.tail(data_.torque_);
*/
}
void QPSolver::preUpdate(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
for(std::size_t i = 0; i < constr_.size(); ++i)
{
constr_[i]->update(mb, mbc);
}
for(std::size_t i = 0; i < tasks_.size(); ++i)
{
tasks_[i]->update(mb, mbc);
}
A1_.setZero();
B1_.setZero();
A2_.setZero();
B2_.setZero();
XL_.fill(-std::numeric_limits<double>::infinity());
XU_.fill(std::numeric_limits<double>::infinity());
Q_.setZero();
C_.setZero();
nrEq_ = 0;
for(std::size_t i = 0; i < eqConstr_.size(); ++i)
{
// eq constraint can return a matrix with more line
// than the number of constraint
int nrConstr = eqConstr_[i]->nrEq();
const Eigen::MatrixXd& A1 = eqConstr_[i]->AEq();
const Eigen::VectorXd& B1 = eqConstr_[i]->BEq();
A1_.block(nrEq_, 0, nrConstr, data_.nrVars_) = A1;
B1_.segment(nrEq_, nrConstr) = B1;
nrEq_ += nrConstr;
}
nrInEq_ = 0;
for(std::size_t i = 0; i < inEqConstr_.size(); ++i)
{
// ineq constraint can return a matrix with more line
// than the number of constraint
int nrConstr = inEqConstr_[i]->nrInEq();
const Eigen::MatrixXd& A2 = inEqConstr_[i]->AInEq();
const Eigen::VectorXd& B2 = inEqConstr_[i]->BInEq();
A2_.block(nrInEq_, 0, nrConstr, data_.nrVars_) = A2;
B2_.segment(nrInEq_, nrConstr) = B2;
nrInEq_ += nrConstr;
}
for(std::size_t i = 0; i < boundConstr_.size(); ++i)
{
const Eigen::VectorXd& XL = boundConstr_[i]->Lower();
const Eigen::VectorXd& XU = boundConstr_[i]->Upper();
int bv = boundConstr_[i]->beginVar();
XL_.segment(bv, XL.size()) = XL;
XU_.segment(bv, XU.size()) = XU;
}
for(std::size_t i = 0; i < tasks_.size(); ++i)
{
const Eigen::MatrixXd& Q = tasks_[i]->Q();
const Eigen::VectorXd& C = tasks_[i]->C();
std::pair<int, int> b = tasks_[i]->begin();
int r = static_cast<int>(Q.rows());
int c = static_cast<int>(Q.cols());
Q_.block(b.first, b.second, r, c) += tasks_[i]->weight()*Q;
C_.segment(b.first, r) += tasks_[i]->weight()*C;
}
// try to transform Q_ to a positive matrix
// we just add a small value to the diagonal since
// the first necessary condition is to have
// Q_(i,i) > 0
// may be we can try to check the second
// condition in a near futur
// Q_(i,i) + Q_(j,j) > 2·Q_(i,j) for i≠j
for(int i = 0; i < data_.nrVars_; ++i)
{
if(std::abs(Q_(i, i)) < DIAG_CONSTANT)
{
Q_(i, i) += DIAG_CONSTANT;
}
}
}
void QPSolver::postUpdate(const rbd::MultiBody& mb,
rbd::MultiBodyConfig& mbc, bool success, const Eigen::VectorXd& result)
{
if(success)
{
res_ = result;
int dof0 = mb.joint(0).dof();
torqueRes_.segment(dof0, mb.nrDof() - dof0) = result.tail(data_.torque_);
rbd::vectorToParam(res_.head(data_.alphaD_), mbc.alphaD);
rbd::vectorToParam(torqueRes_, mbc.jointTorque);
// don't write contact force to the structure since contact force are used
// to compute C vector.
}
}
} // namespace qp
} // namespace tasks
<commit_msg>Fix a bug in constraint matrix filling.<commit_after>// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPSolver.h"
// includes
// std
#include <limits>
#include <cmath>
// RBDyn
#include <RBDyn/MultiBody.h>
#include <RBDyn/MultiBodyConfig.h>
// Tasks
#include "QL.h"
namespace tasks
{
namespace qp
{
// Value add to the diagonal to ensure positive matrix
static const double DIAG_CONSTANT = 1e-5;
/**
* QPSolver
*/
QPSolver::QPSolver(bool silent):
constr_(),
eqConstr_(),
inEqConstr_(),
boundConstr_(),
tasks_(),
nrEq_(0),
A1_(),B1_(),
nrInEq_(0),
A2_(),B2_(),
XL_(),XU_(),
Q_(),C_(),
res_(),
silent_(silent)
{
lssol_.warm(false);
}
bool QPSolver::update(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
return updateLSSOL(mb, mbc);
}
bool QPSolver::updateQLD(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
preUpdate(mb, mbc);
bool success = false;
double iter = 1e-8;
while(!success && iter < 1e-3)
{
success = qld_.solve(Q_, C_,
A1_.block(0, 0, nrEq_, data_.nrVars_), B1_.head(nrEq_),
A2_.block(0, 0, nrInEq_, data_.nrVars_), B2_.head(nrInEq_),
XL_, XU_, iter);
iter *= 10.;
}
postUpdate(mb, mbc, success, qld_.result());
/*
while(!success && iter < 1e-3)
{
success = solveQP(A1_.cols(), A1_.rows(), A2_.rows(),
Q_, C_, A1_, B1_, A2_, B2_, XL_, XU_, res_, iter, silent_);
iter *= 10.;
}
postUpdate(mb, mbc, success, res_);
*/
return success;
}
bool QPSolver::updateLSSOL(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
preUpdate(mb, mbc);
bool success = lssol_.solve(Q_, C_,
A1_.block(0, 0, nrEq_, data_.nrVars_), B1_.head(nrEq_),
A2_.block(0, 0, nrInEq_, data_.nrVars_), B2_.head(nrInEq_),
XL_, XU_);
postUpdate(mb, mbc, success, lssol_.result());
return success;
}
void QPSolver::updateEqConstrSize()
{
int nbEq = 0;
for(std::size_t i = 0; i < eqConstr_.size(); ++i)
{
nbEq += eqConstr_[i]->maxEq();
}
nrEq_ = 0;
A1_.resize(nbEq, data_.nrVars_);
B1_.resize(nbEq);
updateSolverSize(data_.nrVars_, nbEq, int(B2_.rows()));
}
void QPSolver::updateInEqConstrSize()
{
int nbInEq = 0;
for(std::size_t i = 0; i < inEqConstr_.size(); ++i)
{
nbInEq += inEqConstr_[i]->maxInEq();
}
nrInEq_ = 0;
A2_.resize(nbInEq, data_.nrVars_);
B2_.resize(nbInEq);
updateSolverSize(data_.nrVars_, int(B1_.rows()), nbInEq);
}
void QPSolver::nrVars(const rbd::MultiBody& mb,
std::vector<UnilateralContact> uni,
std::vector<BilateralContact> bi)
{
data_.alphaD_ = mb.nrDof();
data_.lambda_ = 0;
data_.torque_ = (mb.nrDof() - mb.joint(0).dof());
data_.uniCont_ = uni;
data_.biCont_ = bi;
// counting unilateral contact
for(const UnilateralContact& c: data_.uniCont_)
{
for(std::size_t i = 0; i < c.points.size(); ++i)
{
data_.lambda_ += c.nrLambda(int(i));
}
}
data_.lambdaUni_ = data_.lambda_;
// counting bilateral contact
for(const BilateralContact& c: data_.biCont_)
{
for(std::size_t i = 0; i < c.points.size(); ++i)
{
data_.lambda_ += c.nrLambda(int(i));
}
}
data_.lambdaBi_ = data_.lambda_ - data_.lambdaUni_;
data_.nrVars_ = data_.alphaD_ + data_.lambda_ + data_.torque_;
if(XL_.rows() != data_.nrVars_)
{
XL_.resize(data_.nrVars_);
XU_.resize(data_.nrVars_);
Q_.resize(data_.nrVars_, data_.nrVars_);
C_.resize(data_.nrVars_);
res_.resize(data_.nrVars_);
torqueRes_.resize(mb.nrDof());
if(mb.joint(0).type() == rbd::Joint::Free)
{
torqueRes_.segment(0, mb.joint(0).dof()).setZero();
}
}
for(Task* t: tasks_)
{
t->updateNrVars(mb, data_);
}
for(Constraint* c: constr_)
{
c->updateNrVars(mb, data_);
}
updateSolverSize(data_.nrVars_, static_cast<int>(B1_.rows()),
static_cast<int>(B2_.rows()));
}
int QPSolver::nrVars() const
{
return data_.nrVars_;
}
void QPSolver::addEqualityConstraint(Equality* co)
{
eqConstr_.push_back(co);
}
void QPSolver::removeEqualityConstraint(Equality* co)
{
eqConstr_.erase(std::find(eqConstr_.begin(), eqConstr_.end(), co));
}
int QPSolver::nrEqualityConstraints() const
{
return static_cast<int>(eqConstr_.size());
}
void QPSolver::addInequalityConstraint(Inequality* co)
{
inEqConstr_.push_back(co);
}
void QPSolver::removeInequalityConstraint(Inequality* co)
{
inEqConstr_.erase(std::find(inEqConstr_.begin(), inEqConstr_.end(), co));
}
int QPSolver::nrInequalityConstraints() const
{
return static_cast<int>(inEqConstr_.size());
}
void QPSolver::addBoundConstraint(Bound* co)
{
boundConstr_.push_back(co);
}
void QPSolver::removeBoundConstraint(Bound* co)
{
boundConstr_.erase(std::find(boundConstr_.begin(), boundConstr_.end(), co));
}
int QPSolver::nrBoundConstraints() const
{
return static_cast<int>(boundConstr_.size());
}
void QPSolver::addConstraint(Constraint* co)
{
if(std::find(constr_.begin(), constr_.end(), co) == constr_.end())
{
constr_.push_back(co);
}
}
void QPSolver::removeConstraint(Constraint* co)
{
auto it = std::find(constr_.begin(), constr_.end(), co);
if(it != constr_.end())
{
constr_.erase(it);
}
}
int QPSolver::nrConstraints() const
{
return static_cast<int>(constr_.size());
}
void QPSolver::addTask(Task* task)
{
if(std::find(tasks_.begin(), tasks_.end(), task) == tasks_.end())
{
tasks_.push_back(task);
}
}
void QPSolver::removeTask(Task* task)
{
auto it = std::find(tasks_.begin(), tasks_.end(), task);
if(it != tasks_.end())
{
tasks_.erase(it);
}
}
int QPSolver::nrTasks() const
{
return static_cast<int>(tasks_.size());
}
void QPSolver::resetTasks()
{
tasks_.clear();
}
const Eigen::VectorXd& QPSolver::result() const
{
return res_;
}
Eigen::VectorXd QPSolver::alphaDVec() const
{
return res_.head(data_.alphaD_);
}
Eigen::VectorXd QPSolver::lambdaVec() const
{
return res_.segment(data_.alphaD_, data_.lambda_);
}
Eigen::VectorXd QPSolver::torqueVec() const
{
return res_.tail(data_.torque_);
}
void QPSolver::updateSolverSize(int nrVar, int nrEq, int nrIneq)
{
updateLSSOLSize(nrVar, nrEq, nrIneq);
}
void QPSolver::updateQLDSize(int nrVar, int nrEq, int nrIneq)
{
qld_.problem(nrVar, nrEq, nrIneq);
}
void QPSolver::updateLSSOLSize(int nrVar, int nrEq, int nrIneq)
{
lssol_.problem(nrVar, nrEq, nrIneq);
// warning, if the user change the number of dof of the robot those lines
// don't have any sense
/*
lssol_.result().head(data_.alphaD_) = res_.head(data_.alphaD_);
lssol_.result().tail(data_.torque_) = res_.tail(data_.torque_);
*/
}
void QPSolver::preUpdate(const rbd::MultiBody& mb, rbd::MultiBodyConfig& mbc)
{
for(std::size_t i = 0; i < constr_.size(); ++i)
{
constr_[i]->update(mb, mbc);
}
for(std::size_t i = 0; i < tasks_.size(); ++i)
{
tasks_[i]->update(mb, mbc);
}
A1_.setZero();
B1_.setZero();
A2_.setZero();
B2_.setZero();
XL_.fill(-std::numeric_limits<double>::infinity());
XU_.fill(std::numeric_limits<double>::infinity());
Q_.setZero();
C_.setZero();
nrEq_ = 0;
for(std::size_t i = 0; i < eqConstr_.size(); ++i)
{
// eq constraint can return a matrix with more line
// than the number of constraint
int nrConstr = eqConstr_[i]->nrEq();
const Eigen::MatrixXd& A1 = eqConstr_[i]->AEq();
const Eigen::VectorXd& B1 = eqConstr_[i]->BEq();
A1_.block(nrEq_, 0, nrConstr, data_.nrVars_) =
A1.block(0, 0, nrConstr, data_.nrVars_);
B1_.segment(nrEq_, nrConstr) = B1.head(nrConstr);
nrEq_ += nrConstr;
}
nrInEq_ = 0;
for(std::size_t i = 0; i < inEqConstr_.size(); ++i)
{
// ineq constraint can return a matrix with more line
// than the number of constraint
int nrConstr = inEqConstr_[i]->nrInEq();
const Eigen::MatrixXd& A2 = inEqConstr_[i]->AInEq();
const Eigen::VectorXd& B2 = inEqConstr_[i]->BInEq();
A2_.block(nrInEq_, 0, nrConstr, data_.nrVars_) =
A2.block(0, 0, nrConstr, data_.nrVars_);
B2_.segment(nrInEq_, nrConstr) = B2.head(nrConstr);
nrInEq_ += nrConstr;
}
for(std::size_t i = 0; i < boundConstr_.size(); ++i)
{
const Eigen::VectorXd& XL = boundConstr_[i]->Lower();
const Eigen::VectorXd& XU = boundConstr_[i]->Upper();
int bv = boundConstr_[i]->beginVar();
XL_.segment(bv, XL.size()) = XL;
XU_.segment(bv, XU.size()) = XU;
}
for(std::size_t i = 0; i < tasks_.size(); ++i)
{
const Eigen::MatrixXd& Q = tasks_[i]->Q();
const Eigen::VectorXd& C = tasks_[i]->C();
std::pair<int, int> b = tasks_[i]->begin();
int r = static_cast<int>(Q.rows());
int c = static_cast<int>(Q.cols());
Q_.block(b.first, b.second, r, c) += tasks_[i]->weight()*Q;
C_.segment(b.first, r) += tasks_[i]->weight()*C;
}
// try to transform Q_ to a positive matrix
// we just add a small value to the diagonal since
// the first necessary condition is to have
// Q_(i,i) > 0
// may be we can try to check the second
// condition in a near futur
// Q_(i,i) + Q_(j,j) > 2·Q_(i,j) for i≠j
for(int i = 0; i < data_.nrVars_; ++i)
{
if(std::abs(Q_(i, i)) < DIAG_CONSTANT)
{
Q_(i, i) += DIAG_CONSTANT;
}
}
}
void QPSolver::postUpdate(const rbd::MultiBody& mb,
rbd::MultiBodyConfig& mbc, bool success, const Eigen::VectorXd& result)
{
if(success)
{
res_ = result;
int dof0 = mb.joint(0).dof();
torqueRes_.segment(dof0, mb.nrDof() - dof0) = result.tail(data_.torque_);
rbd::vectorToParam(res_.head(data_.alphaD_), mbc.alphaD);
rbd::vectorToParam(torqueRes_, mbc.jointTorque);
// don't write contact force to the structure since contact force are used
// to compute C vector.
}
}
} // namespace qp
} // namespace tasks
<|endoftext|> |
<commit_before>/*
* Universe
*
* Copyright 2015 Lubosz Sarnecki <[email protected]>
*
*/
#include "Renderer.h"
#include "util.h"
#include <gli/gli.hpp>
Renderer::Renderer(int width, int height) {
translate_z = -0.1f;
rotate_x = 0.0;
rotate_y = 0.0;
if (gl3wInit()) {
fprintf(stderr, "failed to initialize gl3w\n");
return;
}
if (!gl3wIsSupported(4, 5)) {
fprintf(stderr, "OpenGL 4.5 not supported\n");
return;
}
printContextInfo();
initShaders();
glUseProgram(shader_programm);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
GLuint tex = initTexture("media/cloud.dds");
glBindTexture(GL_TEXTURE_2D, tex);
GLint texLoc = glGetUniformLocation(shader_programm, "cloud");
glUniform1i(texLoc, tex-1);
updateModel();
updateProjection(width, height);
glClearColor(0.0, 0.0, 0.0, 1.0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindVertexArray(vao);
glError;
}
Renderer::~Renderer() {}
void Renderer::draw(GLuint positionVBO, GLuint colorVBO,
GLuint massVBO, int particleCount) {
// render the particles from VBOs
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, positionVBO);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, massVBO);
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, NULL);
glDrawArrays(GL_POINTS, 0, particleCount);
}
void Renderer::printContextInfo() {
printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
printf("GL_VERSION: %s\n", glGetString(GL_VERSION));
printf("GL_SHADING_LANGUAGE_VERSION: %s\n",
glGetString(GL_SHADING_LANGUAGE_VERSION));
}
GLuint Renderer::initTexture(char const* Filename) {
gli::texture Texture = gli::load(Filename);
if (Texture.empty())
return 0;
gli::gl GL;
gli::gl::format const Format = GL.translate(Texture.format());
GLenum Target = GL.translate(Texture.target());
GLuint TextureName = 0;
glGenTextures(1, &TextureName);
glBindTexture(Target, TextureName);
glTexParameteri(Target, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(Target,
GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1));
glm::tvec3<GLsizei> const Dimensions(Texture.dimensions());
GLsizei const FaceTotal =
static_cast<GLsizei>(Texture.layers() * Texture.faces());
glTexStorage2D(
Target, static_cast<GLint>(Texture.levels()), Format.Internal,
Dimensions.x,
Texture.target() == gli::TARGET_2D ? Dimensions.y : FaceTotal);
for (std::size_t Layer = 0;
Layer < Texture.layers(); ++Layer)
for (std::size_t Face = 0;
Face < Texture.faces(); ++Face)
for (std::size_t Level = 0;
Level < Texture.levels(); ++Level) {
glm::tvec3<GLsizei> Dimensions(Texture.dimensions(Level));
/*
printf("layer %ld, face %ld, level %ld, iscompressed %d\n",
Layer, Face, Level,
gli::is_compressed(Texture.format()));
*/
if (gli::is_compressed(Texture.format()))
glCompressedTexSubImage2D(
Target, static_cast<GLint>(Level),
0, 0,
Dimensions.x,
Dimensions.y,
Format.Internal,
static_cast<GLsizei>(Texture.size(Level)),
Texture.data(Layer, Face, Level));
else
glTexSubImage2D(
Target, static_cast<GLint>(Level),
0, 0,
Dimensions.x,
Dimensions.y,
Format.External, Format.Type,
Texture.data(Layer, Face, Level));
}
return TextureName;
}
void Renderer::initShaders() {
shaders.push_back(readFile("gpu/MVP.vert"));
shaders.push_back(readFile("gpu/color.frag"));
const char* vertex[] = {shaders[0].c_str()};
const char* fragment[] = {shaders[1].c_str()};
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, vertex, NULL);
glCompileShader(vs);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, fragment, NULL);
glCompileShader(fs);
shader_programm = glCreateProgram();
glAttachShader(shader_programm, fs);
glAttachShader(shader_programm, vs);
glLinkProgram(shader_programm);
}
void Renderer::rotate(float x, float y) {
rotate_x += y * 0.2;
rotate_y += x * 0.2;
updateModel();
}
void Renderer::translate(float z) {
translate_z += z * 0.1;
updateModel();
}
void Renderer::updateModel() {
model = glm::mat4(1.0f);
model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));
updateMVP();
}
void Renderer::updateProjection(int width, int height) {
glViewport(0, 0, width, height);
float aspect = static_cast<GLfloat>(width)
/ static_cast<GLfloat>(height);
projection = glm::perspective(45.0f, aspect, 0.01f, 10000.f);
updateMVP();
}
void Renderer::updateMVP() {
glUniformMatrix4fv(
glGetUniformLocation(shader_programm, "modelMatrix"),
1, GL_FALSE, &model[0][0]);
glUniformMatrix4fv(
glGetUniformLocation(shader_programm, "projectionMatrix"),
1, GL_FALSE, &projection[0][0]);
}
void Renderer::checkGlError(const char* file, int line) {
GLenum err(glGetError());
while (err != GL_NO_ERROR) {
std::string error;
switch (err) {
case GL_INVALID_OPERATION:
error = "INVALID_OPERATION";
break;
case GL_INVALID_ENUM:
error = "INVALID_ENUM";
break;
case GL_INVALID_VALUE:
error = "INVALID_VALUE";
break;
case GL_OUT_OF_MEMORY:
error = "OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
error = "INVALID_FRAMEBUFFER_OPERATION";
break;
default:
error = "Unknown error";
break;
}
std::cout
<< "GL ERROR: GL_"
<< error << " "
<< file << " "
<< line << "\n";
err = glGetError();
}
}
GLuint Renderer::createVBO(
const void* data,
int dataSize,
GLenum target,
GLenum usage) {
GLuint id;
glGenBuffers(1, &id);
glBindBuffer(target, id);
glBufferData(target, dataSize, data, usage);
// check data size in VBO is same as input array
// if not return 0 and delete VBO
int bufferSize = 0;
glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);
if (dataSize != bufferSize) {
glDeleteBuffers(1, &id);
id = 0;
std::cout << "[createVBO()] Data size is mismatch with input array\n";
}
glBindBuffer(target, 0);
return id;
}
<commit_msg>Renderer: change initial camera position and scroll strep<commit_after>/*
* Universe
*
* Copyright 2015 Lubosz Sarnecki <[email protected]>
*
*/
#include "Renderer.h"
#include "util.h"
#include <gli/gli.hpp>
Renderer::Renderer(int width, int height) {
translate_z = -0.5f;
rotate_x = 0.0;
rotate_y = 0.0;
if (gl3wInit()) {
fprintf(stderr, "failed to initialize gl3w\n");
return;
}
if (!gl3wIsSupported(4, 5)) {
fprintf(stderr, "OpenGL 4.5 not supported\n");
return;
}
printContextInfo();
initShaders();
glUseProgram(shader_programm);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
GLuint tex = initTexture("media/cloud.dds");
glBindTexture(GL_TEXTURE_2D, tex);
GLint texLoc = glGetUniformLocation(shader_programm, "cloud");
glUniform1i(texLoc, tex-1);
updateModel();
updateProjection(width, height);
glClearColor(0.0, 0.0, 0.0, 1.0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindVertexArray(vao);
glError;
}
Renderer::~Renderer() {}
void Renderer::draw(GLuint positionVBO, GLuint colorVBO,
GLuint massVBO, int particleCount) {
// render the particles from VBOs
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, positionVBO);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, massVBO);
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, NULL);
glDrawArrays(GL_POINTS, 0, particleCount);
}
void Renderer::printContextInfo() {
printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
printf("GL_VERSION: %s\n", glGetString(GL_VERSION));
printf("GL_SHADING_LANGUAGE_VERSION: %s\n",
glGetString(GL_SHADING_LANGUAGE_VERSION));
}
GLuint Renderer::initTexture(char const* Filename) {
gli::texture Texture = gli::load(Filename);
if (Texture.empty())
return 0;
gli::gl GL;
gli::gl::format const Format = GL.translate(Texture.format());
GLenum Target = GL.translate(Texture.target());
GLuint TextureName = 0;
glGenTextures(1, &TextureName);
glBindTexture(Target, TextureName);
glTexParameteri(Target, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(Target,
GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1));
glm::tvec3<GLsizei> const Dimensions(Texture.dimensions());
GLsizei const FaceTotal =
static_cast<GLsizei>(Texture.layers() * Texture.faces());
glTexStorage2D(
Target, static_cast<GLint>(Texture.levels()), Format.Internal,
Dimensions.x,
Texture.target() == gli::TARGET_2D ? Dimensions.y : FaceTotal);
for (std::size_t Layer = 0;
Layer < Texture.layers(); ++Layer)
for (std::size_t Face = 0;
Face < Texture.faces(); ++Face)
for (std::size_t Level = 0;
Level < Texture.levels(); ++Level) {
glm::tvec3<GLsizei> Dimensions(Texture.dimensions(Level));
/*
printf("layer %ld, face %ld, level %ld, iscompressed %d\n",
Layer, Face, Level,
gli::is_compressed(Texture.format()));
*/
if (gli::is_compressed(Texture.format()))
glCompressedTexSubImage2D(
Target, static_cast<GLint>(Level),
0, 0,
Dimensions.x,
Dimensions.y,
Format.Internal,
static_cast<GLsizei>(Texture.size(Level)),
Texture.data(Layer, Face, Level));
else
glTexSubImage2D(
Target, static_cast<GLint>(Level),
0, 0,
Dimensions.x,
Dimensions.y,
Format.External, Format.Type,
Texture.data(Layer, Face, Level));
}
return TextureName;
}
void Renderer::initShaders() {
shaders.push_back(readFile("gpu/MVP.vert"));
shaders.push_back(readFile("gpu/color.frag"));
const char* vertex[] = {shaders[0].c_str()};
const char* fragment[] = {shaders[1].c_str()};
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, vertex, NULL);
glCompileShader(vs);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, fragment, NULL);
glCompileShader(fs);
shader_programm = glCreateProgram();
glAttachShader(shader_programm, fs);
glAttachShader(shader_programm, vs);
glLinkProgram(shader_programm);
}
void Renderer::rotate(float x, float y) {
rotate_x += y * 0.2;
rotate_y += x * 0.2;
updateModel();
}
void Renderer::translate(float z) {
translate_z += z * 0.01;
updateModel();
}
void Renderer::updateModel() {
model = glm::mat4(1.0f);
model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));
updateMVP();
}
void Renderer::updateProjection(int width, int height) {
glViewport(0, 0, width, height);
float aspect = static_cast<GLfloat>(width)
/ static_cast<GLfloat>(height);
projection = glm::perspective(45.0f, aspect, 0.01f, 10000.f);
updateMVP();
}
void Renderer::updateMVP() {
glUniformMatrix4fv(
glGetUniformLocation(shader_programm, "modelMatrix"),
1, GL_FALSE, &model[0][0]);
glUniformMatrix4fv(
glGetUniformLocation(shader_programm, "projectionMatrix"),
1, GL_FALSE, &projection[0][0]);
}
void Renderer::checkGlError(const char* file, int line) {
GLenum err(glGetError());
while (err != GL_NO_ERROR) {
std::string error;
switch (err) {
case GL_INVALID_OPERATION:
error = "INVALID_OPERATION";
break;
case GL_INVALID_ENUM:
error = "INVALID_ENUM";
break;
case GL_INVALID_VALUE:
error = "INVALID_VALUE";
break;
case GL_OUT_OF_MEMORY:
error = "OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
error = "INVALID_FRAMEBUFFER_OPERATION";
break;
default:
error = "Unknown error";
break;
}
std::cout
<< "GL ERROR: GL_"
<< error << " "
<< file << " "
<< line << "\n";
err = glGetError();
}
}
GLuint Renderer::createVBO(
const void* data,
int dataSize,
GLenum target,
GLenum usage) {
GLuint id;
glGenBuffers(1, &id);
glBindBuffer(target, id);
glBufferData(target, dataSize, data, usage);
// check data size in VBO is same as input array
// if not return 0 and delete VBO
int bufferSize = 0;
glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);
if (dataSize != bufferSize) {
glDeleteBuffers(1, &id);
id = 0;
std::cout << "[createVBO()] Data size is mismatch with input array\n";
}
glBindBuffer(target, 0);
return id;
}
<|endoftext|> |
<commit_before>#include "Renderer.hpp"
static GLfloat vertices[] = {
1, 1,0, 1,-1,0, -1,1,0,
1,-1,0, -1,-1,0, -1,1,0
};
static GLfloat uvs[] = {
1,0, 1,1, 0,0,
1,1, 0,1, 0,0
};
const char * Renderer::defaultVertexShader =
"#version 330 core\n"
"\n"
"in vec3 position;\n"
"in vec2 texCoord;\n"
"\n"
"out vec2 uv;\n"
"\n"
"void main(){\n"
" gl_Position = vec4(position, 1);\n"
" uv = texCoord;\n"
"}";
const char * Renderer::defaultFragmentShader =
"#version 330 core\n"
"\n"
"out vec4 color;\n"
"\n"
"in vec2 uv;\n"
"uniform float time;\n"
"uniform vec2 mouse;\n"
"uniform float ration;\n"
"\n"
"void main(){\n"
" color = vec4(cos(uv.x * 5 - time / 1000) / 2 + .5, 0, sin(uv.x * 5 - time / 1000) / 2 + .5, 1);\n"
"}";
/**
* @brief Renderer::Renderer
* @param parent Parent object of the render window
*
* Create a new Renderer with default shader
*/
Renderer::Renderer(QWindow *parent) : Renderer::Renderer("new", defaultFragmentShader, parent){ }
/**
* @brief Renderer::Renderer
* @param filename Name that should shown in the title
* @param instructions Shader code for execution
* @param parent Parent object of the render window
*
* Create a new Renderer with given code and set filename as title
*/
Renderer::Renderer(const QString &filename, const QString &instructions, QWindow *parent) :
QWindow(parent),
clearColor(Qt::black),
context(0), device(0),
time(0),
pendingUpdate(false),
vao(0), uvBuffer(0), audioLeftTexture(0), audioRightTexture(0),
vertexAttr(0), uvAttr(0), timeUniform(0),
shaderProgram(0),
fragmentSource(instructions)
{
setTitle(filename);
m_logger = new QOpenGLDebugLogger( this );
connect(m_logger, SIGNAL(messageLogged(QOpenGLDebugMessage)),
this, SLOT(onMessageLogged(QOpenGLDebugMessage)),
Qt::DirectConnection );
setSurfaceType(QWindow::OpenGLSurface);
time = new QTime();
time->start();
audio = new AudioInputProcessor(this);
connect(audio, SIGNAL(processData(QByteArray)), this, SLOT(updateAudioData(QByteArray)));
audio->start();
QSurfaceFormat format;
format.setMajorVersion(3);
format.setMinorVersion(3);
format.setSamples(4);
format.setProfile(QSurfaceFormat::CoreProfile);
setFormat(format);
}
/**
* @brief Renderer::~Renderer
*
* Free resources
*/
Renderer::~Renderer(){
glDeleteBuffers(1, &uvBuffer);
glDeleteTextures(1, &audioLeftTexture);
glDeleteTextures(1, &audioRightTexture);
delete time;
delete vao;
delete device;
delete m_logger;
}
/**
* @brief Renderer::init
* @return True on success, otherwise false
*
* Allocates grafic memory and initialize the shader program
*/
bool Renderer::init(){
delete vao;
vao = new QOpenGLVertexArrayObject(this);
vao->create();
vao->bind();
glDeleteBuffers(1, &vertexBuffer);
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glDeleteBuffers(1, &uvBuffer);
glGenBuffers(1, &uvBuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
glEnable(GL_TEXTURE_1D);
glDeleteTextures(1, &audioLeftTexture);
glGenTextures(1, &audioLeftTexture);
glDeleteTextures(1, &audioRightTexture);
glGenTextures(1, &audioRightTexture);
glClearColor(0,0,.3,1);
bool result = initShaders(fragmentSource);
vao->release();
return result;
}
/**
* @brief Renderer::initShaders
* @param fragmentShader Code to compile as shader
* @return True on success, otherwise false
*
* Initialze and compile the shader program
*/
bool Renderer::initShaders(const QString &fragmentShader){
QOpenGLShaderProgram *newShaderProgram = new QOpenGLShaderProgram(this);
bool hasError = false;
QString error = "";
if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, defaultVertexShader)){
hasError = true;
error = newShaderProgram->log();
qWarning() << tr("Failed to compile default shader.");
}
if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment,fragmentShader)){
hasError = true;
error = newShaderProgram->log();
if(fragmentShader == defaultFragmentShader)
qWarning() << tr("Failed to compile default shader.");
else if(shaderProgram == 0)
initShaders(defaultFragmentShader);
}
if(!hasError && !newShaderProgram->link()){
hasError = true;
error = newShaderProgram->log();
if(fragmentShader == defaultFragmentShader)
qWarning() << tr("Failed to compile default shader.");
else if(shaderProgram == 0)
initShaders(defaultFragmentShader);
}
if(hasError){
delete newShaderProgram;
QRegExp errorline(":[0-9]+:");
errorline.indexIn(error);
QString text = errorline.capturedTexts().at(0);
text.replace(":", "");
if(text.toInt()-3 > 0)
emit errored(error, text.toInt()-3);
else
emit errored(error, text.toInt());
return false;
}
shaderProgramMutex.lock();
if(shaderProgram)
delete shaderProgram;
shaderProgram = newShaderProgram;
vertexAttr = shaderProgram->attributeLocation("position");
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
shaderProgram->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3);
shaderProgram->enableAttributeArray(vertexAttr);
uvAttr = shaderProgram->attributeLocation("texCoord");
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
shaderProgram->setAttributeBuffer("texCoord", GL_FLOAT, 0, 2);
shaderProgram->enableAttributeArray(uvAttr);
timeUniform = shaderProgram->uniformLocation("time");
mouseUniform = shaderProgram->uniformLocation("mouse");
rationUniform = shaderProgram->uniformLocation("ration");
fragmentSource = fragmentShader;
shaderProgramMutex.unlock();
// qDebug() << "vertexAttr" << vertexAttr;
// qDebug() << "uvAttr" << uvAttr;
// qDebug() << "timeUniform" << timeUniform;
// qDebug() << "audioUniform" << audioUniform;
return true;
}
/**
* @brief Renderer::render
*
* Initialize output device, execute the shader and display the result
*/
void Renderer::render(){
if(!device)
device = new QOpenGLPaintDevice();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
device->setSize(size());
// qDebug() << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_VERSION))) << " " << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
const qreal retinaScale = devicePixelRatio();
glViewport(0, 0, width() * retinaScale, height() * retinaScale);
glClear(GL_COLOR_BUFFER_BIT);
QPoint mouse = this->mapFromGlobal(QCursor::pos());
QVector2D mousePosition((float)mouse.x() / (float)this->width(),
(float)mouse.y() / (float)this->height());
float ration = (float)this->width() / (float)this->height();
shaderProgramMutex.lock();
vao->bind();
shaderProgram->bind();
shaderProgram->setUniformValue(mouseUniform,mousePosition);
if(this->height() != 0)
shaderProgram->setUniformValue(rationUniform, ration);
shaderProgram->setUniformValue(timeUniform, (float)time->elapsed());
glDrawArrays(GL_TRIANGLES, 0, 6);
vao->release();
shaderProgramMutex.unlock();
}
/**
* @brief Renderer::renderLater
*
* Enqueue an update event to event queue
*/
void Renderer::renderLater(){
if(!pendingUpdate){
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
pendingUpdate = true;
}
}
/**
* @brief Renderer::renderNow
*
* Use the compiled shader to render on the widget
*/
void Renderer::renderNow(){
pendingUpdate = false;
if(!isExposed())
return;
bool needsInit = false;
if(!context){
context = new QOpenGLContext(this);
context->setFormat(requestedFormat());
context->create();
needsInit = true;
}
context->makeCurrent(this);
if(needsInit){
if (m_logger->initialize()){
m_logger->startLogging( QOpenGLDebugLogger::SynchronousLogging );
m_logger->enableMessages();
}
initializeOpenGLFunctions();
init();
}
if(!shaderProgram)
initShaders(fragmentSource);
if(shaderProgram)
render();
context->swapBuffers(this);
renderLater();
}
/**
* @brief Renderer::event
* @param event The event that should be proccessed
* @return True if the event was successful proccessed, otherwise false
*
* Called if a new event is poped from the event-queue to render on update event
* and emit doneSignal on close event.
*/
bool Renderer::event(QEvent *event){
switch(event->type()){
case QEvent::UpdateRequest:
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
renderNow();
return true;
case QEvent::Close:
emit doneSignal(tr("User closed renderer"));
return true;
default:
return QWindow::event(event);
}
}
/**
* @brief Renderer::exposeEvent
*
* Called if the window is ready to start rendering
*/
void Renderer::exposeEvent(QExposeEvent *){
if(isExposed())
renderNow();
}
/**
* @brief Renderer::updateCode
* @param filename Text for the title
* @param code New shader program code
* @return True on success, otherwise false.
*
* Set new title and compile new code for the shader program
*/
bool Renderer::updateCode(const QString &filename, const QString &code){
if(!initShaders(code))
return false;
setTitle(filename);
show();
return true;
}
/**
* @brief Renderer::updateAudioData
* @param data New audio data
*
* Copy the new sound-data to the graphics memory for visualisation
*/
void Renderer::updateAudioData(QByteArray data){
if(!shaderProgram)
return;
GLenum type, internalType;
Q_UNUSED(internalType);
char typeSize;
switch(audio->format().sampleType() + audio->format().sampleSize()){
case 8: case 10:
type = GL_UNSIGNED_BYTE;
internalType = GL_R8UI;
typeSize = 1;
break;
case 9:
type = GL_BYTE;
internalType = GL_R8I;
typeSize = 1;
break;
case 16: case 18:
type = GL_UNSIGNED_SHORT;
internalType = GL_R16UI;
typeSize = 2;
break;
case 17:
type = GL_SHORT;
internalType = GL_R16I;
typeSize = 2;
break;
case 32: case 34:
type = GL_UNSIGNED_INT;
internalType = GL_R32UI;
typeSize = 4;
break;
case 33:
type = GL_INT;
internalType = GL_R32I;
typeSize = 4;
break;
case 35:
type = GL_FLOAT;
internalType = GL_R32F;
typeSize = 4;
break;
default: return;
}
char *left, *right;
int count = data.size();
if(audio->format().channelCount() == 2){
count /= 2;
left = new char[count];
right = new char[count];
for(int i = 0; i < count; i += typeSize){
for(int j = 0; j < typeSize; ++j){
left [i+j] = data[i*2+j];
right[i+j] = data[i*2+j+typeSize];
}
}
}else
left = right = data.data();
shaderProgramMutex.lock();
shaderProgram->bind();
glBindTexture(GL_TEXTURE_1D, audioLeftTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, left);
glBindTexture(GL_TEXTURE_1D, audioRightTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, right);
shaderProgram->release();
shaderProgramMutex.unlock();
if(left != data.data())
delete[] left;
if(right != data.data())
delete[] right;
}
/**
* @brief Renderer::onMessageLogged
* @param message Message text
*
* Write the message text in the debug output
*/
void Renderer::onMessageLogged(QOpenGLDebugMessage message){
qDebug() << message;
}
<commit_msg>Highlight correct line while using mesa-driver<commit_after>#include "Renderer.hpp"
static GLfloat vertices[] = {
1, 1,0, 1,-1,0, -1,1,0,
1,-1,0, -1,-1,0, -1,1,0
};
static GLfloat uvs[] = {
1,0, 1,1, 0,0,
1,1, 0,1, 0,0
};
const char * Renderer::defaultVertexShader =
"#version 330 core\n"
"\n"
"in vec3 position;\n"
"in vec2 texCoord;\n"
"\n"
"out vec2 uv;\n"
"\n"
"void main(){\n"
" gl_Position = vec4(position, 1);\n"
" uv = texCoord;\n"
"}";
const char * Renderer::defaultFragmentShader =
"#version 330 core\n"
"\n"
"out vec4 color;\n"
"\n"
"in vec2 uv;\n"
"uniform float time;\n"
"uniform vec2 mouse;\n"
"uniform float ration;\n"
"\n"
"void main(){\n"
" color = vec4(cos(uv.x * 5 - time / 1000) / 2 + .5, 0, sin(uv.x * 5 - time / 1000) / 2 + .5, 1);\n"
"}";
/**
* @brief Renderer::Renderer
* @param parent Parent object of the render window
*
* Create a new Renderer with default shader
*/
Renderer::Renderer(QWindow *parent) : Renderer::Renderer("new", defaultFragmentShader, parent){ }
/**
* @brief Renderer::Renderer
* @param filename Name that should shown in the title
* @param instructions Shader code for execution
* @param parent Parent object of the render window
*
* Create a new Renderer with given code and set filename as title
*/
Renderer::Renderer(const QString &filename, const QString &instructions, QWindow *parent) :
QWindow(parent),
clearColor(Qt::black),
context(0), device(0),
time(0),
pendingUpdate(false),
vao(0), uvBuffer(0), audioLeftTexture(0), audioRightTexture(0),
vertexAttr(0), uvAttr(0), timeUniform(0),
shaderProgram(0),
fragmentSource(instructions)
{
setTitle(filename);
m_logger = new QOpenGLDebugLogger( this );
connect(m_logger, SIGNAL(messageLogged(QOpenGLDebugMessage)),
this, SLOT(onMessageLogged(QOpenGLDebugMessage)),
Qt::DirectConnection );
setSurfaceType(QWindow::OpenGLSurface);
time = new QTime();
time->start();
audio = new AudioInputProcessor(this);
connect(audio, SIGNAL(processData(QByteArray)), this, SLOT(updateAudioData(QByteArray)));
audio->start();
QSurfaceFormat format;
format.setMajorVersion(3);
format.setMinorVersion(3);
format.setSamples(4);
format.setProfile(QSurfaceFormat::CoreProfile);
setFormat(format);
}
/**
* @brief Renderer::~Renderer
*
* Free resources
*/
Renderer::~Renderer(){
glDeleteBuffers(1, &uvBuffer);
glDeleteTextures(1, &audioLeftTexture);
glDeleteTextures(1, &audioRightTexture);
delete time;
delete vao;
delete device;
delete m_logger;
}
/**
* @brief Renderer::init
* @return True on success, otherwise false
*
* Allocates grafic memory and initialize the shader program
*/
bool Renderer::init(){
delete vao;
vao = new QOpenGLVertexArrayObject(this);
vao->create();
vao->bind();
glDeleteBuffers(1, &vertexBuffer);
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glDeleteBuffers(1, &uvBuffer);
glGenBuffers(1, &uvBuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
glEnable(GL_TEXTURE_1D);
glDeleteTextures(1, &audioLeftTexture);
glGenTextures(1, &audioLeftTexture);
glDeleteTextures(1, &audioRightTexture);
glGenTextures(1, &audioRightTexture);
glClearColor(0,0,.3,1);
bool result = initShaders(fragmentSource);
vao->release();
return result;
}
/**
* @brief Renderer::initShaders
* @param fragmentShader Code to compile as shader
* @return True on success, otherwise false
*
* Initialze and compile the shader program
*/
bool Renderer::initShaders(const QString &fragmentShader){
QOpenGLShaderProgram *newShaderProgram = new QOpenGLShaderProgram(this);
bool hasError = false;
QString error = "";
if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, defaultVertexShader)){
hasError = true;
error = newShaderProgram->log();
qWarning() << tr("Failed to compile default shader.");
}
if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment,fragmentShader)){
hasError = true;
error = newShaderProgram->log();
if(fragmentShader == defaultFragmentShader)
qWarning() << tr("Failed to compile default shader.");
else if(shaderProgram == 0)
initShaders(defaultFragmentShader);
}
if(!hasError && !newShaderProgram->link()){
hasError = true;
error = newShaderProgram->log();
if(fragmentShader == defaultFragmentShader)
qWarning() << tr("Failed to compile default shader.");
else if(shaderProgram == 0)
initShaders(defaultFragmentShader);
}
if(hasError){
delete newShaderProgram;
//mac :<line>:
//mesa :<line>(<errorcode>):
QRegExp errorline(":([0-9]+)(\\([0-9]+\\))?:");
if(errorline.indexIn(error) > -1){
QString text = errorline.cap(1);
if(text.toInt()-3 > 0) // because: "#define lowp", "#define mediump" and "#define highp"
emit errored(error, text.toInt()-3);
else
emit errored(error, text.toInt());
}
return false;
}
shaderProgramMutex.lock();
if(shaderProgram)
delete shaderProgram;
shaderProgram = newShaderProgram;
vertexAttr = shaderProgram->attributeLocation("position");
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
shaderProgram->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3);
shaderProgram->enableAttributeArray(vertexAttr);
uvAttr = shaderProgram->attributeLocation("texCoord");
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
shaderProgram->setAttributeBuffer("texCoord", GL_FLOAT, 0, 2);
shaderProgram->enableAttributeArray(uvAttr);
timeUniform = shaderProgram->uniformLocation("time");
mouseUniform = shaderProgram->uniformLocation("mouse");
rationUniform = shaderProgram->uniformLocation("ration");
fragmentSource = fragmentShader;
shaderProgramMutex.unlock();
// qDebug() << "vertexAttr" << vertexAttr;
// qDebug() << "uvAttr" << uvAttr;
// qDebug() << "timeUniform" << timeUniform;
// qDebug() << "audioUniform" << audioUniform;
return true;
}
/**
* @brief Renderer::render
*
* Initialize output device, execute the shader and display the result
*/
void Renderer::render(){
if(!device)
device = new QOpenGLPaintDevice();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
device->setSize(size());
// qDebug() << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_VERSION))) << " " << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
const qreal retinaScale = devicePixelRatio();
glViewport(0, 0, width() * retinaScale, height() * retinaScale);
glClear(GL_COLOR_BUFFER_BIT);
QPoint mouse = this->mapFromGlobal(QCursor::pos());
QVector2D mousePosition((float)mouse.x() / (float)this->width(),
(float)mouse.y() / (float)this->height());
float ration = (float)this->width() / (float)this->height();
shaderProgramMutex.lock();
vao->bind();
shaderProgram->bind();
shaderProgram->setUniformValue(mouseUniform,mousePosition);
if(this->height() != 0)
shaderProgram->setUniformValue(rationUniform, ration);
shaderProgram->setUniformValue(timeUniform, (float)time->elapsed());
glDrawArrays(GL_TRIANGLES, 0, 6);
vao->release();
shaderProgramMutex.unlock();
}
/**
* @brief Renderer::renderLater
*
* Enqueue an update event to event queue
*/
void Renderer::renderLater(){
if(!pendingUpdate){
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
pendingUpdate = true;
}
}
/**
* @brief Renderer::renderNow
*
* Use the compiled shader to render on the widget
*/
void Renderer::renderNow(){
pendingUpdate = false;
if(!isExposed())
return;
bool needsInit = false;
if(!context){
context = new QOpenGLContext(this);
context->setFormat(requestedFormat());
context->create();
needsInit = true;
}
context->makeCurrent(this);
if(needsInit){
if (m_logger->initialize()){
m_logger->startLogging( QOpenGLDebugLogger::SynchronousLogging );
m_logger->enableMessages();
}
initializeOpenGLFunctions();
init();
}
if(!shaderProgram)
initShaders(fragmentSource);
if(shaderProgram)
render();
context->swapBuffers(this);
renderLater();
}
/**
* @brief Renderer::event
* @param event The event that should be proccessed
* @return True if the event was successful proccessed, otherwise false
*
* Called if a new event is poped from the event-queue to render on update event
* and emit doneSignal on close event.
*/
bool Renderer::event(QEvent *event){
switch(event->type()){
case QEvent::UpdateRequest:
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
renderNow();
return true;
case QEvent::Close:
emit doneSignal(tr("User closed renderer"));
return true;
default:
return QWindow::event(event);
}
}
/**
* @brief Renderer::exposeEvent
*
* Called if the window is ready to start rendering
*/
void Renderer::exposeEvent(QExposeEvent *){
if(isExposed())
renderNow();
}
/**
* @brief Renderer::updateCode
* @param filename Text for the title
* @param code New shader program code
* @return True on success, otherwise false.
*
* Set new title and compile new code for the shader program
*/
bool Renderer::updateCode(const QString &filename, const QString &code){
if(!initShaders(code))
return false;
setTitle(filename);
show();
return true;
}
/**
* @brief Renderer::updateAudioData
* @param data New audio data
*
* Copy the new sound-data to the graphics memory for visualisation
*/
void Renderer::updateAudioData(QByteArray data){
if(!shaderProgram)
return;
GLenum type, internalType;
Q_UNUSED(internalType);
char typeSize;
switch(audio->format().sampleType() + audio->format().sampleSize()){
case 8: case 10:
type = GL_UNSIGNED_BYTE;
internalType = GL_R8UI;
typeSize = 1;
break;
case 9:
type = GL_BYTE;
internalType = GL_R8I;
typeSize = 1;
break;
case 16: case 18:
type = GL_UNSIGNED_SHORT;
internalType = GL_R16UI;
typeSize = 2;
break;
case 17:
type = GL_SHORT;
internalType = GL_R16I;
typeSize = 2;
break;
case 32: case 34:
type = GL_UNSIGNED_INT;
internalType = GL_R32UI;
typeSize = 4;
break;
case 33:
type = GL_INT;
internalType = GL_R32I;
typeSize = 4;
break;
case 35:
type = GL_FLOAT;
internalType = GL_R32F;
typeSize = 4;
break;
default: return;
}
char *left, *right;
int count = data.size();
if(audio->format().channelCount() == 2){
count /= 2;
left = new char[count];
right = new char[count];
for(int i = 0; i < count; i += typeSize){
for(int j = 0; j < typeSize; ++j){
left [i+j] = data[i*2+j];
right[i+j] = data[i*2+j+typeSize];
}
}
}else
left = right = data.data();
shaderProgramMutex.lock();
shaderProgram->bind();
glBindTexture(GL_TEXTURE_1D, audioLeftTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, left);
glBindTexture(GL_TEXTURE_1D, audioRightTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, right);
shaderProgram->release();
shaderProgramMutex.unlock();
if(left != data.data())
delete[] left;
if(right != data.data())
delete[] right;
}
/**
* @brief Renderer::onMessageLogged
* @param message Message text
*
* Write the message text in the debug output
*/
void Renderer::onMessageLogged(QOpenGLDebugMessage message){
qDebug() << message;
}
<|endoftext|> |
<commit_before>#include "paxos/parliament.hpp"
Parliament::Parliament(
Replica legislator,
std::string location,
DecreeHandler decree_handler)
: signal(std::make_shared<Signal>()),
legislator(legislator),
legislators(LoadReplicaSet(
std::ifstream(
(fs::path(location) / fs::path(ReplicasetFilename)).string()))),
receiver(std::make_shared<NetworkReceiver<BoostServer>>(
legislator.hostname, legislator.port)),
sender(std::make_shared<NetworkSender<BoostTransport>>(legislators)),
bootstrap(
std::make_shared<BootstrapListener<BoostServer>>(
legislators,
legislator.hostname,
legislator.port + 1
)
),
ledger(std::make_shared<Ledger>(
std::make_shared<PersistentQueue<Decree>>(location, "paxos.ledger"),
decree_handler,
DecreeHandler([this, location, legislator](std::string entry){
SystemOperation op = Deserialize<SystemOperation>(entry);
if (op.operation == SystemOperationType::AddReplica)
{
legislators->Add(op.replica);
std::ofstream replicasetfile(
(fs::path(location) /
fs::path(ReplicasetFilename)).string());
SaveReplicaSet(legislators, replicasetfile);
// Only decree author sends bootstrap.
if (op.author.hostname == legislator.hostname &&
op.author.port == legislator.port)
{
SendBootstrap<BoostTransport>(
op.replica,
Deserialize<BootstrapMetadata>(op.content));
}
}
else if (op.operation == SystemOperationType::RemoveReplica)
{
legislators->Remove(op.replica);
std::ofstream replicasetfile(
(fs::path(op.content) /
fs::path(ReplicasetFilename)).string());
SaveReplicaSet(legislators, replicasetfile);
}
signal->Set();
}))),
learner(std::make_shared<LearnerContext>(legislators, ledger)),
location(location)
{
auto acceptor = std::make_shared<AcceptorContext>(
std::make_shared<PersistentDecree>(location, "paxos.promised_decree"),
std::make_shared<PersistentDecree>(location, "paxos.accepted_decree"));
hookup_legislator(legislator, acceptor);
}
Parliament::Parliament(const Parliament& other)
: signal(other.signal),
legislator(other.legislator),
legislators(other.legislators),
receiver(other.receiver),
sender(other.sender),
bootstrap(other.bootstrap),
ledger(other.ledger),
learner(other.learner),
location(other.location)
{
}
Parliament::Parliament(
Replica legislator,
std::shared_ptr<ReplicaSet> legislators,
std::shared_ptr<Ledger> ledger,
std::shared_ptr<Receiver> receiver,
std::shared_ptr<Sender> sender,
std::shared_ptr<AcceptorContext> acceptor
) :
signal(std::make_shared<Signal>()),
legislators(legislators),
receiver(receiver),
sender(sender),
ledger(ledger),
learner(std::make_shared<LearnerContext>(legislators, ledger))
{
signal->Set();
hookup_legislator(legislator, acceptor);
}
void
Parliament::hookup_legislator(
Replica replica,
std::shared_ptr<AcceptorContext> acceptor)
{
auto proposer = std::make_shared<ProposerContext>(
legislators,
ledger
);
auto updater = std::make_shared<UpdaterContext>(ledger);
RegisterProposer(
receiver,
sender,
proposer
);
RegisterAcceptor(
receiver,
sender,
acceptor
);
RegisterLearner(
receiver,
sender,
learner
);
RegisterUpdater(
receiver,
sender,
updater
);
}
void
Parliament::AddLegislator(
std::string address,
short port,
std::string remote)
{
Decree d;
d.type = DecreeType::SystemDecree;
d.content = Serialize(
SystemOperation(
SystemOperationType::AddReplica,
legislator,
0,
Replica(address, port),
Serialize(
BootstrapMetadata
{
location,
remote
}
)
)
);
send_decree(d);
signal->Wait();
}
void
Parliament::RemoveLegislator(
std::string address,
short port,
std::string remote)
{
Decree d;
d.type = DecreeType::SystemDecree;
d.content = Serialize(
SystemOperation(
SystemOperationType::RemoveReplica,
legislator,
0,
Replica(address, port),
Serialize(
BootstrapMetadata
{
location,
remote
}
)
)
);
send_decree(d);
signal->Wait();
}
void
Parliament::SendProposal(std::string entry)
{
Decree d;
d.content = entry;
send_decree(d);
}
void
Parliament::send_decree(Decree d)
{
Message m(
d,
legislator,
legislator,
MessageType::RequestMessage);
sender->Reply(m);
}
AbsenteeBallots
Parliament::GetAbsenteeBallots(int max_ballots)
{
std::map<Decree, std::shared_ptr<ReplicaSet>, compare_decree> ballots;
int current = 0;
for (auto vote : learner->accepted_map)
{
if (current <= max_ballots)
{
ballots[vote.first] = learner->replicaset->Difference(vote.second);
}
current += 1;
}
return ballots;
}
void
Parliament::SetActive()
{
learner->is_observer = false;
}
void
Parliament::SetInactive()
{
learner->is_observer = true;
}
<commit_msg>Fix remove legislator to update replicaset<commit_after>#include "paxos/parliament.hpp"
Parliament::Parliament(
Replica legislator,
std::string location,
DecreeHandler decree_handler)
: signal(std::make_shared<Signal>()),
legislator(legislator),
legislators(LoadReplicaSet(
std::ifstream(
(fs::path(location) / fs::path(ReplicasetFilename)).string()))),
receiver(std::make_shared<NetworkReceiver<BoostServer>>(
legislator.hostname, legislator.port)),
sender(std::make_shared<NetworkSender<BoostTransport>>(legislators)),
bootstrap(
std::make_shared<BootstrapListener<BoostServer>>(
legislators,
legislator.hostname,
legislator.port + 1
)
),
ledger(std::make_shared<Ledger>(
std::make_shared<PersistentQueue<Decree>>(location, "paxos.ledger"),
decree_handler,
DecreeHandler([this, location, legislator](std::string entry){
SystemOperation op = Deserialize<SystemOperation>(entry);
if (op.operation == SystemOperationType::AddReplica)
{
legislators->Add(op.replica);
std::ofstream replicasetfile(
(fs::path(location) /
fs::path(ReplicasetFilename)).string());
SaveReplicaSet(legislators, replicasetfile);
// Only decree author sends bootstrap.
if (op.author.hostname == legislator.hostname &&
op.author.port == legislator.port)
{
SendBootstrap<BoostTransport>(
op.replica,
Deserialize<BootstrapMetadata>(op.content));
}
}
else if (op.operation == SystemOperationType::RemoveReplica)
{
legislators->Remove(op.replica);
std::ofstream replicasetfile(
(fs::path(location) /
fs::path(ReplicasetFilename)).string());
SaveReplicaSet(legislators, replicasetfile);
}
signal->Set();
}))),
learner(std::make_shared<LearnerContext>(legislators, ledger)),
location(location)
{
auto acceptor = std::make_shared<AcceptorContext>(
std::make_shared<PersistentDecree>(location, "paxos.promised_decree"),
std::make_shared<PersistentDecree>(location, "paxos.accepted_decree"));
hookup_legislator(legislator, acceptor);
}
Parliament::Parliament(const Parliament& other)
: signal(other.signal),
legislator(other.legislator),
legislators(other.legislators),
receiver(other.receiver),
sender(other.sender),
bootstrap(other.bootstrap),
ledger(other.ledger),
learner(other.learner),
location(other.location)
{
}
Parliament::Parliament(
Replica legislator,
std::shared_ptr<ReplicaSet> legislators,
std::shared_ptr<Ledger> ledger,
std::shared_ptr<Receiver> receiver,
std::shared_ptr<Sender> sender,
std::shared_ptr<AcceptorContext> acceptor
) :
signal(std::make_shared<Signal>()),
legislators(legislators),
receiver(receiver),
sender(sender),
ledger(ledger),
learner(std::make_shared<LearnerContext>(legislators, ledger))
{
signal->Set();
hookup_legislator(legislator, acceptor);
}
void
Parliament::hookup_legislator(
Replica replica,
std::shared_ptr<AcceptorContext> acceptor)
{
auto proposer = std::make_shared<ProposerContext>(
legislators,
ledger
);
auto updater = std::make_shared<UpdaterContext>(ledger);
RegisterProposer(
receiver,
sender,
proposer
);
RegisterAcceptor(
receiver,
sender,
acceptor
);
RegisterLearner(
receiver,
sender,
learner
);
RegisterUpdater(
receiver,
sender,
updater
);
}
void
Parliament::AddLegislator(
std::string address,
short port,
std::string remote)
{
Decree d;
d.type = DecreeType::SystemDecree;
d.content = Serialize(
SystemOperation(
SystemOperationType::AddReplica,
legislator,
0,
Replica(address, port),
Serialize(
BootstrapMetadata
{
location,
remote
}
)
)
);
send_decree(d);
signal->Wait();
}
void
Parliament::RemoveLegislator(
std::string address,
short port,
std::string remote)
{
Decree d;
d.type = DecreeType::SystemDecree;
d.content = Serialize(
SystemOperation(
SystemOperationType::RemoveReplica,
legislator,
0,
Replica(address, port),
Serialize(
BootstrapMetadata
{
location,
remote
}
)
)
);
send_decree(d);
signal->Wait();
}
void
Parliament::SendProposal(std::string entry)
{
Decree d;
d.content = entry;
send_decree(d);
}
void
Parliament::send_decree(Decree d)
{
Message m(
d,
legislator,
legislator,
MessageType::RequestMessage);
sender->Reply(m);
}
AbsenteeBallots
Parliament::GetAbsenteeBallots(int max_ballots)
{
std::map<Decree, std::shared_ptr<ReplicaSet>, compare_decree> ballots;
int current = 0;
for (auto vote : learner->accepted_map)
{
if (current <= max_ballots)
{
ballots[vote.first] = learner->replicaset->Difference(vote.second);
}
current += 1;
}
return ballots;
}
void
Parliament::SetActive()
{
learner->is_observer = false;
}
void
Parliament::SetInactive()
{
learner->is_observer = true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#include "hpp/pinocchio/center-of-mass-computation.hh"
#include <algorithm>
#include <boost/foreach.hpp>
#include <pinocchio/algorithm/center-of-mass.hpp>
#include <pinocchio/algorithm/copy.hpp>
#include <hpp/util/exception-factory.hh>
#include "hpp/pinocchio/joint.hh"
#include <hpp/pinocchio/joint-collection.hh>
#include "hpp/pinocchio/device.hh"
namespace hpp {
namespace pinocchio {
CenterOfMassComputationPtr_t CenterOfMassComputation::create (
const DevicePtr_t& d)
{
return CenterOfMassComputationPtr_t (new CenterOfMassComputation (d));
}
void CenterOfMassComputation::compute (const Computation_t& flag)
{
const Model& model = robot_->model();
bool computeCOM = (flag & COM);
bool computeJac = (flag & JACOBIAN);
assert(computeCOM && "This does nothing");
assert (!(computeJac && !computeCOM)); // JACOBIAN => COM
// update kinematics
::pinocchio::copy(model,robot_->data(),data,0);
data.mass[0] = 0;
if(computeCOM) data.com[0].setZero();
if(computeJac) data.Jcom.setZero();
// Propagate COM initialization on all joints.
// Could be done only on subtree, with minor gain (possibly loss because of
// more difficult branch prediction). I dont recommend to implement it.
for(JointIndex jid=1;jid<JointIndex(model.joints.size());++jid)
{
const double & mass = model.inertias[jid].mass ();
data.mass[jid] = mass;
data.com [jid] = mass*data.oMi[jid].act (model.inertias[jid].lever());
}
// Nullify non-subtree com and mass.
std::size_t root = 0;
for(std::size_t jid=1; jid<model.joints.size(); ++jid )
{
const std::size_t& rootId = roots_[root];
if(jid == rootId)
{
jid = (std::size_t)data.lastChild[rootId];
root ++;
}
else
{
data.mass[jid] = 0;
data.com [jid] .setZero();
}
}
// TODO as of now, it is not possible to access the template parameter
// JointCollectionTpl of Model so we use the default one.
typedef ::pinocchio::JacobianCenterOfMassBackwardStep<Model::Scalar,
Model::Options, JointCollectionTpl> Pass;
// Assume root is sorted from smallest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots_.size()-1); root>=0; --root )
{
std::size_t rootId = roots_[(std::size_t)root];
// Backward loop on descendents of joint rootId.
for( JointIndex jid = (JointIndex)data.lastChild[rootId];jid>=rootId;--jid )
{
if(computeJac)
Pass::run(model.joints[jid],data.joints[jid],
Pass::ArgsType(model,data,false));
else
{
assert(computeCOM);
const JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
}
//std::cout << data.oMi [jid] << std::endl;
//std::cout << data.mass[jid] << std::endl;
//std::cout << data.com [jid].transpose() << std::endl;
} // end for jid
// Backward loop on ancestors of joint rootId
JointIndex jid = model.parents[rootId]; // loop variable
rootId = (root>0) ? roots_[(std::size_t)(root-1)] : 0; // root of previous subtree in roots_
while (jid>rootId) // stop when meeting the next subtree
{
const JointIndex & parent = model.parents[jid];
if(computeJac)
Pass::run(model.joints[jid],data.joints[jid],
Pass::ArgsType(model,data,false));
else
{
assert(computeCOM);
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
}
jid = parent;
} // end while
} // end for root in roots_
if(computeCOM) data.com[0] /= data.mass[0];
if(computeJac) data.Jcom /= data.mass[0];
}
CenterOfMassComputation::CenterOfMassComputation (const DevicePtr_t& d) :
robot_(d), roots_ (), //mass_ (0), jacobianCom_ (3, d->numberDof ())
data(d->model())
{ assert (d->modelPtr()); }
void CenterOfMassComputation::add (const JointPtr_t& j)
{
JointIndex jid = j->index();
BOOST_FOREACH( const JointIndex rootId, roots_ )
{
assert (std::size_t(rootId)<robot_->model().joints.size());
// Assert that the new root is not in already-recorded subtrees.
if( (jid >= rootId) && (data.lastChild[rootId] >= int(jid)) )
// We are doing something stupid. Should we throw an error
// or just return silently ?
HPP_THROW(std::invalid_argument, "Joint " << j->name()
<< " (" << jid << ") is already in a subtree ["
<< rootId << ", " << data.lastChild[rootId] << "]");
}
roots_.push_back(jid);
}
CenterOfMassComputation::~CenterOfMassComputation ()
{}
} // namespace pinocchio
} // namespace hpp
<commit_msg>Compatibility with Pinocchio v2.1.6<commit_after>// Copyright (c) 2016, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#include "hpp/pinocchio/center-of-mass-computation.hh"
#include <algorithm>
#include <boost/foreach.hpp>
#include <pinocchio/algorithm/center-of-mass.hpp>
#include <pinocchio/algorithm/copy.hpp>
#include <hpp/util/exception-factory.hh>
#include "hpp/pinocchio/joint.hh"
#include <hpp/pinocchio/joint-collection.hh>
#include "hpp/pinocchio/device.hh"
namespace hpp {
namespace pinocchio {
CenterOfMassComputationPtr_t CenterOfMassComputation::create (
const DevicePtr_t& d)
{
return CenterOfMassComputationPtr_t (new CenterOfMassComputation (d));
}
void CenterOfMassComputation::compute (const Computation_t& flag)
{
const Model& model = robot_->model();
bool computeCOM = (flag & COM);
bool computeJac = (flag & JACOBIAN);
assert(computeCOM && "This does nothing");
assert (!(computeJac && !computeCOM)); // JACOBIAN => COM
// update kinematics
::pinocchio::copy(model,robot_->data(),data,0);
data.mass[0] = 0;
if(computeCOM) data.com[0].setZero();
if(computeJac) data.Jcom.setZero();
// Propagate COM initialization on all joints.
// Could be done only on subtree, with minor gain (possibly loss because of
// more difficult branch prediction). I dont recommend to implement it.
for(JointIndex jid=1;jid<JointIndex(model.joints.size());++jid)
{
const double & mass = model.inertias[jid].mass ();
data.mass[jid] = mass;
data.com [jid] = mass*data.oMi[jid].act (model.inertias[jid].lever());
}
// Nullify non-subtree com and mass.
std::size_t root = 0;
for(std::size_t jid=1; jid<model.joints.size(); ++jid )
{
const std::size_t& rootId = roots_[root];
if(jid == rootId)
{
jid = (std::size_t)data.lastChild[rootId];
root ++;
}
else
{
data.mass[jid] = 0;
data.com [jid] .setZero();
}
}
// TODO as of now, it is not possible to access the template parameter
// JointCollectionTpl of Model so we use the default one.
typedef ::pinocchio::JacobianCenterOfMassBackwardStep<Model::Scalar,
Model::Options, JointCollectionTpl
#if PINOCCHIO_VERSION_AT_LEAST(2,1,6)
,Data::Matrix3x
#endif
> Pass;
// Assume root is sorted from smallest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots_.size()-1); root>=0; --root )
{
std::size_t rootId = roots_[(std::size_t)root];
// Backward loop on descendents of joint rootId.
for( JointIndex jid = (JointIndex)data.lastChild[rootId];jid>=rootId;--jid )
{
if(computeJac)
Pass::run(model.joints[jid],data.joints[jid],
Pass::ArgsType(model,data,
#if PINOCCHIO_VERSION_AT_LEAST(2,1,6)
data.Jcom,
#endif
false));
else
{
assert(computeCOM);
const JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
}
//std::cout << data.oMi [jid] << std::endl;
//std::cout << data.mass[jid] << std::endl;
//std::cout << data.com [jid].transpose() << std::endl;
} // end for jid
// Backward loop on ancestors of joint rootId
JointIndex jid = model.parents[rootId]; // loop variable
rootId = (root>0) ? roots_[(std::size_t)(root-1)] : 0; // root of previous subtree in roots_
while (jid>rootId) // stop when meeting the next subtree
{
const JointIndex & parent = model.parents[jid];
if(computeJac)
Pass::run(model.joints[jid],data.joints[jid],
Pass::ArgsType(model,data,
#if PINOCCHIO_VERSION_AT_LEAST(2,1,6)
data.Jcom,
#endif
false));
else
{
assert(computeCOM);
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
}
jid = parent;
} // end while
} // end for root in roots_
if(computeCOM) data.com[0] /= data.mass[0];
if(computeJac) data.Jcom /= data.mass[0];
}
CenterOfMassComputation::CenterOfMassComputation (const DevicePtr_t& d) :
robot_(d), roots_ (), //mass_ (0), jacobianCom_ (3, d->numberDof ())
data(d->model())
{ assert (d->modelPtr()); }
void CenterOfMassComputation::add (const JointPtr_t& j)
{
JointIndex jid = j->index();
BOOST_FOREACH( const JointIndex rootId, roots_ )
{
assert (std::size_t(rootId)<robot_->model().joints.size());
// Assert that the new root is not in already-recorded subtrees.
if( (jid >= rootId) && (data.lastChild[rootId] >= int(jid)) )
// We are doing something stupid. Should we throw an error
// or just return silently ?
HPP_THROW(std::invalid_argument, "Joint " << j->name()
<< " (" << jid << ") is already in a subtree ["
<< rootId << ", " << data.lastChild[rootId] << "]");
}
roots_.push_back(jid);
}
CenterOfMassComputation::~CenterOfMassComputation ()
{}
} // namespace pinocchio
} // namespace hpp
<|endoftext|> |
<commit_before>/**
* @file PathPlanner.cpp
*
* @author <a href="mailto:[email protected]">Yigit Can Akcay</a>
* Implementation of class PathPlanner
*/
#include "PathPlanner.h"
PathPlanner::PathPlanner()
:
step_buffer({}),
foot_to_use(Foot::RIGHT),
last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1
kick_planned(false)
{
DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false);
getDebugParameterList().add(¶ms);
}
PathPlanner::~PathPlanner()
{
getDebugParameterList().remove(¶ms);
}
void PathPlanner::execute()
{
// --- DEBUG REQUESTS ---
DEBUG_REQUEST("PathPlanner:walk_to_ball",
if (getBallModel().positionPreview.x > 250) {
walk_to_ball(Foot::NONE);
}
);
// --- DEBUG REQUESTS ---
getPathModel().kick_executed = false;
STOPWATCH_START("PathPlanner");
// Always executed first
manage_step_buffer();
// The kick has been executed
// Tells XABSL to jump into next state
if (kick_planned && step_buffer.empty()) {
getPathModel().kick_executed = true;
}
// HACK: xabsl set a firced motion request => clear everything
if(getPathModel().path_routine == PathModel::PathRoutine::NONE && getMotionRequest().forced) {
step_buffer.clear();
return;
}
switch (getPathModel().path_routine)
{
case PathModel::PathRoutine::NONE:
// There is no kick planned, since the kick has been executed
// and XABSL is in a different state now
if (kick_planned) {
kick_planned = false;
}
if (step_buffer.empty()) {
return;
}
break;
case PathModel::PathRoutine::GO_TO_BALL_FAST:
walk_to_ball(Foot::NONE , true);
break;
case PathModel::PathRoutine::GO_TO_BALL_SLOW:
walk_to_ball(Foot::NONE);
break;
case PathModel::PathRoutine::MOVE_AROUND_BALL:
move_around_ball(getPathModel().direction, getPathModel().radius);
break;
case PathModel::PathRoutine::APPROACH_BALL_LEFT:
approach_ball(Foot::LEFT);
break;
case PathModel::PathRoutine::APPROACH_BALL_RIGHT:
approach_ball(Foot::RIGHT);
break;
case PathModel::PathRoutine::SHORT_KICK_LEFT:
short_kick(Foot::LEFT);
break;
case PathModel::PathRoutine::SHORT_KICK_RIGHT:
short_kick(Foot::RIGHT);
break;
case PathModel::PathRoutine::LONG_KICK_LEFT:
long_kick(Foot::LEFT);
break;
case PathModel::PathRoutine::LONG_KICK_RIGHT:
long_kick(Foot::RIGHT);
break;
case PathModel::PathRoutine::SIDEKICK_LEFT:
sidekick(Foot::LEFT);
break;
case PathModel::PathRoutine::SIDEKICK_RIGHT:
sidekick(Foot::RIGHT);
break;
}
// Always executed last
execute_step_buffer();
STOPWATCH_STOP("PathPlanner");
}
void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast)
{
Vector2d ballPos = Vector2d();
double ballRadius = getFieldInfo().ballRadius;
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
ballPos = getBallModel().positionPreviewInLFoot;
coordinate = WalkRequest::LFoot;
break;
case Foot::RIGHT:
ballPos = getBallModel().positionPreviewInRFoot;
coordinate = WalkRequest::RFoot;
break;
case Foot::NONE:
ballPos = getBallModel().positionPreview;
coordinate = WalkRequest::Hip;
break;
}
double ballRotation = ballPos.angle();
Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance - ballRadius), ballPos.y };
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
if (go_fast)
{
double character = 1.0;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
double character = 0.3;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
}
else
{
update_step(pose);
}
}
void PathPlanner::move_around_ball(const double direction, const double radius)
{
Vector2d ballPos = getBallModel().positionPreview;
double ballRotation = ballPos.angle();
double ballDistance = ballPos.abs();
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
double min1;
double min2;
double max1;
double max2;
if (direction <= 0)
{
min1 = 0.0;
min2 = 0.0;
max1 = 45.0;
max2 = 100.0;
}
else {
min1 = -45;
min2 = -100;
max1 = 0;
max2 = 0;
}
double stepX = (ballDistance - radius) * std::cos(ballRotation);
double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation);
Pose2D pose = { ballRotation, stepX, stepY };
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double character = 0.7;
Foot foot = Foot::NONE;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
update_step(pose);
}
}
void PathPlanner::approach_ball(const Foot foot)
{
Vector2d ballPos = Vector2d();
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
double stepX = 0.0;
double stepY = 0.0;
double ballRadius = getFieldInfo().ballRadius;
double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0;
switch (foot) {
case Foot::LEFT:
ballPos = getBallModel().positionPreviewInLFoot;
coordinate = WalkRequest::LFoot;
stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius;
stepY = ballPos.y - getPathModel().yOffset;
break;
case Foot::RIGHT:
ballPos = getBallModel().positionPreviewInRFoot;
coordinate = WalkRequest::RFoot;
stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius;
stepY = ballPos.y + getPathModel().yOffset;
break;
case Foot::NONE:
ASSERT(false);
}
//if (ballPos.x < getPathModel().distance + 30 && ballPos.x > getPathModel().distance - 30)
if (stepX < 0 && ballPos.x > getPathModel().distance + 30)
{
stepX = 0;
}
const double slow_down_factor = 0.7;
Pose2D pose;
if ( params.approach_ball_adapt_control
&& Vector2d(stepX, stepY).abs() < params.approach_ball_adapt_threshold)
{
pose = { stepRotation, stepX, stepY };
}
else
{
pose = { stepRotation, slow_down_factor * stepX, slow_down_factor * stepY };
}
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double character = 0.7;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
update_step(pose);
}
}
void PathPlanner::short_kick(const Foot foot)
{
if (!kick_planned)
{
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::RFoot;
break;
case Foot::RIGHT:
coordinate = WalkRequest::LFoot;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500 , 0.0 };
StepType type = StepType::KICKSTEP;
double character = 1.0;
double scale = 0.7;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
void PathPlanner::long_kick(const Foot foot)
{
if (!kick_planned)
{
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::RFoot;
break;
case Foot::RIGHT:
coordinate = WalkRequest::LFoot;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500, 0.0 };
StepType type = StepType::KICKSTEP;
double character = 1.0;
double scale = 0.7;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
void PathPlanner::sidekick(const Foot foot)
{
if (!kick_planned)
{
double speed_direction = Math::fromDegrees(0.0);
double stepY = 0.0;
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::LFoot;
speed_direction = Math::fromDegrees(90);
stepY = 100;
break;
case Foot::RIGHT:
coordinate = WalkRequest::RFoot;
speed_direction = Math::fromDegrees(-90);
stepY = -100;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500, stepY };
StepType type = StepType::KICKSTEP;
double character = 1.0;
Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT;
double scale = params.sidekick_scale;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
// Stepcontrol
void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected)
{
step_buffer.push_back(Step_Buffer_Element({ pose,
speedDirection,
type,
type == StepType::KICKSTEP ? params.kick_time : 250,
character,
scale,
foot,
coordinate,
restriction,
isProtected}));
}
void PathPlanner::update_step(Pose2D &pose)
{
ASSERT(step_buffer.size() > 0);
step_buffer.front().pose = pose;
}
void PathPlanner::manage_step_buffer()
{
if (step_buffer.empty()) {
return;
}
// requested step has been accepted
if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID)
{
step_buffer.erase(step_buffer.begin());
last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1;
}
}
void PathPlanner::execute_step_buffer()
{
STOPWATCH_START("PathPlanner:execute_steplist");
if (step_buffer.empty()) {
return;
}
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate;
getMotionRequest().walkRequest.character = step_buffer.front().character;
getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale;
getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID;
getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type;
getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time;
getMotionRequest().walkRequest.stepControl.speedDirection = Math::fromDegrees(step_buffer.front().speedDirection);
getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose;
getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction;
getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected;
getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID;
// normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified
if (step_buffer.front().foot == Foot::NONE)
{
switch (getMotionStatus().stepControl.moveableFoot)
{
case MotionStatus::StepControlStatus::LEFT:
foot_to_use = Foot::LEFT;
break;
case MotionStatus::StepControlStatus::RIGHT:
foot_to_use = Foot::RIGHT;
break;
case MotionStatus::StepControlStatus::BOTH:
if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f)
{
foot_to_use = Foot::LEFT;
}
else
{
foot_to_use = Foot::RIGHT;
}
break;
case MotionStatus::StepControlStatus::NONE:
foot_to_use = Foot::RIGHT;
break;
}
}
else
{
foot_to_use = step_buffer.front().foot;
}
// false means right foot
getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT);
STOPWATCH_STOP("PathPlanner:execute_steplist");
}
<commit_msg>should have been commited<commit_after>/**
* @file PathPlanner.cpp
*
* @author <a href="mailto:[email protected]">Yigit Can Akcay</a>
* Implementation of class PathPlanner
*/
#include "PathPlanner.h"
PathPlanner::PathPlanner()
:
step_buffer({}),
foot_to_use(Foot::RIGHT),
last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1
kick_planned(false)
{
DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false);
getDebugParameterList().add(¶ms);
}
PathPlanner::~PathPlanner()
{
getDebugParameterList().remove(¶ms);
}
void PathPlanner::execute()
{
// --- DEBUG REQUESTS ---
DEBUG_REQUEST("PathPlanner:walk_to_ball",
if (getBallModel().positionPreview.x > 250) {
walk_to_ball(Foot::NONE);
}
);
// --- DEBUG REQUESTS ---
getPathModel().kick_executed = false;
STOPWATCH_START("PathPlanner");
// Always executed first
manage_step_buffer();
// The kick has been executed
// Tells XABSL to jump into next state
if (kick_planned && step_buffer.empty()) {
getPathModel().kick_executed = true;
}
// HACK: xabsl set a firced motion request => clear everything
if(getPathModel().path_routine == PathModel::PathRoutine::NONE && getMotionRequest().forced) {
step_buffer.clear();
return;
}
switch (getPathModel().path_routine)
{
case PathModel::PathRoutine::NONE:
// There is no kick planned, since the kick has been executed
// and XABSL is in a different state now
if (kick_planned) {
kick_planned = false;
}
if (step_buffer.empty()) {
return;
}
break;
case PathModel::PathRoutine::GO_TO_BALL_FAST:
walk_to_ball(Foot::NONE , true);
break;
case PathModel::PathRoutine::GO_TO_BALL_SLOW:
walk_to_ball(Foot::NONE);
break;
case PathModel::PathRoutine::MOVE_AROUND_BALL:
move_around_ball(getPathModel().direction, getPathModel().radius);
break;
case PathModel::PathRoutine::APPROACH_BALL_LEFT:
approach_ball(Foot::LEFT);
break;
case PathModel::PathRoutine::APPROACH_BALL_RIGHT:
approach_ball(Foot::RIGHT);
break;
case PathModel::PathRoutine::SHORT_KICK_LEFT:
short_kick(Foot::LEFT);
break;
case PathModel::PathRoutine::SHORT_KICK_RIGHT:
short_kick(Foot::RIGHT);
break;
case PathModel::PathRoutine::LONG_KICK_LEFT:
long_kick(Foot::LEFT);
break;
case PathModel::PathRoutine::LONG_KICK_RIGHT:
long_kick(Foot::RIGHT);
break;
case PathModel::PathRoutine::SIDEKICK_LEFT:
sidekick(Foot::LEFT);
break;
case PathModel::PathRoutine::SIDEKICK_RIGHT:
sidekick(Foot::RIGHT);
break;
}
// Always executed last
execute_step_buffer();
STOPWATCH_STOP("PathPlanner");
}
void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast)
{
Vector2d ballPos = Vector2d();
double ballRadius = getFieldInfo().ballRadius;
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
ballPos = getBallModel().positionPreviewInLFoot;
coordinate = WalkRequest::LFoot;
break;
case Foot::RIGHT:
ballPos = getBallModel().positionPreviewInRFoot;
coordinate = WalkRequest::RFoot;
break;
case Foot::NONE:
ballPos = getBallModel().positionPreview;
coordinate = WalkRequest::Hip;
break;
}
double ballRotation = ballPos.angle();
Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance - ballRadius), ballPos.y };
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
if (go_fast)
{
double character = 1.0;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
double character = 0.3;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
}
else
{
update_step(pose);
}
}
void PathPlanner::move_around_ball(const double direction, const double radius)
{
Vector2d ballPos = getBallModel().positionPreview;
double ballRotation = ballPos.angle();
double ballDistance = ballPos.abs();
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
double min1;
double min2;
double max1;
double max2;
if (direction <= 0)
{
min1 = 0.0;
min2 = 0.0;
max1 = 45.0;
max2 = 100.0;
}
else {
min1 = -45;
min2 = -100;
max1 = 0;
max2 = 0;
}
double stepX = (ballDistance - radius) * std::cos(ballRotation);
double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation);
Pose2D pose = { ballRotation, stepX, stepY };
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double character = 0.7;
Foot foot = Foot::NONE;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
update_step(pose);
}
}
void PathPlanner::approach_ball(const Foot foot)
{
Vector2d ballPos = Vector2d();
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
double stepX = 0.0;
double stepY = 0.0;
double ballRadius = getFieldInfo().ballRadius;
double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0;
switch (foot) {
case Foot::LEFT:
ballPos = getBallModel().positionPreviewInLFoot;
coordinate = WalkRequest::LFoot;
stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius;
stepY = ballPos.y - getPathModel().yOffset;
break;
case Foot::RIGHT:
ballPos = getBallModel().positionPreviewInRFoot;
coordinate = WalkRequest::RFoot;
stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius;
stepY = ballPos.y + getPathModel().yOffset;
break;
case Foot::NONE:
ASSERT(false);
}
//if (ballPos.x < getPathModel().distance + 30 && ballPos.x > getPathModel().distance - 30)
if (stepX < 0 && ballPos.x > getPathModel().distance + 30)
{
stepX = 0;
}
const double slow_down_factor = 0.7;
Pose2D pose;
if ( params.approach_ball_adapt_control
&& Vector2d(stepX, stepY).abs() < params.approach_ball_adapt_threshold)
{
pose = { stepRotation, stepX, stepY };
}
else
{
pose = { stepRotation, slow_down_factor * stepX, slow_down_factor * stepY };
}
if (step_buffer.empty())
{
StepType type = StepType::WALKSTEP;
double character = 0.7;
double scale = 1.0;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false);
}
else
{
update_step(pose);
}
}
void PathPlanner::short_kick(const Foot foot)
{
if (!kick_planned)
{
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::RFoot;
break;
case Foot::RIGHT:
coordinate = WalkRequest::LFoot;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500 , 0.0 };
StepType type = StepType::KICKSTEP;
double character = 1.0;
double scale = 0.7;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
void PathPlanner::long_kick(const Foot foot)
{
if (!kick_planned)
{
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::RFoot;
break;
case Foot::RIGHT:
coordinate = WalkRequest::LFoot;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500, 0.0 };
StepType type = StepType::KICKSTEP;
double character = 1.0;
double scale = 0.7;
double speed_direction = Math::fromDegrees(0.0);
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
void PathPlanner::sidekick(const Foot foot)
{
if (!kick_planned)
{
double speed_direction = Math::fromDegrees(0.0);
double stepY = 0.0;
WalkRequest::Coordinate coordinate = WalkRequest::Hip;
switch (foot) {
case Foot::LEFT:
coordinate = WalkRequest::LFoot;
speed_direction = Math::fromDegrees(90);
stepY = 100;
break;
case Foot::RIGHT:
coordinate = WalkRequest::RFoot;
speed_direction = Math::fromDegrees(-90);
stepY = -100;
break;
case Foot::NONE:
ASSERT(false);
}
if (step_buffer.empty())
{
Pose2D pose = { 0.0, 500, stepY };
StepType type = StepType::KICKSTEP;
double character = 1.0;
Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT;
double scale = params.sidekick_scale;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
type = StepType::ZEROSTEP;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true);
pose = { 0.0, 0.0, 0.0 };
type = StepType::WALKSTEP;
add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true);
kick_planned = true;
}
}
}
// Stepcontrol
void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected)
{
step_buffer.push_back(Step_Buffer_Element({ pose,
speedDirection,
type,
type == StepType::KICKSTEP ? params.kick_time : 250,
character,
scale,
foot,
coordinate,
restriction,
isProtected}));
}
void PathPlanner::update_step(Pose2D &pose)
{
ASSERT(step_buffer.size() > 0);
step_buffer.front().pose = pose;
}
void PathPlanner::manage_step_buffer()
{
if (step_buffer.empty()) {
return;
}
// requested step has been accepted
if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID)
{
step_buffer.erase(step_buffer.begin());
last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1;
}
}
void PathPlanner::execute_step_buffer()
{
STOPWATCH_START("PathPlanner:execute_steplist");
if (step_buffer.empty()) {
return;
}
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate;
getMotionRequest().walkRequest.character = step_buffer.front().character;
getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale;
getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID;
getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type;
getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time;
getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection;
getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose;
getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction;
getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected;
getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID;
// normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified
if (step_buffer.front().foot == Foot::NONE)
{
switch (getMotionStatus().stepControl.moveableFoot)
{
case MotionStatus::StepControlStatus::LEFT:
foot_to_use = Foot::LEFT;
break;
case MotionStatus::StepControlStatus::RIGHT:
foot_to_use = Foot::RIGHT;
break;
case MotionStatus::StepControlStatus::BOTH:
if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f)
{
foot_to_use = Foot::LEFT;
}
else
{
foot_to_use = Foot::RIGHT;
}
break;
case MotionStatus::StepControlStatus::NONE:
foot_to_use = Foot::RIGHT;
break;
}
}
else
{
foot_to_use = step_buffer.front().foot;
}
// false means right foot
getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT);
STOPWATCH_STOP("PathPlanner:execute_steplist");
}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
// $Id: tria.cc 32807 2014-04-22 15:01:57Z heister $
//
// Copyright (C) 2015 - 2017 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/base/utilities.h>
#include <deal.II/base/mpi.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/filtered_iterator.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/distributed/shared_tria.h>
#include <deal.II/distributed/tria.h>
DEAL_II_NAMESPACE_OPEN
#ifdef DEAL_II_WITH_MPI
namespace parallel
{
namespace shared
{
template <int dim, int spacedim>
Triangulation<dim,spacedim>::Triangulation (MPI_Comm mpi_communicator,
const typename dealii::Triangulation<dim,spacedim>::MeshSmoothing smooth_grid,
const bool allow_artificial_cells,
const Settings settings):
dealii::parallel::Triangulation<dim,spacedim>(mpi_communicator,smooth_grid,false),
settings (settings),
allow_artificial_cells(allow_artificial_cells)
{
const auto partition_settings
= (partition_zoltan | partition_metis |
partition_zorder | partition_custom_signal) & settings;
Assert(partition_settings == partition_auto ||
partition_settings == partition_metis ||
partition_settings == partition_zoltan ||
partition_settings == partition_zorder ||
partition_settings == partition_custom_signal,
ExcMessage ("Settings must contain exactly one type of the active cell partitioning scheme."))
if (settings & construct_multigrid_hierarchy)
Assert(allow_artificial_cells,
ExcMessage ("construct_multigrid_hierarchy requires allow_artificial_cells to be set to true."))
}
template <int dim, int spacedim>
void Triangulation<dim,spacedim>::partition()
{
#ifdef DEBUG
// Check that all meshes are the same (or at least have the same
// total number of active cells):
const unsigned int max_active_cells
= Utilities::MPI::max(this->n_active_cells(), this->get_communicator());
Assert(max_active_cells == this->n_active_cells(),
ExcMessage("A parallel::shared::Triangulation needs to be refined in the same"
"way on all processors, but the participating processors don't "
"agree on the number of active cells."))
#endif
auto partition_settings
= (partition_zoltan | partition_metis |
partition_zorder | partition_custom_signal) & settings;
if (partition_settings == partition_auto)
#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN
partition_settings = partition_zoltan;
#elif defined DEAL_II_WITH_METIS
partition_settings = partition_metis;
#else
partition_settings = partition_zorder;
#endif
if (partition_settings == partition_zoltan)
{
#ifndef DEAL_II_TRILINOS_WITH_ZOLTAN
AssertThrow (false,
ExcMessage("Choosing 'partition_zoltan' requires the library "
"to be compiled with support for Zoltan! "
"Instead, you might use 'partition_auto' to select "
"a partitioning algorithm that is supported "
"by your current configuration."));
#else
GridTools::partition_triangulation (this->n_subdomains, *this,
SparsityTools::Partitioner::zoltan);
#endif
}
else if (partition_settings == partition_metis)
{
#ifndef DEAL_II_WITH_METIS
AssertThrow (false,
ExcMessage("Choosing 'partition_metis' requires the library "
"to be compiled with support for METIS! "
"Instead, you might use 'partition_auto' to select "
"a partitioning algorithm that is supported "
"by your current configuration."));
#else
GridTools::partition_triangulation (this->n_subdomains, *this,
SparsityTools::Partitioner::metis);
#endif
}
else if (partition_settings == partition_zorder)
{
GridTools::partition_triangulation_zorder (this->n_subdomains, *this);
}
else if (partition_settings == partition_custom_signal)
{
// User partitions mesh manually
}
else
{
AssertThrow(false, ExcInternalError())
}
// do not partition multigrid levels if user is
// defining a custom partition
if ((settings & construct_multigrid_hierarchy) && !(settings & partition_custom_signal))
dealii::GridTools::partition_multigrid_levels(*this);
true_subdomain_ids_of_cells.resize(this->n_active_cells());
// loop over all cells and mark artificial:
typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator
cell = this->begin_active(),
endc = this->end();
if (allow_artificial_cells)
{
// get active halo layer of (ghost) cells
// parallel::shared::Triangulation<dim>::
std::function<bool (const typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator &)> predicate
= IteratorFilters::SubdomainEqualTo(this->my_subdomain);
const std::vector<typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator>
active_halo_layer_vector = dealii::GridTools::compute_active_cell_halo_layer (*this, predicate);
std::set<typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator>
active_halo_layer(active_halo_layer_vector.begin(), active_halo_layer_vector.end());
for (unsigned int index=0; cell != endc; cell++, index++)
{
// store original/true subdomain ids:
true_subdomain_ids_of_cells[index] = cell->subdomain_id();
if (cell->is_locally_owned() == false &&
active_halo_layer.find(cell) == active_halo_layer.end())
cell->set_subdomain_id(numbers::artificial_subdomain_id);
}
// loop over all cells in multigrid hierarchy and mark artificial:
if (settings & construct_multigrid_hierarchy)
{
true_level_subdomain_ids_of_cells.resize(this->n_levels());
std::function<bool (const typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator &)> predicate
= IteratorFilters::LocallyOwnedLevelCell();
for (unsigned int lvl=0; lvl<this->n_levels(); ++lvl)
{
true_level_subdomain_ids_of_cells[lvl].resize(this->n_cells(lvl));
const std::vector<typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator>
level_halo_layer_vector = dealii::GridTools::compute_cell_halo_layer_on_level (*this, predicate, lvl);
std::set<typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator>
level_halo_layer(level_halo_layer_vector.begin(), level_halo_layer_vector.end());
typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator
cell = this->begin(lvl),
endc = this->end(lvl);
for (unsigned int index=0; cell != endc; cell++, index++)
{
// Store true level subdomain IDs before setting artificial
true_level_subdomain_ids_of_cells[lvl][index] = cell->level_subdomain_id();
// for active cells, we must have knowledge of level subdomain ids of
// all neighbors to our subdomain, not just neighbors on the same level.
// if the cells subdomain id was not set to artitficial above, we will
// also keep its level subdomain id since it is either owned by this processor
// or in the ghost layer of the active mesh.
if (!cell->has_children() && cell->subdomain_id() != numbers::artificial_subdomain_id)
continue;
// we must have knowledge of our parent in the hierarchy
if (cell->has_children())
{
bool keep_cell = false;
for (unsigned int c=0; c<GeometryInfo<dim>::max_children_per_cell; ++c)
if (cell->child(c)->level_subdomain_id() == this->my_subdomain)
{
keep_cell = true;
break;
}
if (keep_cell)
continue;
}
// we must have knowledge of our neighbors on the same level
if (!cell->is_locally_owned_on_level() &&
level_halo_layer.find(cell) != level_halo_layer.end())
continue;
// mark all other cells to artificial
cell->set_level_subdomain_id(numbers::artificial_subdomain_id);
}
}
}
}
else
{
// just store true subdomain ids
for (unsigned int index=0; cell != endc; cell++, index++)
true_subdomain_ids_of_cells[index] = cell->subdomain_id();
}
#ifdef DEBUG
{
// Assert that each cell is owned by a processor
unsigned int n_my_cells = 0;
typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator
cell = this->begin_active(),
endc = this->end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
n_my_cells += 1;
const unsigned int total_cells
= Utilities::MPI::sum(n_my_cells, this->get_communicator());
Assert(total_cells == this->n_active_cells(),
ExcMessage("Not all cells are assigned to a processor."))
}
// If running with multigrid, assert that each level
// cell is owned by a processor
if (settings & construct_multigrid_hierarchy)
{
unsigned int n_my_cells = 0;
typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator
cell = this->begin(),
endc = this->end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned_on_level())
n_my_cells += 1;
const unsigned int total_cells
= Utilities::MPI::sum(n_my_cells, this->get_communicator());
Assert(total_cells == this->n_cells(),
ExcMessage("Not all cells are assigned to a processor."))
}
#endif
}
template <int dim, int spacedim>
bool
Triangulation<dim,spacedim>::with_artificial_cells() const
{
return allow_artificial_cells;
}
template <int dim, int spacedim>
const std::vector<types::subdomain_id> &
Triangulation<dim,spacedim>::get_true_subdomain_ids_of_cells() const
{
return true_subdomain_ids_of_cells;
}
template <int dim, int spacedim>
const std::vector<types::subdomain_id> &
Triangulation<dim,spacedim>::get_true_level_subdomain_ids_of_cells(const unsigned int level) const
{
return true_level_subdomain_ids_of_cells[level];
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::execute_coarsening_and_refinement ()
{
dealii::Triangulation<dim,spacedim>::execute_coarsening_and_refinement ();
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::create_triangulation (const std::vector< Point< spacedim > > &vertices,
const std::vector< CellData< dim > > &cells,
const SubCellData &subcelldata)
{
try
{
dealii::Triangulation<dim,spacedim>::
create_triangulation (vertices, cells, subcelldata);
}
catch (const typename dealii::Triangulation<dim,spacedim>::DistortedCellList &)
{
// the underlying triangulation should not be checking for distorted
// cells
Assert (false, ExcInternalError());
}
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim, spacedim>::
copy_triangulation (const dealii::Triangulation<dim, spacedim> &other_tria)
{
Assert ((dynamic_cast<const dealii::parallel::distributed::Triangulation<dim,spacedim> *>(&other_tria) == nullptr),
ExcMessage("Cannot use this function on parallel::distributed::Triangulation."));
dealii::parallel::Triangulation<dim,spacedim>::copy_triangulation (other_tria);
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::
update_number_cache ()
{
parallel::Triangulation<dim,spacedim>::update_number_cache();
if (settings & construct_multigrid_hierarchy)
parallel::Triangulation<dim,spacedim>::fill_level_ghost_owners();
}
}
}
#else
namespace parallel
{
namespace shared
{
template <int dim, int spacedim>
bool
Triangulation<dim,spacedim>::with_artificial_cells() const
{
Assert (false, ExcNotImplemented());
return true;
}
template <int dim, int spacedim>
const std::vector<unsigned int> &
Triangulation<dim,spacedim>::get_true_subdomain_ids_of_cells() const
{
Assert (false, ExcNotImplemented());
return true_subdomain_ids_of_cells;
}
template <int dim, int spacedim>
const std::vector<unsigned int> &
Triangulation<dim,spacedim>::get_true_level_subdomain_ids_of_cells(const unsigned int) const
{
Assert (false, ExcNotImplemented());
return true_level_subdomain_ids_of_cells;
}
}
}
#endif
/*-------------- Explicit Instantiations -------------------------------*/
#include "shared_tria.inst"
DEAL_II_NAMESPACE_CLOSE
<commit_msg>Remove an old svn tag.<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 2015 - 2017 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/base/utilities.h>
#include <deal.II/base/mpi.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/filtered_iterator.h>
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/distributed/shared_tria.h>
#include <deal.II/distributed/tria.h>
DEAL_II_NAMESPACE_OPEN
#ifdef DEAL_II_WITH_MPI
namespace parallel
{
namespace shared
{
template <int dim, int spacedim>
Triangulation<dim,spacedim>::Triangulation (MPI_Comm mpi_communicator,
const typename dealii::Triangulation<dim,spacedim>::MeshSmoothing smooth_grid,
const bool allow_artificial_cells,
const Settings settings):
dealii::parallel::Triangulation<dim,spacedim>(mpi_communicator,smooth_grid,false),
settings (settings),
allow_artificial_cells(allow_artificial_cells)
{
const auto partition_settings
= (partition_zoltan | partition_metis |
partition_zorder | partition_custom_signal) & settings;
Assert(partition_settings == partition_auto ||
partition_settings == partition_metis ||
partition_settings == partition_zoltan ||
partition_settings == partition_zorder ||
partition_settings == partition_custom_signal,
ExcMessage ("Settings must contain exactly one type of the active cell partitioning scheme."))
if (settings & construct_multigrid_hierarchy)
Assert(allow_artificial_cells,
ExcMessage ("construct_multigrid_hierarchy requires allow_artificial_cells to be set to true."))
}
template <int dim, int spacedim>
void Triangulation<dim,spacedim>::partition()
{
#ifdef DEBUG
// Check that all meshes are the same (or at least have the same
// total number of active cells):
const unsigned int max_active_cells
= Utilities::MPI::max(this->n_active_cells(), this->get_communicator());
Assert(max_active_cells == this->n_active_cells(),
ExcMessage("A parallel::shared::Triangulation needs to be refined in the same"
"way on all processors, but the participating processors don't "
"agree on the number of active cells."))
#endif
auto partition_settings
= (partition_zoltan | partition_metis |
partition_zorder | partition_custom_signal) & settings;
if (partition_settings == partition_auto)
#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN
partition_settings = partition_zoltan;
#elif defined DEAL_II_WITH_METIS
partition_settings = partition_metis;
#else
partition_settings = partition_zorder;
#endif
if (partition_settings == partition_zoltan)
{
#ifndef DEAL_II_TRILINOS_WITH_ZOLTAN
AssertThrow (false,
ExcMessage("Choosing 'partition_zoltan' requires the library "
"to be compiled with support for Zoltan! "
"Instead, you might use 'partition_auto' to select "
"a partitioning algorithm that is supported "
"by your current configuration."));
#else
GridTools::partition_triangulation (this->n_subdomains, *this,
SparsityTools::Partitioner::zoltan);
#endif
}
else if (partition_settings == partition_metis)
{
#ifndef DEAL_II_WITH_METIS
AssertThrow (false,
ExcMessage("Choosing 'partition_metis' requires the library "
"to be compiled with support for METIS! "
"Instead, you might use 'partition_auto' to select "
"a partitioning algorithm that is supported "
"by your current configuration."));
#else
GridTools::partition_triangulation (this->n_subdomains, *this,
SparsityTools::Partitioner::metis);
#endif
}
else if (partition_settings == partition_zorder)
{
GridTools::partition_triangulation_zorder (this->n_subdomains, *this);
}
else if (partition_settings == partition_custom_signal)
{
// User partitions mesh manually
}
else
{
AssertThrow(false, ExcInternalError())
}
// do not partition multigrid levels if user is
// defining a custom partition
if ((settings & construct_multigrid_hierarchy) && !(settings & partition_custom_signal))
dealii::GridTools::partition_multigrid_levels(*this);
true_subdomain_ids_of_cells.resize(this->n_active_cells());
// loop over all cells and mark artificial:
typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator
cell = this->begin_active(),
endc = this->end();
if (allow_artificial_cells)
{
// get active halo layer of (ghost) cells
// parallel::shared::Triangulation<dim>::
std::function<bool (const typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator &)> predicate
= IteratorFilters::SubdomainEqualTo(this->my_subdomain);
const std::vector<typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator>
active_halo_layer_vector = dealii::GridTools::compute_active_cell_halo_layer (*this, predicate);
std::set<typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator>
active_halo_layer(active_halo_layer_vector.begin(), active_halo_layer_vector.end());
for (unsigned int index=0; cell != endc; cell++, index++)
{
// store original/true subdomain ids:
true_subdomain_ids_of_cells[index] = cell->subdomain_id();
if (cell->is_locally_owned() == false &&
active_halo_layer.find(cell) == active_halo_layer.end())
cell->set_subdomain_id(numbers::artificial_subdomain_id);
}
// loop over all cells in multigrid hierarchy and mark artificial:
if (settings & construct_multigrid_hierarchy)
{
true_level_subdomain_ids_of_cells.resize(this->n_levels());
std::function<bool (const typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator &)> predicate
= IteratorFilters::LocallyOwnedLevelCell();
for (unsigned int lvl=0; lvl<this->n_levels(); ++lvl)
{
true_level_subdomain_ids_of_cells[lvl].resize(this->n_cells(lvl));
const std::vector<typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator>
level_halo_layer_vector = dealii::GridTools::compute_cell_halo_layer_on_level (*this, predicate, lvl);
std::set<typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator>
level_halo_layer(level_halo_layer_vector.begin(), level_halo_layer_vector.end());
typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator
cell = this->begin(lvl),
endc = this->end(lvl);
for (unsigned int index=0; cell != endc; cell++, index++)
{
// Store true level subdomain IDs before setting artificial
true_level_subdomain_ids_of_cells[lvl][index] = cell->level_subdomain_id();
// for active cells, we must have knowledge of level subdomain ids of
// all neighbors to our subdomain, not just neighbors on the same level.
// if the cells subdomain id was not set to artitficial above, we will
// also keep its level subdomain id since it is either owned by this processor
// or in the ghost layer of the active mesh.
if (!cell->has_children() && cell->subdomain_id() != numbers::artificial_subdomain_id)
continue;
// we must have knowledge of our parent in the hierarchy
if (cell->has_children())
{
bool keep_cell = false;
for (unsigned int c=0; c<GeometryInfo<dim>::max_children_per_cell; ++c)
if (cell->child(c)->level_subdomain_id() == this->my_subdomain)
{
keep_cell = true;
break;
}
if (keep_cell)
continue;
}
// we must have knowledge of our neighbors on the same level
if (!cell->is_locally_owned_on_level() &&
level_halo_layer.find(cell) != level_halo_layer.end())
continue;
// mark all other cells to artificial
cell->set_level_subdomain_id(numbers::artificial_subdomain_id);
}
}
}
}
else
{
// just store true subdomain ids
for (unsigned int index=0; cell != endc; cell++, index++)
true_subdomain_ids_of_cells[index] = cell->subdomain_id();
}
#ifdef DEBUG
{
// Assert that each cell is owned by a processor
unsigned int n_my_cells = 0;
typename parallel::shared::Triangulation<dim,spacedim>::active_cell_iterator
cell = this->begin_active(),
endc = this->end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned())
n_my_cells += 1;
const unsigned int total_cells
= Utilities::MPI::sum(n_my_cells, this->get_communicator());
Assert(total_cells == this->n_active_cells(),
ExcMessage("Not all cells are assigned to a processor."))
}
// If running with multigrid, assert that each level
// cell is owned by a processor
if (settings & construct_multigrid_hierarchy)
{
unsigned int n_my_cells = 0;
typename parallel::shared::Triangulation<dim,spacedim>::cell_iterator
cell = this->begin(),
endc = this->end();
for (; cell!=endc; ++cell)
if (cell->is_locally_owned_on_level())
n_my_cells += 1;
const unsigned int total_cells
= Utilities::MPI::sum(n_my_cells, this->get_communicator());
Assert(total_cells == this->n_cells(),
ExcMessage("Not all cells are assigned to a processor."))
}
#endif
}
template <int dim, int spacedim>
bool
Triangulation<dim,spacedim>::with_artificial_cells() const
{
return allow_artificial_cells;
}
template <int dim, int spacedim>
const std::vector<types::subdomain_id> &
Triangulation<dim,spacedim>::get_true_subdomain_ids_of_cells() const
{
return true_subdomain_ids_of_cells;
}
template <int dim, int spacedim>
const std::vector<types::subdomain_id> &
Triangulation<dim,spacedim>::get_true_level_subdomain_ids_of_cells(const unsigned int level) const
{
return true_level_subdomain_ids_of_cells[level];
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::execute_coarsening_and_refinement ()
{
dealii::Triangulation<dim,spacedim>::execute_coarsening_and_refinement ();
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::create_triangulation (const std::vector< Point< spacedim > > &vertices,
const std::vector< CellData< dim > > &cells,
const SubCellData &subcelldata)
{
try
{
dealii::Triangulation<dim,spacedim>::
create_triangulation (vertices, cells, subcelldata);
}
catch (const typename dealii::Triangulation<dim,spacedim>::DistortedCellList &)
{
// the underlying triangulation should not be checking for distorted
// cells
Assert (false, ExcInternalError());
}
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim, spacedim>::
copy_triangulation (const dealii::Triangulation<dim, spacedim> &other_tria)
{
Assert ((dynamic_cast<const dealii::parallel::distributed::Triangulation<dim,spacedim> *>(&other_tria) == nullptr),
ExcMessage("Cannot use this function on parallel::distributed::Triangulation."));
dealii::parallel::Triangulation<dim,spacedim>::copy_triangulation (other_tria);
partition();
this->update_number_cache ();
}
template <int dim, int spacedim>
void
Triangulation<dim,spacedim>::
update_number_cache ()
{
parallel::Triangulation<dim,spacedim>::update_number_cache();
if (settings & construct_multigrid_hierarchy)
parallel::Triangulation<dim,spacedim>::fill_level_ghost_owners();
}
}
}
#else
namespace parallel
{
namespace shared
{
template <int dim, int spacedim>
bool
Triangulation<dim,spacedim>::with_artificial_cells() const
{
Assert (false, ExcNotImplemented());
return true;
}
template <int dim, int spacedim>
const std::vector<unsigned int> &
Triangulation<dim,spacedim>::get_true_subdomain_ids_of_cells() const
{
Assert (false, ExcNotImplemented());
return true_subdomain_ids_of_cells;
}
template <int dim, int spacedim>
const std::vector<unsigned int> &
Triangulation<dim,spacedim>::get_true_level_subdomain_ids_of_cells(const unsigned int) const
{
Assert (false, ExcNotImplemented());
return true_level_subdomain_ids_of_cells;
}
}
}
#endif
/*-------------- Explicit Instantiations -------------------------------*/
#include "shared_tria.inst"
DEAL_II_NAMESPACE_CLOSE
<|endoftext|> |
<commit_before>// @(#)root/tree:$Id$
// Author: Rene Brun 14/04/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. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////////
///
/// TCut
///
/// A specialized string object used for TTree selections.
/// A TCut object has a name and a title. It does not add any data
/// members compared to a TNamed. It only add a set of operators to
/// facilitate logical string concatenation. For example, assume
///
/// cut1 = "x<1" and cut2 = "y>2"
///
/// then
///
/// cut1 && cut2 will be the string "(x<1)&&(y>2)"
///
/// Operators =, +=, +, *, !, &&, || overloaded.
///
/// Examples of use:
///
/// Root > TCut c1 = "x<1"
/// Root > TCut c2 = "y<0"
/// Root > TCut c3 = c1&&c2
/// Root > ntuple.Draw("x", c1)
/// Root > ntuple.Draw("x", c1||"x>0")
/// Root > ntuple.Draw("x", c1&&c2)
/// Root > ntuple.Draw("x", "(x+y)"*(c1&&c2))
#include "TCut.h"
ClassImp(TCut)
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut() : TNamed()
{
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut(const char *title) : TNamed("CUT",title)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut(const char *name, const char *title) : TNamed(name,title)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Copy Constructor.
TCut::TCut(const TCut &cut) : TNamed(cut)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Typical destructor.
TCut::~TCut()
{
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator==(const char *rhs) const
{
return fTitle == rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator==(const TCut &rhs) const
{
return fTitle == rhs.fTitle;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator!=(const char *rhs) const
{
return fTitle != rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator!=(const TCut &rhs) const
{
return fTitle != rhs.fTitle;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment.
TCut& TCut::operator=(const char *rhs)
{
fTitle = rhs;
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment.
TCut& TCut::operator=(const TCut& rhs)
{
if (this != &rhs) TNamed::operator=(rhs);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut& TCut::operator+=(const char *rhs)
{
if (!rhs || !rhs[0]) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")&&(" + TString(rhs) + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut& TCut::operator+=(const TCut& rhs)
{
if (rhs.fTitle.Length() == 0) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")&&(" + rhs.fTitle + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut& TCut::operator*=(const char *rhs)
{
if (!rhs || !rhs[0]) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")*(" + TString(rhs) + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut& TCut::operator*=(const TCut& rhs)
{
if (rhs.fTitle.Length() == 0) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")*(" + rhs.fTitle + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const TCut& lhs, const char *rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const char *lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const TCut& lhs, const char *rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const char *lhs, const TCut& rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const TCut& lhs, const char *rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const char *lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const TCut& lhs, const char *rhs)
{
if (lhs.fTitle.Length() == 0 && (!rhs || !rhs[0])) return TCut();
if (lhs.fTitle.Length() == 0) return TCut(rhs);
if (!rhs || !rhs[0]) return TCut(lhs);
TString s = "(" + lhs.fTitle + ")||(" + TString(rhs) + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const char *lhs, const TCut& rhs)
{
if ((!lhs || !lhs[0]) && rhs.fTitle.Length() == 0) return TCut();
if (!lhs || !lhs[0]) return TCut(rhs);
if (rhs.fTitle.Length() == 0) return TCut(lhs);
TString s = "(" + TString(lhs) + ")||(" + rhs.fTitle + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const TCut& lhs, const TCut& rhs)
{
if (lhs.fTitle.Length() == 0 && rhs.fTitle.Length() == 0) return TCut();
if (lhs.fTitle.Length() == 0) return TCut(rhs);
if (rhs.fTitle.Length() == 0) return TCut(lhs);
TString s = "(" + lhs.fTitle + ")||(" + rhs.fTitle + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical negation.
TCut operator!(const TCut &rhs)
{
if (rhs.fTitle.Length() == 0) return TCut();
TString s = "!(" + rhs.fTitle + ")";
return TCut(s.Data());
}
<commit_msg>Doxygen (\class was missing)<commit_after>// @(#)root/tree:$Id$
// Author: Rene Brun 14/04/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. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/// \class TCut
///
/// A specialized string object used for TTree selections.
/// A TCut object has a name and a title. It does not add any data
/// members compared to a TNamed. It only add a set of operators to
/// facilitate logical string concatenation. For example, assume
///
/// cut1 = "x<1" and cut2 = "y>2"
///
/// then
///
/// cut1 && cut2 will be the string "(x<1)&&(y>2)"
///
/// Operators =, +=, +, *, !, &&, || overloaded.
///
/// Examples of use:
///
/// Root > TCut c1 = "x<1"
/// Root > TCut c2 = "y<0"
/// Root > TCut c3 = c1&&c2
/// Root > ntuple.Draw("x", c1)
/// Root > ntuple.Draw("x", c1||"x>0")
/// Root > ntuple.Draw("x", c1&&c2)
/// Root > ntuple.Draw("x", "(x+y)"*(c1&&c2))
#include "TCut.h"
ClassImp(TCut)
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut() : TNamed()
{
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut(const char *title) : TNamed("CUT",title)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
TCut::TCut(const char *name, const char *title) : TNamed(name,title)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Copy Constructor.
TCut::TCut(const TCut &cut) : TNamed(cut)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Typical destructor.
TCut::~TCut()
{
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator==(const char *rhs) const
{
return fTitle == rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator==(const TCut &rhs) const
{
return fTitle == rhs.fTitle;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator!=(const char *rhs) const
{
return fTitle != rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison.
Bool_t TCut::operator!=(const TCut &rhs) const
{
return fTitle != rhs.fTitle;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment.
TCut& TCut::operator=(const char *rhs)
{
fTitle = rhs;
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment.
TCut& TCut::operator=(const TCut& rhs)
{
if (this != &rhs) TNamed::operator=(rhs);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut& TCut::operator+=(const char *rhs)
{
if (!rhs || !rhs[0]) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")&&(" + TString(rhs) + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut& TCut::operator+=(const TCut& rhs)
{
if (rhs.fTitle.Length() == 0) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")&&(" + rhs.fTitle + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut& TCut::operator*=(const char *rhs)
{
if (!rhs || !rhs[0]) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")*(" + TString(rhs) + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut& TCut::operator*=(const TCut& rhs)
{
if (rhs.fTitle.Length() == 0) return *this;
if (fTitle.Length() == 0)
fTitle = rhs;
else
fTitle = "(" + fTitle + ")*(" + rhs.fTitle + ")";
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const TCut& lhs, const char *rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const char *lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Addition.
TCut operator+(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const TCut& lhs, const char *rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const char *lhs, const TCut& rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Multiplication.
TCut operator*(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) *= rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const TCut& lhs, const char *rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const char *lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical and.
TCut operator&&(const TCut& lhs, const TCut& rhs)
{
return TCut(lhs) += rhs;
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const TCut& lhs, const char *rhs)
{
if (lhs.fTitle.Length() == 0 && (!rhs || !rhs[0])) return TCut();
if (lhs.fTitle.Length() == 0) return TCut(rhs);
if (!rhs || !rhs[0]) return TCut(lhs);
TString s = "(" + lhs.fTitle + ")||(" + TString(rhs) + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const char *lhs, const TCut& rhs)
{
if ((!lhs || !lhs[0]) && rhs.fTitle.Length() == 0) return TCut();
if (!lhs || !lhs[0]) return TCut(rhs);
if (rhs.fTitle.Length() == 0) return TCut(lhs);
TString s = "(" + TString(lhs) + ")||(" + rhs.fTitle + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical or.
TCut operator||(const TCut& lhs, const TCut& rhs)
{
if (lhs.fTitle.Length() == 0 && rhs.fTitle.Length() == 0) return TCut();
if (lhs.fTitle.Length() == 0) return TCut(rhs);
if (rhs.fTitle.Length() == 0) return TCut(lhs);
TString s = "(" + lhs.fTitle + ")||(" + rhs.fTitle + ")";
return TCut(s.Data());
}
////////////////////////////////////////////////////////////////////////////////
/// Logical negation.
TCut operator!(const TCut &rhs)
{
if (rhs.fTitle.Length() == 0) return TCut();
TString s = "!(" + rhs.fTitle + ")";
return TCut(s.Data());
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\brief A Lua class proxy for IO's dataset class.
*/
#include <vector>
#include "Controller/Controller.h"
#include "3rdParty/LUA/lua.hpp"
#include "IO/IOManager.h"
#include "IO/FileBackedDataset.h"
#include "IO/uvfDataset.h"
#include "../LuaScripting.h"
#include "../LuaClassRegistration.h"
#include "LuaTuvokTypes.h"
#include "LuaDatasetProxy.h"
using namespace std;
namespace tuvok
{
namespace Registrar {
void addIOInterface(LuaClassRegistration<Dataset>& reg, Dataset*,
LuaScripting*) {
reg.function(&Dataset::GetLODLevelCount, "LODs", "help?", false);
}
void dataset(std::shared_ptr<LuaScripting>& ss) {
LuaDatasetProxy* proxy = new LuaDatasetProxy;
ss->registerClass<Dataset>(
proxy, &LuaDatasetProxy::CreateDS, "tuvok.dataset", "creates a new dataset",
LuaClassRegCallback<Dataset>::Type(addIOInterface)
);
delete proxy;
}
}
LuaDatasetProxy::LuaDatasetProxy()
: mReg(NULL)
, mDS(NULL)
, mDatasetType(Unknown) { }
LuaDatasetProxy::~LuaDatasetProxy()
{
delete mReg; mReg = NULL;
mDS = NULL;
}
Dataset* LuaDatasetProxy::CreateDS(const std::string& uvf, unsigned bricksize) {
return Controller::Const().IOMan().CreateDataset(uvf,
uint64_t(bricksize), false
);
}
void LuaDatasetProxy::bind(Dataset* ds, shared_ptr<LuaScripting> ss)
{
if (mReg == NULL)
throw LuaError("Unable to bind dataset, no class registration available.");
mReg->clearProxyFunctions();
mDS = ds;
if (ds != NULL)
{
// Register dataset functions using ds.
string id;
id = mReg->functionProxy(ds, &Dataset::GetDomainSize,
"getDomainSize", "", false);
id = mReg->functionProxy(ds, &Dataset::GetRange,
"getRange", "", false);
id = mReg->functionProxy(ds, &Dataset::GetLODLevelCount,
"getLODLevelCount", "", false);
id = mReg->functionProxy(ds, &Dataset::GetNumberOfTimesteps,
"getNumberOfTimesteps", "", false);
id = mReg->functionProxy(ds, &Dataset::GetMeshes,
"getMeshes", "", false);
id = mReg->functionProxy(ds, &Dataset::GetBitWidth,
"getBitWidth", "", false);
id = mReg->functionProxy(ds, &Dataset::Get1DHistogram,
"get1DHistogram", "", false);
id = mReg->functionProxy(ds, &Dataset::Get2DHistogram,
"get2DHistogram", "", false);
id = mReg->functionProxy(ds, &Dataset::SaveRescaleFactors,
"saveRescaleFactors", "", false);
id = mReg->functionProxy(ds, &Dataset::GetRescaleFactors,
"getRescaleFactors", "", false);
// We do NOT want the return values from GetMeshes stuck in the provenance
// system (Okay, so the provenance system doesn't store return values, just
// function parameters. But it's best to be safe).
ss->setProvenanceExempt(id);
// Attempt to cast the dataset to a file backed dataset.
FileBackedDataset* fileDataset = dynamic_cast<FileBackedDataset*>(ds);
if (fileDataset != NULL)
{
MESSAGE("Binding extra FileBackedDS functions.");
id = mReg->functionProxy(fileDataset, &FileBackedDataset::Filename,
"fullpath", "Full path to the dataset.", false);
id = mReg->functionProxy(ds, &FileBackedDataset::Name,
"name", "Dataset descriptive name.", false);
}
try {
UVFDataset& uvfDataset = dynamic_cast<UVFDataset&>(*ds);
MESSAGE("Binding extra UVF functions.");
mDatasetType = UVF;
mReg->functionProxy(&uvfDataset, &UVFDataset::RemoveMesh, "removeMesh",
"", true);
mReg->functionProxy(&uvfDataset, &UVFDataset::AppendMesh,
"appendMesh", "", false);
id = mReg->functionProxy(&uvfDataset,
&UVFDataset::GeometryTransformToFile, "geomTransformToFile", "",
false
);
ss->setProvenanceExempt(id);
} catch(const std::bad_cast&) {
WARNING("Not a uvf; not binding advanced functions.");
}
/// @todo Expose 1D/2D histogram? Currently, it is being transfered
/// via shared_ptr. If lua wants to interpret this, the histogram
/// will need to be placed in terms that lua can understand.
/// Two approaches:
/// 1) Add Grid1D to the LuaStrictStack.
/// 2) Create a Histogram1D and Histogram2D proxy.
///
/// The second solution would be more efficient, since there wouldn't
/// be any time spent converting datatypes to and from Lua (and with
/// histograms, that time wouldn't be negligible).
}
}
void LuaDatasetProxy::defineLuaInterface(
LuaClassRegistration<LuaDatasetProxy>& reg,
LuaDatasetProxy* me,
LuaScripting*)
{
me->mReg = new LuaClassRegistration<LuaDatasetProxy>(reg);
string id;
// Register our functions
id = reg.function(&LuaDatasetProxy::getDatasetType, "getDSType", "", false);
id = reg.function(&LuaDatasetProxy::proxyGetMetadata, "getMetadata", "",
false);
}
std::vector<std::pair<std::string, std::string>>
LuaDatasetProxy::proxyGetMetadata()
{
return mDS->GetMetadata();
}
} /* namespace tuvok */
<commit_msg>Bind minmax computation strategies into Lua.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\brief A Lua class proxy for IO's dataset class.
*/
#include <vector>
#include "3rdParty/LUA/lua.hpp"
#include "Controller/Controller.h"
#include "IO/DynamicBrickingDS.h"
#include "IO/FileBackedDataset.h"
#include "IO/IOManager.h"
#include "IO/uvfDataset.h"
#include "../LuaClassRegistration.h"
#include "../LuaScripting.h"
#include "LuaDatasetProxy.h"
#include "LuaTuvokTypes.h"
using namespace std;
namespace tuvok
{
namespace Registrar {
void addIOInterface(LuaClassRegistration<Dataset>& reg, Dataset*,
LuaScripting*) {
reg.function(&Dataset::GetLODLevelCount, "LODs", "help?", false);
}
void dataset(std::shared_ptr<LuaScripting>& ss) {
LuaDatasetProxy* proxy = new LuaDatasetProxy;
ss->registerClass<Dataset>(
proxy, &LuaDatasetProxy::CreateDS, "tuvok.dataset", "creates a new dataset",
LuaClassRegCallback<Dataset>::Type(addIOInterface)
);
delete proxy;
}
}
LuaDatasetProxy::LuaDatasetProxy()
: mReg(NULL)
, mDS(NULL)
, mDatasetType(Unknown) { }
LuaDatasetProxy::~LuaDatasetProxy()
{
delete mReg; mReg = NULL;
mDS = NULL;
}
Dataset* LuaDatasetProxy::CreateDS(const std::string& uvf, unsigned bricksize) {
return Controller::Const().IOMan().CreateDataset(uvf,
uint64_t(bricksize), false
);
}
void LuaDatasetProxy::bind(Dataset* ds, shared_ptr<LuaScripting> ss)
{
if (mReg == NULL)
throw LuaError("Unable to bind dataset, no class registration available.");
mReg->clearProxyFunctions();
mDS = ds;
if (ds != NULL)
{
// Register dataset functions using ds.
string id;
id = mReg->functionProxy(ds, &Dataset::GetDomainSize,
"getDomainSize", "", false);
id = mReg->functionProxy(ds, &Dataset::GetRange,
"getRange", "", false);
id = mReg->functionProxy(ds, &Dataset::GetLODLevelCount,
"getLODLevelCount", "", false);
id = mReg->functionProxy(ds, &Dataset::GetNumberOfTimesteps,
"getNumberOfTimesteps", "", false);
id = mReg->functionProxy(ds, &Dataset::GetMeshes,
"getMeshes", "", false);
id = mReg->functionProxy(ds, &Dataset::GetBitWidth,
"getBitWidth", "", false);
id = mReg->functionProxy(ds, &Dataset::Get1DHistogram,
"get1DHistogram", "", false);
id = mReg->functionProxy(ds, &Dataset::Get2DHistogram,
"get2DHistogram", "", false);
id = mReg->functionProxy(ds, &Dataset::SaveRescaleFactors,
"saveRescaleFactors", "", false);
id = mReg->functionProxy(ds, &Dataset::GetRescaleFactors,
"getRescaleFactors", "", false);
// We do NOT want the return values from GetMeshes stuck in the provenance
// system (Okay, so the provenance system doesn't store return values, just
// function parameters. But it's best to be safe).
ss->setProvenanceExempt(id);
// Attempt to cast the dataset to a file backed dataset.
FileBackedDataset* fileDataset = dynamic_cast<FileBackedDataset*>(ds);
if (fileDataset != NULL)
{
MESSAGE("Binding extra FileBackedDS functions.");
id = mReg->functionProxy(fileDataset, &FileBackedDataset::Filename,
"fullpath", "Full path to the dataset.", false);
id = mReg->functionProxy(ds, &FileBackedDataset::Name,
"name", "Dataset descriptive name.", false);
}
try {
UVFDataset& uvfDataset = dynamic_cast<UVFDataset&>(*ds);
MESSAGE("Binding extra UVF functions.");
mDatasetType = UVF;
mReg->functionProxy(&uvfDataset, &UVFDataset::RemoveMesh, "removeMesh",
"", true);
mReg->functionProxy(&uvfDataset, &UVFDataset::AppendMesh,
"appendMesh", "", false);
id = mReg->functionProxy(&uvfDataset,
&UVFDataset::GeometryTransformToFile, "geomTransformToFile", "",
false
);
ss->setProvenanceExempt(id);
} catch(const std::bad_cast&) {
WARNING("Not a uvf; not binding advanced functions.");
}
/// @todo Expose 1D/2D histogram? Currently, it is being transfered
/// via shared_ptr. If lua wants to interpret this, the histogram
/// will need to be placed in terms that lua can understand.
/// Two approaches:
/// 1) Add Grid1D to the LuaStrictStack.
/// 2) Create a Histogram1D and Histogram2D proxy.
///
/// The second solution would be more efficient, since there wouldn't
/// be any time spent converting datatypes to and from Lua (and with
/// histograms, that time wouldn't be negligible).
}
}
void LuaDatasetProxy::defineLuaInterface(
LuaClassRegistration<LuaDatasetProxy>& reg,
LuaDatasetProxy* me,
LuaScripting* ss)
{
me->mReg = new LuaClassRegistration<LuaDatasetProxy>(reg);
string id;
// Register our functions
id = reg.function(&LuaDatasetProxy::getDatasetType, "getDSType", "", false);
id = reg.function(&LuaDatasetProxy::proxyGetMetadata, "getMetadata", "",
false);
lua_State* L = ss->getLuaState();
lua_pushinteger(L, DynamicBrickingDS::MM_SOURCE);
lua_setglobal(L, "MM_SOURCE");
lua_pushinteger(L, DynamicBrickingDS::MM_PRECOMPUTE);
lua_setglobal(L, "MM_PRECOMPUTE");
lua_pushinteger(L, DynamicBrickingDS::MM_DYNAMIC);
lua_setglobal(L, "MM_DYNAMIC");
}
std::vector<std::pair<std::string, std::string>>
LuaDatasetProxy::proxyGetMetadata()
{
return mDS->GetMetadata();
}
} /* namespace tuvok */
<|endoftext|> |
<commit_before>#include "clustering/reactor/reactor.hpp"
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "clustering/immediate_consistency/query/master.hpp"
#include "clustering/immediate_consistency/branch/multistore.hpp"
#include "concurrency/cross_thread_signal.hpp"
#include "concurrency/cross_thread_watchable.hpp"
template<class key_t, class value_t>
std::map<key_t, value_t> collapse_optionals_in_map(const std::map<key_t, boost::optional<value_t> > &map) {
std::map<key_t, value_t> res;
for (typename std::map<key_t, boost::optional<value_t> >::const_iterator it = map.begin(); it != map.end(); it++) {
if (it->second) {
res.insert(std::make_pair(it->first, it->second.get()));
}
}
return res;
}
template<class protocol_t>
reactor_t<protocol_t>::reactor_t(
io_backender_t *_io_backender,
mailbox_manager_t *mm,
typename master_t<protocol_t>::ack_checker_t *ack_checker_,
clone_ptr_t<watchable_t<std::map<peer_id_t, boost::optional<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t<protocol_t> > > > > > > rd,
branch_history_manager_t<protocol_t> *bhm,
clone_ptr_t<watchable_t<blueprint_t<protocol_t> > > b,
multistore_ptr_t<protocol_t> *_underlying_svs,
perfmon_collection_t *_parent_perfmon_collection,
typename protocol_t::context_t *_ctx) THROWS_NOTHING :
io_backender(_io_backender),
mailbox_manager(mm),
ack_checker(ack_checker_),
directory_echo_writer(mailbox_manager, cow_ptr_t<reactor_business_card_t<protocol_t> >()),
directory_echo_mirror(mailbox_manager, rd->subview(&collapse_optionals_in_map<peer_id_t, directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t<protocol_t> > > >)),
branch_history_manager(bhm),
blueprint_watchable(b),
underlying_svs(_underlying_svs),
blueprint_subscription(boost::bind(&reactor_t<protocol_t>::on_blueprint_changed, this)),
parent_perfmon_collection(_parent_perfmon_collection),
regions_perfmon_collection(),
regions_perfmon_membership(parent_perfmon_collection, ®ions_perfmon_collection, "regions"),
ctx(_ctx)
{
{
typename watchable_t<blueprint_t<protocol_t> >::freeze_t freeze(blueprint_watchable);
blueprint_watchable->get().guarantee_valid();
try_spawn_roles();
blueprint_subscription.reset(blueprint_watchable, &freeze);
}
}
template <class protocol_t>
reactor_t<protocol_t>::directory_entry_t::directory_entry_t(reactor_t<protocol_t> *_parent, typename protocol_t::region_t _region)
: parent(_parent), region(_region), reactor_activity_id(nil_uuid())
{ }
template <class protocol_t>
directory_echo_version_t reactor_t<protocol_t>::directory_entry_t::set(typename reactor_business_card_t<protocol_t>::activity_t activity) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
if (!reactor_activity_id.is_nil()) {
cow_ptr_change.get()->activities.erase(reactor_activity_id);
}
reactor_activity_id = generate_uuid();
cow_ptr_change.get()->activities.insert(std::make_pair(reactor_activity_id, typename reactor_business_card_t<protocol_t>::activity_entry_t(region, activity)));
}
return our_value_change.commit();
}
template <class protocol_t>
directory_echo_version_t reactor_t<protocol_t>::directory_entry_t::update_without_changing_id(typename reactor_business_card_t<protocol_t>::activity_t activity) {
guarantee(!reactor_activity_id.is_nil(), "This method should only be called when an activity has already been set\n");
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
cow_ptr_change.get()->activities[reactor_activity_id].activity = activity;
}
return our_value_change.commit();
}
template <class protocol_t>
reactor_t<protocol_t>::directory_entry_t::~directory_entry_t() {
if (!reactor_activity_id.is_nil()) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
cow_ptr_change.get()->activities.erase(reactor_activity_id);
}
our_value_change.commit();
}
}
template<class protocol_t>
void reactor_t<protocol_t>::on_blueprint_changed() THROWS_NOTHING {
blueprint_t<protocol_t> blueprint = blueprint_watchable->get();
blueprint.guarantee_valid();
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::const_iterator role_it = blueprint.peers_roles.find(get_me());
guarantee(role_it != blueprint.peers_roles.end(), "reactor_t assumes that it is mentioned in the blueprint it's given.");
std::map<typename protocol_t::region_t, blueprint_role_t> blueprint_roles = role_it->second;
for (typename std::map<typename protocol_t::region_t, current_role_t *>::iterator it = current_roles.begin();
it != current_roles.end(); ++it) {
typename std::map<typename protocol_t::region_t, blueprint_role_t>::iterator it2 =
blueprint_roles.find(it->first);
if (it2 == blueprint_roles.end()) {
/* The shard boundaries have changed, and the shard that the running
coroutine was for no longer exists; interrupt it */
it->second->abort_roles.pulse_if_not_already_pulsed();
} else {
if (it->second->role != it2->second) {
/* Our role for the shard has changed; interrupt the running
coroutine */
it->second->abort_roles.pulse_if_not_already_pulsed();
} else {
/* Notify the running coroutine of the new blueprint */
it->second->blueprint.set_value(blueprint);
}
}
}
}
template<class protocol_t>
void reactor_t<protocol_t>::try_spawn_roles() THROWS_NOTHING {
blueprint_t<protocol_t> blueprint = blueprint_watchable->get();
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::const_iterator role_it = blueprint.peers_roles.find(get_me());
guarantee(role_it != blueprint.peers_roles.end(), "reactor_t assumes that it is mentioned in the blueprint it's given.");
std::map<typename protocol_t::region_t, blueprint_role_t> blueprint_roles = role_it->second;
for (typename std::map<typename protocol_t::region_t, blueprint_role_t>::iterator it = blueprint_roles.begin();
it != blueprint_roles.end(); ++it) {
bool none_overlap = true;
for (typename std::map<typename protocol_t::region_t, current_role_t *>::iterator it2 = current_roles.begin();
it2 != current_roles.end(); ++it2) {
if (region_overlaps(it->first, it2->first)) {
none_overlap = false;
break;
}
}
if (none_overlap) {
//This state will be cleaned up in run_role
current_role_t *role = new current_role_t(it->second, blueprint);
current_roles.insert(std::make_pair(it->first, role));
coro_t::spawn_sometime(boost::bind(&reactor_t<protocol_t>::run_role, this, it->first,
role, auto_drainer_t::lock_t(&drainer)));
}
}
}
template<class protocol_t>
void reactor_t<protocol_t>::run_cpu_sharded_role(
int cpu_shard_number,
current_role_t *role,
const typename protocol_t::region_t& region,
multistore_ptr_t<protocol_t> *svs_subview,
signal_t *interruptor,
cond_t *abort_roles) THROWS_NOTHING {
store_view_t<protocol_t> *store_view = svs_subview->get_store(cpu_shard_number);
typename protocol_t::region_t cpu_sharded_region = region_intersection(region, protocol_t::cpu_sharding_subspace(cpu_shard_number, svs_subview->num_stores()));
switch (role->role) {
case blueprint_role_primary:
be_primary(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
case blueprint_role_secondary:
be_secondary(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
case blueprint_role_nothing:
be_nothing(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
default:
unreachable();
break;
}
// When one role returns, make sure all others are aborted
if (!abort_roles->is_pulsed()) {
abort_roles->pulse();
}
}
template<class protocol_t>
void reactor_t<protocol_t>::run_role(
typename protocol_t::region_t region,
current_role_t *role,
auto_drainer_t::lock_t keepalive) THROWS_NOTHING {
//A store_view_t derived object that acts as a store for the specified region
multistore_ptr_t<protocol_t> svs_subview(underlying_svs, region);
{
//All of the be_{role} functions respond identically to blueprint changes
//and interruptions... so we just unify those signals
wait_any_t wait_any(&role->abort_roles, keepalive.get_drain_signal());
// guarantee(CLUSTER_CPU_SHARDING_FACTOR == svs_subview.num_stores());
pmap(svs_subview.num_stores(), boost::bind(&reactor_t<protocol_t>::run_cpu_sharded_role, this, _1, role, region, &svs_subview, &wait_any, &role->abort_roles));
}
//As promised, clean up the state from try_spawn_roles
current_roles.erase(region);
delete role;
if (!keepalive.get_drain_signal()->is_pulsed()) {
try_spawn_roles();
}
}
template<class protocol_t>
boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > > reactor_t<protocol_t>::extract_broadcaster_from_reactor_business_card_primary(const boost::optional<boost::optional<typename reactor_business_card_t<protocol_t>::primary_t> > &bcard) {
if (!bcard) {
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >();
}
if (!bcard.get()) {
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >(
boost::optional<broadcaster_business_card_t<protocol_t> >());
}
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >(
boost::optional<broadcaster_business_card_t<protocol_t> >(bcard.get().get().broadcaster));
}
template <class protocol_t>
void reactor_t<protocol_t>::wait_for_directory_acks(directory_echo_version_t version_to_wait_on, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
while (true) {
/* This function waits for acks from all the peers mentioned in the
blueprint. If the blueprint changes while we're waiting for acks, we
restart from the top. This is important because otherwise we might
deadlock. For example, if we were waiting for a machine to come back up
and then it was declared dead, our interruptor might not be pulsed but
the `ack_waiter_t` would never be pulsed so we would get stuck. */
cond_t blueprint_changed;
blueprint_t<protocol_t> bp;
typename watchable_t<blueprint_t<protocol_t> >::subscription_t subscription(
boost::bind(&cond_t::pulse_if_not_already_pulsed, &blueprint_changed));
{
typename watchable_t<blueprint_t<protocol_t> >::freeze_t freeze(blueprint_watchable);
bp = blueprint_watchable->get();
subscription.reset(blueprint_watchable, &freeze);
}
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::iterator it = bp.peers_roles.begin();
for (it = bp.peers_roles.begin(); it != bp.peers_roles.end(); it++) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::ack_waiter_t ack_waiter(&directory_echo_writer, it->first, version_to_wait_on);
wait_any_t waiter(&ack_waiter, &blueprint_changed);
wait_interruptible(&waiter, interruptor);
if (blueprint_changed.is_pulsed()) {
break;
}
}
if (!blueprint_changed.is_pulsed()) {
break;
}
}
}
#include "mock/dummy_protocol.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"
template class reactor_t<mock::dummy_protocol_t>;
template class reactor_t<memcached_protocol_t>;
template class reactor_t<rdb_protocol_t>;
<commit_msg>Don't let a reactor start until its bcard has been insterted.<commit_after>#include "clustering/reactor/reactor.hpp"
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "clustering/immediate_consistency/query/master.hpp"
#include "clustering/immediate_consistency/branch/multistore.hpp"
#include "concurrency/cross_thread_signal.hpp"
#include "concurrency/cross_thread_watchable.hpp"
template<class key_t, class value_t>
std::map<key_t, value_t> collapse_optionals_in_map(const std::map<key_t, boost::optional<value_t> > &map) {
std::map<key_t, value_t> res;
for (typename std::map<key_t, boost::optional<value_t> >::const_iterator it = map.begin(); it != map.end(); it++) {
if (it->second) {
res.insert(std::make_pair(it->first, it->second.get()));
}
}
return res;
}
template<class protocol_t>
reactor_t<protocol_t>::reactor_t(
io_backender_t *_io_backender,
mailbox_manager_t *mm,
typename master_t<protocol_t>::ack_checker_t *ack_checker_,
clone_ptr_t<watchable_t<std::map<peer_id_t, boost::optional<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t<protocol_t> > > > > > > rd,
branch_history_manager_t<protocol_t> *bhm,
clone_ptr_t<watchable_t<blueprint_t<protocol_t> > > b,
multistore_ptr_t<protocol_t> *_underlying_svs,
perfmon_collection_t *_parent_perfmon_collection,
typename protocol_t::context_t *_ctx) THROWS_NOTHING :
io_backender(_io_backender),
mailbox_manager(mm),
ack_checker(ack_checker_),
directory_echo_writer(mailbox_manager, cow_ptr_t<reactor_business_card_t<protocol_t> >()),
directory_echo_mirror(mailbox_manager, rd->subview(&collapse_optionals_in_map<peer_id_t, directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t<protocol_t> > > >)),
branch_history_manager(bhm),
blueprint_watchable(b),
underlying_svs(_underlying_svs),
blueprint_subscription(boost::bind(&reactor_t<protocol_t>::on_blueprint_changed, this)),
parent_perfmon_collection(_parent_perfmon_collection),
regions_perfmon_collection(),
regions_perfmon_membership(parent_perfmon_collection, ®ions_perfmon_collection, "regions"),
ctx(_ctx)
{
{
typename watchable_t<blueprint_t<protocol_t> >::freeze_t freeze(blueprint_watchable);
blueprint_watchable->get().guarantee_valid();
try_spawn_roles();
blueprint_subscription.reset(blueprint_watchable, &freeze);
}
}
template <class protocol_t>
reactor_t<protocol_t>::directory_entry_t::directory_entry_t(reactor_t<protocol_t> *_parent, typename protocol_t::region_t _region)
: parent(_parent), region(_region), reactor_activity_id(nil_uuid())
{ }
template <class protocol_t>
directory_echo_version_t reactor_t<protocol_t>::directory_entry_t::set(typename reactor_business_card_t<protocol_t>::activity_t activity) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
if (!reactor_activity_id.is_nil()) {
cow_ptr_change.get()->activities.erase(reactor_activity_id);
}
reactor_activity_id = generate_uuid();
cow_ptr_change.get()->activities.insert(std::make_pair(reactor_activity_id, typename reactor_business_card_t<protocol_t>::activity_entry_t(region, activity)));
}
return our_value_change.commit();
}
template <class protocol_t>
directory_echo_version_t reactor_t<protocol_t>::directory_entry_t::update_without_changing_id(typename reactor_business_card_t<protocol_t>::activity_t activity) {
guarantee(!reactor_activity_id.is_nil(), "This method should only be called when an activity has already been set\n");
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
cow_ptr_change.get()->activities[reactor_activity_id].activity = activity;
}
return our_value_change.commit();
}
template <class protocol_t>
reactor_t<protocol_t>::directory_entry_t::~directory_entry_t() {
if (!reactor_activity_id.is_nil()) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::our_value_change_t our_value_change(&parent->directory_echo_writer);
{
typename cow_ptr_t<reactor_business_card_t<protocol_t> >::change_t cow_ptr_change(&our_value_change.buffer);
cow_ptr_change.get()->activities.erase(reactor_activity_id);
}
our_value_change.commit();
}
}
template<class protocol_t>
void reactor_t<protocol_t>::on_blueprint_changed() THROWS_NOTHING {
blueprint_t<protocol_t> blueprint = blueprint_watchable->get();
blueprint.guarantee_valid();
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::const_iterator role_it = blueprint.peers_roles.find(get_me());
guarantee(role_it != blueprint.peers_roles.end(), "reactor_t assumes that it is mentioned in the blueprint it's given.");
std::map<typename protocol_t::region_t, blueprint_role_t> blueprint_roles = role_it->second;
for (typename std::map<typename protocol_t::region_t, current_role_t *>::iterator it = current_roles.begin();
it != current_roles.end(); ++it) {
typename std::map<typename protocol_t::region_t, blueprint_role_t>::iterator it2 =
blueprint_roles.find(it->first);
if (it2 == blueprint_roles.end()) {
/* The shard boundaries have changed, and the shard that the running
coroutine was for no longer exists; interrupt it */
it->second->abort_roles.pulse_if_not_already_pulsed();
} else {
if (it->second->role != it2->second) {
/* Our role for the shard has changed; interrupt the running
coroutine */
it->second->abort_roles.pulse_if_not_already_pulsed();
} else {
/* Notify the running coroutine of the new blueprint */
it->second->blueprint.set_value(blueprint);
}
}
}
}
template<class protocol_t>
void reactor_t<protocol_t>::try_spawn_roles() THROWS_NOTHING {
blueprint_t<protocol_t> blueprint = blueprint_watchable->get();
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::const_iterator role_it = blueprint.peers_roles.find(get_me());
guarantee(role_it != blueprint.peers_roles.end(), "reactor_t assumes that it is mentioned in the blueprint it's given.");
std::map<typename protocol_t::region_t, blueprint_role_t> blueprint_roles = role_it->second;
for (typename std::map<typename protocol_t::region_t, blueprint_role_t>::iterator it = blueprint_roles.begin();
it != blueprint_roles.end(); ++it) {
bool none_overlap = true;
for (typename std::map<typename protocol_t::region_t, current_role_t *>::iterator it2 = current_roles.begin();
it2 != current_roles.end(); ++it2) {
if (region_overlaps(it->first, it2->first)) {
none_overlap = false;
break;
}
}
if (none_overlap) {
//This state will be cleaned up in run_role
current_role_t *role = new current_role_t(it->second, blueprint);
current_roles.insert(std::make_pair(it->first, role));
coro_t::spawn_sometime(boost::bind(&reactor_t<protocol_t>::run_role, this, it->first,
role, auto_drainer_t::lock_t(&drainer)));
}
}
}
template<class protocol_t>
void reactor_t<protocol_t>::run_cpu_sharded_role(
int cpu_shard_number,
current_role_t *role,
const typename protocol_t::region_t& region,
multistore_ptr_t<protocol_t> *svs_subview,
signal_t *interruptor,
cond_t *abort_roles) THROWS_NOTHING {
store_view_t<protocol_t> *store_view = svs_subview->get_store(cpu_shard_number);
typename protocol_t::region_t cpu_sharded_region = region_intersection(region, protocol_t::cpu_sharding_subspace(cpu_shard_number, svs_subview->num_stores()));
switch (role->role) {
case blueprint_role_primary:
be_primary(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
case blueprint_role_secondary:
be_secondary(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
case blueprint_role_nothing:
be_nothing(cpu_sharded_region, store_view, role->blueprint.get_watchable(), interruptor);
break;
default:
unreachable();
break;
}
// When one role returns, make sure all others are aborted
if (!abort_roles->is_pulsed()) {
abort_roles->pulse();
}
}
template<class protocol_t>
bool we_see_our_bcard(const std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > &bcards, peer_id_t me) {
return std_contains(bcards, me);
}
template<class protocol_t>
void reactor_t<protocol_t>::run_role(
typename protocol_t::region_t region,
current_role_t *role,
auto_drainer_t::lock_t keepalive) THROWS_NOTHING {
//A store_view_t derived object that acts as a store for the specified region
multistore_ptr_t<protocol_t> svs_subview(underlying_svs, region);
{
//All of the be_{role} functions respond identically to blueprint changes
//and interruptions... so we just unify those signals
wait_any_t wait_any(&role->abort_roles, keepalive.get_drain_signal());
try {
directory_echo_mirror.get_internal()->run_until_satisfied(boost::bind(&we_see_our_bcard<protocol_t>, _1, get_me()), &wait_any);
} catch (const interrupted_exc_t &) {
goto CLEANUP;
}
// guarantee(CLUSTER_CPU_SHARDING_FACTOR == svs_subview.num_stores());
pmap(svs_subview.num_stores(), boost::bind(&reactor_t<protocol_t>::run_cpu_sharded_role, this, _1, role, region, &svs_subview, &wait_any, &role->abort_roles));
}
CLEANUP:
//As promised, clean up the state from try_spawn_roles
current_roles.erase(region);
delete role;
if (!keepalive.get_drain_signal()->is_pulsed()) {
try_spawn_roles();
}
}
template<class protocol_t>
boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > > reactor_t<protocol_t>::extract_broadcaster_from_reactor_business_card_primary(const boost::optional<boost::optional<typename reactor_business_card_t<protocol_t>::primary_t> > &bcard) {
if (!bcard) {
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >();
}
if (!bcard.get()) {
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >(
boost::optional<broadcaster_business_card_t<protocol_t> >());
}
return boost::optional<boost::optional<broadcaster_business_card_t<protocol_t> > >(
boost::optional<broadcaster_business_card_t<protocol_t> >(bcard.get().get().broadcaster));
}
template <class protocol_t>
void reactor_t<protocol_t>::wait_for_directory_acks(directory_echo_version_t version_to_wait_on, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
while (true) {
/* This function waits for acks from all the peers mentioned in the
blueprint. If the blueprint changes while we're waiting for acks, we
restart from the top. This is important because otherwise we might
deadlock. For example, if we were waiting for a machine to come back up
and then it was declared dead, our interruptor might not be pulsed but
the `ack_waiter_t` would never be pulsed so we would get stuck. */
cond_t blueprint_changed;
blueprint_t<protocol_t> bp;
typename watchable_t<blueprint_t<protocol_t> >::subscription_t subscription(
boost::bind(&cond_t::pulse_if_not_already_pulsed, &blueprint_changed));
{
typename watchable_t<blueprint_t<protocol_t> >::freeze_t freeze(blueprint_watchable);
bp = blueprint_watchable->get();
subscription.reset(blueprint_watchable, &freeze);
}
typename std::map<peer_id_t, std::map<typename protocol_t::region_t, blueprint_role_t> >::iterator it = bp.peers_roles.begin();
for (it = bp.peers_roles.begin(); it != bp.peers_roles.end(); it++) {
typename directory_echo_writer_t<cow_ptr_t<reactor_business_card_t<protocol_t> > >::ack_waiter_t ack_waiter(&directory_echo_writer, it->first, version_to_wait_on);
wait_any_t waiter(&ack_waiter, &blueprint_changed);
wait_interruptible(&waiter, interruptor);
if (blueprint_changed.is_pulsed()) {
break;
}
}
if (!blueprint_changed.is_pulsed()) {
break;
}
}
}
#include "mock/dummy_protocol.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"
template class reactor_t<mock::dummy_protocol_t>;
template class reactor_t<memcached_protocol_t>;
template class reactor_t<rdb_protocol_t>;
<|endoftext|> |
<commit_before><commit_msg>coverity#738566 Uninitialized pointer field<commit_after><|endoftext|> |
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php 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.
======================================================================*/
#ifndef __elxOptimizerBase_hxx
#define __elxOptimizerBase_hxx
#include "elxOptimizerBase.h"
#include "itkSingleValuedNonLinearOptimizer.h"
//#include <kwsys/MD5.h.in> // for MD5 hash
//#include KWSYS_HEADER(MD5.h)
namespace elastix
{
using namespace itk;
/**
* ****************** Constructor ***********************************
*/
template <class TElastix>
OptimizerBase<TElastix>
::OptimizerBase()
{
this->m_NewSamplesEveryIteration = false;
} // end Constructor
/**
* ****************** SetCurrentPositionPublic ************************
*
* Add empty SetCurrentPositionPublic, so it is known everywhere.
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SetCurrentPositionPublic( const ParametersType & /** param */ )
{
xl::xout["error"] << "ERROR: This function should be overridden or just "
<< "not used.\n";
xl::xout["error"] << " Are you using BSplineTransformWithDiffusion in "
<< "combination with another optimizer than the "
<< "StandardGradientDescentOptimizer? Don't!" << std::endl;
/** Throw an exception if this function is not overridden. */
itkExceptionMacro( << "ERROR: The SetCurrentPositionPublic method is not "
<< "implemented in your optimizer" );
} // end SetCurrentPositionPublic()
/**
* ****************** BeforeEachResolutionBase **********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::BeforeEachResolutionBase( void )
{
/** Get the current resolution level. */
unsigned int level
= this->GetRegistration()->GetAsITKBaseType()->GetCurrentLevel();
/** Check if after every iteration a new sample set should be created. */
this->m_NewSamplesEveryIteration = false;
this->GetConfiguration()->ReadParameter( this->m_NewSamplesEveryIteration,
"NewSamplesEveryIteration", this->GetComponentLabel(), level, 0 );
} // end BeforeEachResolutionBase()
/**
* ****************** AfterRegistrationBase **********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::AfterRegistrationBase( void )
{
// /** Get the final parameters. */
// ParametersType finalTP = this->GetAsITKBaseType()->GetCurrentPosition();
//
// /** Compute the MD5 Checksum. */
// unsigned char * md5InputData = reinterpret_cast<unsigned char *>( finalTP );
//
// kwsysMD5* md5 = kwsysMD5_New();
// kwsysMD5_Initialize( md5 );
// kwsysMD5_Append( md5, md5InputData, md5InputData->GetSize() );
// unsigned char digest[16];
// kwsysMD5_Finalize( md5, digest );
// kwsysMD5_Delete( md5 );
//
// // char md5out[33];
// // kwsysMD5_DigestToHex(digest, md5out);
// // md5out[32] = 0;
//
// elxout << "\nRegistration result checksum: "
// << digest
// << std::endl;
} // end AfterRegistrationBase()
/**
* ****************** SelectNewSamples ****************************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SelectNewSamples( void )
{
/** Force the metric to base its computation on a new subset of image samples.
* Not every metric may have implemented this.
*/
for ( unsigned int i = 0; i < this->GetElastix()->GetNumberOfMetrics(); ++i )
{
this->GetElastix()->GetElxMetricBase(i)->SelectNewSamples();
}
} // end SelectNewSamples()
/**
* ****************** GetNewSamplesEveryIteration ********************
*/
template <class TElastix>
bool
OptimizerBase<TElastix>
::GetNewSamplesEveryIteration( void ) const
{
/** itkGetConstMacro Without the itkDebugMacro. */
return this->m_NewSamplesEveryIteration;
} // end GetNewSamplesEveryIteration()
/**
* ****************** SetSinusScales ********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SetSinusScales( double amplitude, double frequency,
unsigned long numberOfParameters )
{
typedef typename ITKBaseType::ScalesType ScalesType;
const double nrofpar = static_cast<double>( numberOfParameters );
ScalesType scales( numberOfParameters );
for ( unsigned long i = 0; i < numberOfParameters; ++i )
{
const double x = static_cast<double>( i ) / nrofpar * 2.0
* vnl_math::pi * frequency;
scales[ i ] = vcl_pow( amplitude, vcl_sin( x ) );
}
this->GetAsITKBaseType()->SetScales( scales );
} // end SetSinusScales()
} // end namespace elastix
#endif // end #ifndef __elxOptimizerBase_hxx
<commit_msg>-ENH: implement computation of crc32 checksum on the final parameter vector, to facilitate testing (and comparison of registration results betweeen platforms). The crc checksum is written to the screen and log file. <commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php 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.
======================================================================*/
#ifndef __elxOptimizerBase_hxx
#define __elxOptimizerBase_hxx
#include "elxOptimizerBase.h"
#include "itkSingleValuedNonLinearOptimizer.h"
#include "itk_zlib.h"
namespace elastix
{
using namespace itk;
/**
* ****************** Constructor ***********************************
*/
template <class TElastix>
OptimizerBase<TElastix>
::OptimizerBase()
{
this->m_NewSamplesEveryIteration = false;
} // end Constructor
/**
* ****************** SetCurrentPositionPublic ************************
*
* Add empty SetCurrentPositionPublic, so it is known everywhere.
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SetCurrentPositionPublic( const ParametersType & /** param */ )
{
xl::xout["error"] << "ERROR: This function should be overridden or just "
<< "not used.\n";
xl::xout["error"] << " Are you using BSplineTransformWithDiffusion in "
<< "combination with another optimizer than the "
<< "StandardGradientDescentOptimizer? Don't!" << std::endl;
/** Throw an exception if this function is not overridden. */
itkExceptionMacro( << "ERROR: The SetCurrentPositionPublic method is not "
<< "implemented in your optimizer" );
} // end SetCurrentPositionPublic()
/**
* ****************** BeforeEachResolutionBase **********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::BeforeEachResolutionBase( void )
{
/** Get the current resolution level. */
unsigned int level
= this->GetRegistration()->GetAsITKBaseType()->GetCurrentLevel();
/** Check if after every iteration a new sample set should be created. */
this->m_NewSamplesEveryIteration = false;
this->GetConfiguration()->ReadParameter( this->m_NewSamplesEveryIteration,
"NewSamplesEveryIteration", this->GetComponentLabel(), level, 0 );
} // end BeforeEachResolutionBase()
/**
* ****************** AfterRegistrationBase **********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::AfterRegistrationBase( void )
{
typedef typename ParametersType::ValueType ParametersValueType;
/** Get the final parameters. */
ParametersType finalTP = this->GetAsITKBaseType()->GetCurrentPosition();
/** Compute the crc checksum using zlib crc32 function. */
const unsigned char * crcInputData = reinterpret_cast<const unsigned char *>( finalTP.data_block() );
uLong crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, crcInputData, finalTP.Size()* sizeof(ParametersValueType) );
elxout << "\nRegistration result checksum: "
<< crc
<< std::endl;
} // end AfterRegistrationBase()
/**
* ****************** SelectNewSamples ****************************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SelectNewSamples( void )
{
/** Force the metric to base its computation on a new subset of image samples.
* Not every metric may have implemented this.
*/
for ( unsigned int i = 0; i < this->GetElastix()->GetNumberOfMetrics(); ++i )
{
this->GetElastix()->GetElxMetricBase(i)->SelectNewSamples();
}
} // end SelectNewSamples()
/**
* ****************** GetNewSamplesEveryIteration ********************
*/
template <class TElastix>
bool
OptimizerBase<TElastix>
::GetNewSamplesEveryIteration( void ) const
{
/** itkGetConstMacro Without the itkDebugMacro. */
return this->m_NewSamplesEveryIteration;
} // end GetNewSamplesEveryIteration()
/**
* ****************** SetSinusScales ********************
*/
template <class TElastix>
void
OptimizerBase<TElastix>
::SetSinusScales( double amplitude, double frequency,
unsigned long numberOfParameters )
{
typedef typename ITKBaseType::ScalesType ScalesType;
const double nrofpar = static_cast<double>( numberOfParameters );
ScalesType scales( numberOfParameters );
for ( unsigned long i = 0; i < numberOfParameters; ++i )
{
const double x = static_cast<double>( i ) / nrofpar * 2.0
* vnl_math::pi * frequency;
scales[ i ] = vcl_pow( amplitude, vcl_sin( x ) );
}
this->GetAsITKBaseType()->SetScales( scales );
} // end SetSinusScales()
} // end namespace elastix
#endif // end #ifndef __elxOptimizerBase_hxx
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkNeighborhood.h"
#include "otbImage.h"
#include "itkVariableLengthVector.h"
#include "itkConstNeighborhoodIterator.h"
#include "otbTextureImageFunction.h"
#include "otbFunctionWithNeighborhoodToImageFilter.h"
#include "otbTextureFunctorBase.h"
template <class TIterInput1, class TIterInput2, class TOutput>
class TextureFunctorTest
{
public:
TextureFunctorTest()
{
m_Offset.Fill(1);
};
~TextureFunctorTest() {};
typedef TIterInput1 IterType1;
typedef TIterInput2 IterType2;
typedef TOutput OutputType;
typedef typename IterType1::OffsetType OffsetType;
typedef typename IterType1::InternalPixelType InternalPixelType;
typedef typename IterType1::ImageType ImageType;
typedef itk::Neighborhood<InternalPixelType, ::itk::GetImageDimension<ImageType>::ImageDimension> NeighborhoodType;
void SetOffset(OffsetType off){ m_Offset=off; };
inline TOutput operator()(const IterType1 &it, const IterType2 &itOff)
{
return static_cast<OutputType>(it.GetCenterPixel()[0]);
}
double ComputeOverSingleChannel(const NeighborhoodType &neigh, const NeighborhoodType &neighOff)
{
return 0.;
}
private:
OffsetType m_Offset;
};
int otbFunctionWithNeighborhoodToImageFilterNew(int argc, char * argv[])
{
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::Image<PixelType,Dimension> ImageType;
typedef itk::VariableLengthVector<double> VectorType;
typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType;
typedef TextureFunctorTest<IteratorType, IteratorType, VectorType> FunctorType;
typedef otb::TextureImageFunction<ImageType, FunctorType> FunctionType;
typedef otb::FunctionWithNeighborhoodToImageFilter<ImageType, ImageType, FunctionType> FilterType;
// Instantiating object
FilterType::Pointer object = FilterType::New();
return EXIT_SUCCESS;
}
<commit_msg>ENH : forgive a change after texture functor refactoring<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkNeighborhood.h"
#include "otbImage.h"
//#include "itkVariableLengthVector.h"
//#include "itkConstNeighborhoodIterator.h"
#include "otbTextureImageFunction.h"
#include "otbFunctionWithNeighborhoodToImageFilter.h"
#include "itkOffset.h"
//#include "otbTextureFunctorBase.h"
template <class TInputScalarType, class TOutputScalarType>//IterInput1, class TIterInput2, class TOutput>
class TextureFunctorTest
{
public:
TextureFunctorTest()
{
m_Offset.Fill(1);
};
~TextureFunctorTest() {};
typedef itk::Offset<> OffsetType;
typedef itk::Neighborhood<TInputScalarType, 2> NeighborhoodType;
void SetOffset(OffsetType off){ m_Offset=off; };
inline TOutputScalarType operator()(const NeighborhoodType &neigh)
{
return static_cast<TOutputScalarType>(neigh.GetCenterValue());
}
private:
OffsetType m_Offset;
};
int otbFunctionWithNeighborhoodToImageFilterNew(int argc, char * argv[])
{
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::Image<PixelType,Dimension> ImageType;
typedef itk::VariableLengthVector<double> VectorType;
typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType;
typedef TextureFunctorTest<PixelType, PixelType> FunctorType;
typedef otb::TextureImageFunction<ImageType, FunctorType> FunctionType;
typedef otb::FunctionWithNeighborhoodToImageFilter<ImageType, ImageType, FunctionType> FilterType;
// Instantiating object
FilterType::Pointer object = FilterType::New();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "Resolver.h"
#include "Requirement.h"
#include <cassert>
#include <exception>
#include <map>
#include <set>
#include <stdexcept>
using namespace Arbiter;
using namespace Resolver;
namespace {
struct DependencyNode final
{
public:
const ArbiterProjectIdentifier _project;
const ArbiterSelectedVersion _proposedVersion;
std::unique_ptr<ArbiterRequirement> _requirement;
std::set<DependencyNode> _dependencies;
DependencyNode (ArbiterProjectIdentifier project, ArbiterSelectedVersion proposedVersion, const ArbiterRequirement &requirement)
: _project(std::move(project))
, _proposedVersion(std::move(proposedVersion))
, _requirement(requirement.clone())
{
assert(_requirement->satisfiedBy(_proposedVersion._semanticVersion));
}
bool operator== (const DependencyNode &other) const
{
return _project == other._project && _proposedVersion == other._proposedVersion;
}
bool operator< (const DependencyNode &other) const
{
if (_project != other._project) {
// There's no well-defined ordering between nodes for different
// projects, and we don't want them to appear equal within a set.
return true;
}
// Sort such that higher versions are tried first.
return _proposedVersion > other._proposedVersion;
}
};
std::ostream &operator<< (std::ostream &os, const DependencyNode &node)
{
return os
<< node._project << " @ " << node._proposedVersion
<< " (restricted to " << *node._requirement << ")";
}
class DependencyGraph final
{
public:
std::set<DependencyNode> _allNodes;
std::map<DependencyNode, std::set<DependencyNode>> _edges;
std::set<DependencyNode> _roots;
bool operator== (const DependencyGraph &other) const
{
return _edges == other._edges && _roots == other._roots;
}
};
std::ostream &operator<< (std::ostream &os, const DependencyGraph &graph)
{
os << "Roots:";
for (const DependencyNode &root : graph._roots) {
os << "\n\t" << root;
}
os << "\n\nEdges";
for (const auto &pair : graph._edges) {
const DependencyNode &node = pair.first;
os << "\n\t" << node._project << " ->";
const auto &dependencies = pair.second;
for (const DependencyNode &dep : dependencies) {
os << "\n\t\t" << dep;
}
}
return os;
}
} // namespace
ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, ArbiterUserValue context)
{
return new ArbiterResolver(std::move(behaviors), *dependencyList, ArbiterResolver::Context(std::move(context)));
}
const void *ArbiterResolverContext (const ArbiterResolver *resolver)
{
return resolver->_context.data();
}
bool ArbiterResolvedAllDependencies (const ArbiterResolver *resolver)
{
return resolver->resolvedAll();
}
void ArbiterStartResolvingNextDependency (ArbiterResolver *resolver, ArbiterResolverCallbacks callbacks)
{
resolver->resolveNext().add_callback([resolver, callbacks = std::move(callbacks)](const auto &result) {
try {
const ResolvedDependency &dependency = result.rightOrThrowLeft();
callbacks.onSuccess(resolver, &dependency.projectIdentifier, &dependency.selectedVersion);
} catch (const std::exception &ex) {
callbacks.onError(resolver, ex.what());
}
});
}
void ArbiterFreeResolver (ArbiterResolver *resolver)
{
delete resolver;
}
ResolvedDependency ResolvedDependency::takeOwnership (ArbiterDependencyListFetch fetch) noexcept
{
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(fetch.project));
std::unique_ptr<ArbiterSelectedVersion> selectedVersion(const_cast<ArbiterSelectedVersion *>(fetch.selectedVersion));
return ResolvedDependency { std::move(*project), std::move(*selectedVersion) };
}
bool ResolvedDependency::operator== (const ResolvedDependency &other) const noexcept
{
return projectIdentifier == other.projectIdentifier && selectedVersion == other.selectedVersion;
}
bool ArbiterResolver::resolvedAll () const noexcept
{
return _remainingDependencies._dependencies.empty();
}
Arbiter::Future<ResolvedDependency> resolveNext ()
{
Arbiter::Promise<ResolvedDependency> promise;
// TODO: Actually resolve
return promise.get_future();
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::insertDependencyListFetch (ResolvedDependency dependency)
{
std::lock_guard<std::mutex> guard(_fetchesMutex);
return _dependencyListFetches[std::move(dependency)].get_future();
}
Arbiter::Promise<ArbiterDependencyList> ArbiterResolver::extractDependencyListFetch (const ResolvedDependency &dependency)
{
std::lock_guard<std::mutex> guard(_fetchesMutex);
Arbiter::Promise<ArbiterDependencyList> promise = std::move(_dependencyListFetches.at(dependency));
_dependencyListFetches.erase(dependency);
return promise;
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::fetchDependencyList (ResolvedDependency dependency)
{
// Eventually freed in the C callback function.
auto project = std::make_unique<ArbiterProjectIdentifier>(dependency.projectIdentifier);
auto version = std::make_unique<ArbiterSelectedVersion>(dependency.selectedVersion);
auto future = insertDependencyListFetch(std::move(dependency));
_behaviors.fetchDependencyList(
ArbiterDependencyListFetch { this, project.release(), version.release() },
&dependencyListFetchOnSuccess,
&dependencyListFetchOnError
);
return future;
}
void ArbiterResolver::dependencyListFetchOnSuccess (ArbiterDependencyListFetch cFetch, const ArbiterDependencyList *fetchedList)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
.set_value(*fetchedList);
}
void ArbiterResolver::dependencyListFetchOnError (ArbiterDependencyListFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
// TODO: Better error reporting
.set_exception(std::make_exception_ptr(std::runtime_error("Dependency list fetch failed")));
}
<commit_msg>Implement sharing of dependency nodes, and graph insertion<commit_after>#include "Resolver.h"
#include "Hash.h"
#include "Requirement.h"
#include <cassert>
#include <exception>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
using namespace Arbiter;
using namespace Resolver;
namespace {
/**
* A node in, or being considered for, an acyclic dependency graph.
*/
class DependencyNode final
{
public:
struct Hash final
{
public:
size_t operator() (const DependencyNode &node) const
{
return hashOf(node._project);
}
};
const ArbiterProjectIdentifier _project;
/**
* The version of the dependency that this node represents.
*
* This version is merely "proposed" because it depends on the final
* resolution of the graph, as well as whether any "better" graphs exist.
*/
const ArbiterSelectedVersion _proposedVersion;
DependencyNode (ArbiterProjectIdentifier project, ArbiterSelectedVersion proposedVersion, const ArbiterRequirement &requirement)
: _project(std::move(project))
, _proposedVersion(std::move(proposedVersion))
, _state(std::make_shared<State>())
{
setRequirement(requirement);
}
DependencyNode (const DependencyNode &other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(other._state)
{}
DependencyNode (DependencyNode &&other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(std::move(other._state))
{}
DependencyNode &operator= (const DependencyNode &other) = delete;
DependencyNode &operator= (DependencyNode &&other) = delete;
bool operator== (const DependencyNode &other) const
{
// For the purposes of node lookup in a graph, this is the only field
// which matters.
return _project == other._project;
}
/**
* The current requirement(s) applied to this dependency.
*
* This specifier may change as the graph is added to, and the requirements
* become more stringent.
*/
const ArbiterRequirement &requirement () const noexcept
{
return *_state->_requirement;
}
void setRequirement (const ArbiterRequirement &requirement)
{
setRequirement(requirement.clone());
}
void setRequirement (std::unique_ptr<ArbiterRequirement> requirement)
{
assert(requirement);
assert(requirement->satisfiedBy(_proposedVersion._semanticVersion));
_state->_requirement = std::move(requirement);
}
std::unordered_set<DependencyNode, Hash> &dependencies () noexcept
{
return _state->_dependencies;
}
const std::unordered_set<DependencyNode, Hash> &dependencies () const noexcept
{
return _state->_dependencies;
}
private:
struct State final
{
public:
std::unique_ptr<ArbiterRequirement> _requirement;
std::unordered_set<DependencyNode, Hash> _dependencies;
};
std::shared_ptr<State> _state;
};
std::ostream &operator<< (std::ostream &os, const DependencyNode &node)
{
return os
<< node._project << " @ " << node._proposedVersion
<< " (restricted to " << node.requirement() << ")";
}
} // namespace
namespace std {
template<>
struct hash<DependencyNode> final
{
public:
size_t operator() (const DependencyNode &node) const
{
return DependencyNode::Hash()(node);
}
};
} // namespace std
namespace {
/**
* Represents an acyclic dependency graph in which each project appears at most
* once.
*
* Dependency graphs can exist in an incomplete state, but will never be
* inconsistent (i.e., include versions that are known to be invalid given the
* current graph).
*/
class DependencyGraph final
{
public:
/**
* A full list of all nodes included in the graph.
*/
std::unordered_set<DependencyNode> _allNodes;
/**
* Maps between nodes in the graph and their immediate dependencies.
*/
std::unordered_map<DependencyNode, std::unordered_set<DependencyNode>> _edges;
/**
* The root nodes of the graph (i.e., those dependencies that are listed by
* the top-level project).
*/
std::unordered_set<DependencyNode> _roots;
bool operator== (const DependencyGraph &other) const
{
return _edges == other._edges && _roots == other._roots;
}
/**
* Attempts to add the given node into the graph, as a dependency of
* `dependent` if specified.
*
* If the given node refers to a project which already exists in the graph,
* this method will attempt to intersect the version requirements of both.
*
* Returns a pointer to the node as actually inserted into the graph (which
* may be different from the node passed in), or `nullptr` if this addition
* would make the graph inconsistent.
*/
DependencyNode *addNode (const DependencyNode &inputNode, const DependencyNode *dependent)
{
auto nodeInsertion = _allNodes.insert(inputNode);
// Unordered collections rightly discourage mutation so hashes don't get
// invalidated, but we've already handled this in the implementation of
// DependencyNode.
DependencyNode &insertedNode = const_cast<DependencyNode &>(*nodeInsertion.first);
// If no insertion was actually performed, we need to unify our input with
// what was already there.
if (!nodeInsertion.second) {
if (auto newRequirement = insertedNode.requirement().intersect(inputNode.requirement())) {
if (!newRequirement->satisfiedBy(insertedNode._proposedVersion._semanticVersion)) {
// This strengthened requirement invalidates the version we've
// proposed in this graph, so the graph would become inconsistent.
return nullptr;
}
insertedNode.setRequirement(std::move(newRequirement));
} else {
// If intersecting the requirements is impossible, the versions
// currently shouldn't be able to match.
//
// Notably, though, Carthage does permit scenarios like this when
// pinned to a branch. Arbiter doesn't support requirements like this
// right now, but may in the future.
assert(inputNode._proposedVersion != insertedNode._proposedVersion);
return nullptr;
}
}
if (dependent) {
_edges[*dependent].insert(insertedNode);
} else {
_roots.insert(insertedNode);
}
return &insertedNode;
}
};
std::ostream &operator<< (std::ostream &os, const DependencyGraph &graph)
{
os << "Roots:";
for (const DependencyNode &root : graph._roots) {
os << "\n\t" << root;
}
os << "\n\nEdges";
for (const auto &pair : graph._edges) {
const DependencyNode &node = pair.first;
os << "\n\t" << node._project << " ->";
const auto &dependencies = pair.second;
for (const DependencyNode &dep : dependencies) {
os << "\n\t\t" << dep;
}
}
return os;
}
} // namespace
ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, ArbiterUserValue context)
{
return new ArbiterResolver(std::move(behaviors), *dependencyList, ArbiterResolver::Context(std::move(context)));
}
const void *ArbiterResolverContext (const ArbiterResolver *resolver)
{
return resolver->_context.data();
}
bool ArbiterResolvedAllDependencies (const ArbiterResolver *resolver)
{
return resolver->resolvedAll();
}
void ArbiterStartResolvingNextDependency (ArbiterResolver *resolver, ArbiterResolverCallbacks callbacks)
{
resolver->resolveNext().add_callback([resolver, callbacks = std::move(callbacks)](const auto &result) {
try {
const ResolvedDependency &dependency = result.rightOrThrowLeft();
callbacks.onSuccess(resolver, &dependency.projectIdentifier, &dependency.selectedVersion);
} catch (const std::exception &ex) {
callbacks.onError(resolver, ex.what());
}
});
}
void ArbiterFreeResolver (ArbiterResolver *resolver)
{
delete resolver;
}
ResolvedDependency ResolvedDependency::takeOwnership (ArbiterDependencyListFetch fetch) noexcept
{
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(fetch.project));
std::unique_ptr<ArbiterSelectedVersion> selectedVersion(const_cast<ArbiterSelectedVersion *>(fetch.selectedVersion));
return ResolvedDependency { std::move(*project), std::move(*selectedVersion) };
}
bool ResolvedDependency::operator== (const ResolvedDependency &other) const noexcept
{
return projectIdentifier == other.projectIdentifier && selectedVersion == other.selectedVersion;
}
bool ArbiterResolver::resolvedAll () const noexcept
{
return _remainingDependencies._dependencies.empty();
}
Arbiter::Future<ResolvedDependency> resolveNext ()
{
Arbiter::Promise<ResolvedDependency> promise;
// TODO: Actually resolve
return promise.get_future();
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::insertDependencyListFetch (ResolvedDependency dependency)
{
std::lock_guard<std::mutex> guard(_fetchesMutex);
return _dependencyListFetches[std::move(dependency)].get_future();
}
Arbiter::Promise<ArbiterDependencyList> ArbiterResolver::extractDependencyListFetch (const ResolvedDependency &dependency)
{
std::lock_guard<std::mutex> guard(_fetchesMutex);
Arbiter::Promise<ArbiterDependencyList> promise = std::move(_dependencyListFetches.at(dependency));
_dependencyListFetches.erase(dependency);
return promise;
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::fetchDependencyList (ResolvedDependency dependency)
{
// Eventually freed in the C callback function.
auto project = std::make_unique<ArbiterProjectIdentifier>(dependency.projectIdentifier);
auto version = std::make_unique<ArbiterSelectedVersion>(dependency.selectedVersion);
auto future = insertDependencyListFetch(std::move(dependency));
_behaviors.fetchDependencyList(
ArbiterDependencyListFetch { this, project.release(), version.release() },
&dependencyListFetchOnSuccess,
&dependencyListFetchOnError
);
return future;
}
void ArbiterResolver::dependencyListFetchOnSuccess (ArbiterDependencyListFetch cFetch, const ArbiterDependencyList *fetchedList)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
.set_value(*fetchedList);
}
void ArbiterResolver::dependencyListFetchOnError (ArbiterDependencyListFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
// TODO: Better error reporting
.set_exception(std::make_exception_ptr(std::runtime_error("Dependency list fetch failed")));
}
<|endoftext|> |
<commit_before>#ifndef CV_ADAPTERS_ROWRANGE_HPP
#define CV_ADAPTERS_ROWRANGE_HPP
#include <iterator>
#include <opencv2/core/core.hpp>
template <typename T>
class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
RowRangeConstIterator()
: data()
, row()
, position(0)
{}
RowRangeConstIterator(const cv::Mat_<T>& m, int index)
: data(m)
, row(data.row(index))
, position(index)
{
CV_DbgAssert(position >= 0 && position <= data.rows + 1);
}
const cv::Mat_<T>& operator*() const
{
return row;
}
bool operator==(const RowRangeConstIterator& that) const
{
return this->position == that.position;
}
bool operator!=(const RowRangeConstIterator& that) const
{
return !(*this == that);
}
bool operator<(const RowRangeConstIterator& that) const
{
return this->position < that.position;
}
bool operator>(const RowRangeConstIterator& that) const
{
return this->position > that.position;
}
bool operator<=(const RowRangeConstIterator& that) const
{
return !(*this > that);
}
bool operator>=(const RowRangeConstIterator& that) const
{
return !(*this < that);
}
protected:
const cv::Mat_<T>& data;
mutable cv::Mat_<T> row;
int position;
};
template <typename T>
class RowRangeIterator : public RowRangeConstIterator
{
public:
RowRangeIterator(const cv::Mat_<T>& m, int position)
: RowRangeConstIterator(m, position)
{}
};
template <typename T>
class RowRange
{
public:
typedef RowRangeConstIterator const_iterator;
typedef RowRangeIterator iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
RowRange(cv::Mat m)
: data(m)
{
CV_Assert(m.type() == cv::DataType<T>::type);
}
RowRange(cv::Mat_<T> m)
: data(m) {}
private:
cv::Mat_<T> data;
cv::Range range;
};
#endif /* CV_ADAPTERS_ROWRANGE_HPP */
<commit_msg>Completing const iterator.<commit_after>#ifndef CV_ADAPTERS_ROWRANGE_HPP
#define CV_ADAPTERS_ROWRANGE_HPP
#include <iterator>
#include <opencv2/core/core.hpp>
template <typename T>
class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
RowRangeConstIterator()
: data()
, row()
, position(0)
{}
RowRangeConstIterator(const cv::Mat_<T>& m, int index)
: data(m)
, row(data.row(index))
, position(index)
{
CV_DbgAssert(position >= 0 && position <= data.rows + 1);
}
// Dereference
const cv::Mat_<T>& operator*() const
{
return row;
}
const cv::Mat_<T>* operator->() const
{
return &row;
}
// Logical comparison
bool operator==(const RowRangeConstIterator& that) const
{
return this->position == that.position;
}
bool operator!=(const RowRangeConstIterator& that) const
{
return !(*this == that);
}
bool operator<(const RowRangeConstIterator& that) const
{
return this->position < that.position;
}
bool operator>(const RowRangeConstIterator& that) const
{
return this->position > that.position;
}
bool operator<=(const RowRangeConstIterator& that) const
{
return !(*this > that);
}
bool operator>=(const RowRangeConstIterator& that) const
{
return !(*this < that);
}
// Increment
RowRangeConstIterator& operator++()
{
++position;
return *this;
}
RowRangeConstIterator operator++(int) const
{
RowRangeConstIterator tmp(*this);
++(*this);
return tmp;
}
protected:
const cv::Mat_<T>& data;
mutable cv::Mat_<T> row;
int position;
};
template <typename T>
class RowRangeIterator : public RowRangeConstIterator
{
public:
RowRangeIterator(const cv::Mat_<T>& m, int position)
: RowRangeConstIterator(m, position)
{}
};
template <typename T>
class RowRange
{
public:
typedef RowRangeConstIterator const_iterator;
typedef RowRangeIterator iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
RowRange(cv::Mat m)
: data(m)
{
CV_Assert(m.type() == cv::DataType<T>::type);
}
RowRange(cv::Mat_<T> m)
: data(m) {}
private:
cv::Mat_<T> data;
cv::Range range;
};
#endif /* CV_ADAPTERS_ROWRANGE_HPP */
<|endoftext|> |
<commit_before>#include "server/connection_handler_impl.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/network/filter.h"
#include "envoy/stats/scope.h"
#include "envoy/stats/timespan.h"
#include "common/network/connection_impl.h"
#include "common/network/utility.h"
#include "extensions/transport_sockets/well_known_names.h"
namespace Envoy {
namespace Server {
ConnectionHandlerImpl::ConnectionHandlerImpl(spdlog::logger& logger, Event::Dispatcher& dispatcher)
: logger_(logger), dispatcher_(dispatcher), disable_listeners_(false) {}
void ConnectionHandlerImpl::addListener(Network::ListenerConfig& config) {
ActiveListenerPtr l(new ActiveListener(*this, config));
if (disable_listeners_) {
l->listener_->disable();
}
listeners_.emplace_back(config.socket().localAddress(), std::move(l));
}
void ConnectionHandlerImpl::removeListeners(uint64_t listener_tag) {
for (auto listener = listeners_.begin(); listener != listeners_.end();) {
if (listener->second->listener_tag_ == listener_tag) {
listener = listeners_.erase(listener);
} else {
++listener;
}
}
}
void ConnectionHandlerImpl::stopListeners(uint64_t listener_tag) {
for (auto& listener : listeners_) {
if (listener.second->listener_tag_ == listener_tag) {
listener.second->listener_.reset();
}
}
}
void ConnectionHandlerImpl::stopListeners() {
for (auto& listener : listeners_) {
listener.second->listener_.reset();
}
}
void ConnectionHandlerImpl::disableListeners() {
disable_listeners_ = true;
for (auto& listener : listeners_) {
listener.second->listener_->disable();
}
}
void ConnectionHandlerImpl::enableListeners() {
disable_listeners_ = false;
for (auto& listener : listeners_) {
listener.second->listener_->enable();
}
}
void ConnectionHandlerImpl::ActiveListener::removeConnection(ActiveConnection& connection) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "adding to cleanup list",
*connection.connection_);
ActiveConnectionPtr removed = connection.removeFromList(connections_);
parent_.dispatcher_.deferredDelete(std::move(removed));
ASSERT(parent_.num_connections_ > 0);
parent_.num_connections_--;
}
ConnectionHandlerImpl::ActiveListener::ActiveListener(ConnectionHandlerImpl& parent,
Network::ListenerConfig& config)
: ActiveListener(parent,
parent.dispatcher_.createListener(
config.socket(), *this, config.handOffRestoredDestinationConnections()),
config) {}
ConnectionHandlerImpl::ActiveListener::ActiveListener(ConnectionHandlerImpl& parent,
Network::ListenerPtr&& listener,
Network::ListenerConfig& config)
: parent_(parent), listener_(std::move(listener)),
stats_(generateStats(config.listenerScope())),
listener_filters_timeout_(config.listenerFiltersTimeout()),
listener_tag_(config.listenerTag()), config_(config) {}
ConnectionHandlerImpl::ActiveListener::~ActiveListener() {
// Purge sockets that have not progressed to connections. This should only happen when
// a listener filter stops iteration and never resumes.
while (!sockets_.empty()) {
ActiveSocketPtr removed = sockets_.front()->removeFromList(sockets_);
parent_.dispatcher_.deferredDelete(std::move(removed));
}
while (!connections_.empty()) {
connections_.front()->connection_->close(Network::ConnectionCloseType::NoFlush);
}
parent_.dispatcher_.clearDeferredDeleteList();
}
Network::Listener*
ConnectionHandlerImpl::findListenerByAddress(const Network::Address::Instance& address) {
ActiveListener* listener = findActiveListenerByAddress(address);
return listener ? listener->listener_.get() : nullptr;
}
ConnectionHandlerImpl::ActiveListener*
ConnectionHandlerImpl::findActiveListenerByAddress(const Network::Address::Instance& address) {
// This is a linear operation, may need to add a map<address, listener> to improve performance.
// However, linear performance might be adequate since the number of listeners is small.
// We do not return stopped listeners.
auto listener_it = std::find_if(
listeners_.begin(), listeners_.end(),
[&address](const std::pair<Network::Address::InstanceConstSharedPtr, ActiveListenerPtr>& p) {
return p.second->listener_ != nullptr && p.first->type() == Network::Address::Type::Ip &&
*(p.first) == address;
});
// If there is exact address match, return the corresponding listener.
if (listener_it != listeners_.end()) {
return listener_it->second.get();
}
// Otherwise, we need to look for the wild card match, i.e., 0.0.0.0:[address_port].
// We do not return stopped listeners.
// TODO(wattli): consolidate with previous search for more efficiency.
listener_it = std::find_if(
listeners_.begin(), listeners_.end(),
[&address](const std::pair<Network::Address::InstanceConstSharedPtr, ActiveListenerPtr>& p) {
return p.second->listener_ != nullptr && p.first->type() == Network::Address::Type::Ip &&
p.first->ip()->port() == address.ip()->port() && p.first->ip()->isAnyAddress();
});
return (listener_it != listeners_.end()) ? listener_it->second.get() : nullptr;
}
void ConnectionHandlerImpl::ActiveSocket::onTimeout() {
listener_.stats_.downstream_pre_cx_timeout_.inc();
ASSERT(inserted());
unlink();
}
void ConnectionHandlerImpl::ActiveSocket::startTimer() {
if (listener_.listener_filters_timeout_.count() > 0) {
timer_ = listener_.parent_.dispatcher_.createTimer([this]() -> void { onTimeout(); });
timer_->enableTimer(listener_.listener_filters_timeout_);
}
}
void ConnectionHandlerImpl::ActiveSocket::unlink() {
ActiveSocketPtr removed = removeFromList(listener_.sockets_);
if (removed->timer_ != nullptr) {
removed->timer_->disableTimer();
}
listener_.parent_.dispatcher_.deferredDelete(std::move(removed));
}
void ConnectionHandlerImpl::ActiveSocket::continueFilterChain(bool success) {
if (success) {
if (iter_ == accept_filters_.end()) {
iter_ = accept_filters_.begin();
} else {
iter_ = std::next(iter_);
}
for (; iter_ != accept_filters_.end(); iter_++) {
Network::FilterStatus status = (*iter_)->onAccept(*this);
if (status == Network::FilterStatus::StopIteration) {
// The filter is responsible for calling us again at a later time to continue the filter
// chain from the next filter.
return;
}
}
// Successfully ran all the accept filters.
// Check if the socket may need to be redirected to another listener.
ActiveListener* new_listener = nullptr;
if (hand_off_restored_destination_connections_ && socket_->localAddressRestored()) {
// Find a listener associated with the original destination address.
new_listener = listener_.parent_.findActiveListenerByAddress(*socket_->localAddress());
}
if (new_listener != nullptr) {
// Hands off connections redirected by iptables to the listener associated with the
// original destination address. Pass 'hand_off_restored_destionations' as false to
// prevent further redirection.
new_listener->onAccept(std::move(socket_), false);
} else {
// Set default transport protocol if none of the listener filters did it.
if (socket_->detectedTransportProtocol().empty()) {
socket_->setDetectedTransportProtocol(
Extensions::TransportSockets::TransportSocketNames::get().RawBuffer);
}
// Create a new connection on this listener.
listener_.newConnection(std::move(socket_));
}
}
// Filter execution concluded, unlink and delete this ActiveSocket if it was linked.
if (inserted()) {
unlink();
}
}
void ConnectionHandlerImpl::ActiveListener::onAccept(
Network::ConnectionSocketPtr&& socket, bool hand_off_restored_destination_connections) {
Network::Address::InstanceConstSharedPtr local_address = socket->localAddress();
auto active_socket = std::make_unique<ActiveSocket>(*this, std::move(socket),
hand_off_restored_destination_connections);
// Create and run the filters
config_.filterChainFactory().createListenerFilterChain(*active_socket);
active_socket->continueFilterChain(true);
// Move active_socket to the sockets_ list if filter iteration needs to continue later.
// Otherwise we let active_socket be destructed when it goes out of scope.
if (active_socket->iter_ != active_socket->accept_filters_.end()) {
active_socket->startTimer();
active_socket->moveIntoListBack(std::move(active_socket), sockets_);
}
}
void ConnectionHandlerImpl::ActiveListener::newConnection(Network::ConnectionSocketPtr&& socket) {
// Find matching filter chain.
const auto filter_chain = config_.filterChainManager().findFilterChain(*socket);
if (filter_chain == nullptr) {
ENVOY_LOG_TO_LOGGER(parent_.logger_, debug,
"closing connection: no matching filter chain found");
stats_.no_filter_chain_match_.inc();
socket->close();
return;
}
auto transport_socket = filter_chain->transportSocketFactory().createTransportSocket(nullptr);
Network::ConnectionPtr new_connection =
parent_.dispatcher_.createServerConnection(std::move(socket), std::move(transport_socket));
new_connection->setBufferLimits(config_.perConnectionBufferLimitBytes());
new_connection->setWriteFilterOrder(config_.reverseWriteFilterOrder());
const bool empty_filter_chain = !config_.filterChainFactory().createNetworkFilterChain(
*new_connection, filter_chain->networkFilterFactories());
if (empty_filter_chain) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "closing connection: no filters",
*new_connection);
new_connection->close(Network::ConnectionCloseType::NoFlush);
return;
}
onNewConnection(std::move(new_connection));
}
void ConnectionHandlerImpl::ActiveListener::onNewConnection(
Network::ConnectionPtr&& new_connection) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "new connection", *new_connection);
// If the connection is already closed, we can just let this connection immediately die.
if (new_connection->state() != Network::Connection::State::Closed) {
ActiveConnectionPtr active_connection(
new ActiveConnection(*this, std::move(new_connection), parent_.dispatcher_.timeSystem()));
active_connection->moveIntoList(std::move(active_connection), connections_);
parent_.num_connections_++;
}
}
ConnectionHandlerImpl::ActiveConnection::ActiveConnection(ActiveListener& listener,
Network::ConnectionPtr&& new_connection,
Event::TimeSystem& time_system)
: listener_(listener), connection_(std::move(new_connection)),
conn_length_(new Stats::Timespan(listener_.stats_.downstream_cx_length_ms_, time_system)) {
// We just universally set no delay on connections. Theoretically we might at some point want
// to make this configurable.
connection_->noDelay(true);
connection_->addConnectionCallbacks(*this);
listener_.stats_.downstream_cx_total_.inc();
listener_.stats_.downstream_cx_active_.inc();
}
ConnectionHandlerImpl::ActiveConnection::~ActiveConnection() {
listener_.stats_.downstream_cx_active_.dec();
listener_.stats_.downstream_cx_destroy_.inc();
conn_length_->complete();
}
ListenerStats ConnectionHandlerImpl::generateStats(Stats::Scope& scope) {
return {ALL_LISTENER_STATS(POOL_COUNTER(scope), POOL_GAUGE(scope), POOL_HISTOGRAM(scope))};
}
} // namespace Server
} // namespace Envoy
<commit_msg>Useless line in onAccept and should be removed. (#5299)<commit_after>#include "server/connection_handler_impl.h"
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/network/filter.h"
#include "envoy/stats/scope.h"
#include "envoy/stats/timespan.h"
#include "common/network/connection_impl.h"
#include "common/network/utility.h"
#include "extensions/transport_sockets/well_known_names.h"
namespace Envoy {
namespace Server {
ConnectionHandlerImpl::ConnectionHandlerImpl(spdlog::logger& logger, Event::Dispatcher& dispatcher)
: logger_(logger), dispatcher_(dispatcher), disable_listeners_(false) {}
void ConnectionHandlerImpl::addListener(Network::ListenerConfig& config) {
ActiveListenerPtr l(new ActiveListener(*this, config));
if (disable_listeners_) {
l->listener_->disable();
}
listeners_.emplace_back(config.socket().localAddress(), std::move(l));
}
void ConnectionHandlerImpl::removeListeners(uint64_t listener_tag) {
for (auto listener = listeners_.begin(); listener != listeners_.end();) {
if (listener->second->listener_tag_ == listener_tag) {
listener = listeners_.erase(listener);
} else {
++listener;
}
}
}
void ConnectionHandlerImpl::stopListeners(uint64_t listener_tag) {
for (auto& listener : listeners_) {
if (listener.second->listener_tag_ == listener_tag) {
listener.second->listener_.reset();
}
}
}
void ConnectionHandlerImpl::stopListeners() {
for (auto& listener : listeners_) {
listener.second->listener_.reset();
}
}
void ConnectionHandlerImpl::disableListeners() {
disable_listeners_ = true;
for (auto& listener : listeners_) {
listener.second->listener_->disable();
}
}
void ConnectionHandlerImpl::enableListeners() {
disable_listeners_ = false;
for (auto& listener : listeners_) {
listener.second->listener_->enable();
}
}
void ConnectionHandlerImpl::ActiveListener::removeConnection(ActiveConnection& connection) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "adding to cleanup list",
*connection.connection_);
ActiveConnectionPtr removed = connection.removeFromList(connections_);
parent_.dispatcher_.deferredDelete(std::move(removed));
ASSERT(parent_.num_connections_ > 0);
parent_.num_connections_--;
}
ConnectionHandlerImpl::ActiveListener::ActiveListener(ConnectionHandlerImpl& parent,
Network::ListenerConfig& config)
: ActiveListener(parent,
parent.dispatcher_.createListener(
config.socket(), *this, config.handOffRestoredDestinationConnections()),
config) {}
ConnectionHandlerImpl::ActiveListener::ActiveListener(ConnectionHandlerImpl& parent,
Network::ListenerPtr&& listener,
Network::ListenerConfig& config)
: parent_(parent), listener_(std::move(listener)),
stats_(generateStats(config.listenerScope())),
listener_filters_timeout_(config.listenerFiltersTimeout()),
listener_tag_(config.listenerTag()), config_(config) {}
ConnectionHandlerImpl::ActiveListener::~ActiveListener() {
// Purge sockets that have not progressed to connections. This should only happen when
// a listener filter stops iteration and never resumes.
while (!sockets_.empty()) {
ActiveSocketPtr removed = sockets_.front()->removeFromList(sockets_);
parent_.dispatcher_.deferredDelete(std::move(removed));
}
while (!connections_.empty()) {
connections_.front()->connection_->close(Network::ConnectionCloseType::NoFlush);
}
parent_.dispatcher_.clearDeferredDeleteList();
}
Network::Listener*
ConnectionHandlerImpl::findListenerByAddress(const Network::Address::Instance& address) {
ActiveListener* listener = findActiveListenerByAddress(address);
return listener ? listener->listener_.get() : nullptr;
}
ConnectionHandlerImpl::ActiveListener*
ConnectionHandlerImpl::findActiveListenerByAddress(const Network::Address::Instance& address) {
// This is a linear operation, may need to add a map<address, listener> to improve performance.
// However, linear performance might be adequate since the number of listeners is small.
// We do not return stopped listeners.
auto listener_it = std::find_if(
listeners_.begin(), listeners_.end(),
[&address](const std::pair<Network::Address::InstanceConstSharedPtr, ActiveListenerPtr>& p) {
return p.second->listener_ != nullptr && p.first->type() == Network::Address::Type::Ip &&
*(p.first) == address;
});
// If there is exact address match, return the corresponding listener.
if (listener_it != listeners_.end()) {
return listener_it->second.get();
}
// Otherwise, we need to look for the wild card match, i.e., 0.0.0.0:[address_port].
// We do not return stopped listeners.
// TODO(wattli): consolidate with previous search for more efficiency.
listener_it = std::find_if(
listeners_.begin(), listeners_.end(),
[&address](const std::pair<Network::Address::InstanceConstSharedPtr, ActiveListenerPtr>& p) {
return p.second->listener_ != nullptr && p.first->type() == Network::Address::Type::Ip &&
p.first->ip()->port() == address.ip()->port() && p.first->ip()->isAnyAddress();
});
return (listener_it != listeners_.end()) ? listener_it->second.get() : nullptr;
}
void ConnectionHandlerImpl::ActiveSocket::onTimeout() {
listener_.stats_.downstream_pre_cx_timeout_.inc();
ASSERT(inserted());
unlink();
}
void ConnectionHandlerImpl::ActiveSocket::startTimer() {
if (listener_.listener_filters_timeout_.count() > 0) {
timer_ = listener_.parent_.dispatcher_.createTimer([this]() -> void { onTimeout(); });
timer_->enableTimer(listener_.listener_filters_timeout_);
}
}
void ConnectionHandlerImpl::ActiveSocket::unlink() {
ActiveSocketPtr removed = removeFromList(listener_.sockets_);
if (removed->timer_ != nullptr) {
removed->timer_->disableTimer();
}
listener_.parent_.dispatcher_.deferredDelete(std::move(removed));
}
void ConnectionHandlerImpl::ActiveSocket::continueFilterChain(bool success) {
if (success) {
if (iter_ == accept_filters_.end()) {
iter_ = accept_filters_.begin();
} else {
iter_ = std::next(iter_);
}
for (; iter_ != accept_filters_.end(); iter_++) {
Network::FilterStatus status = (*iter_)->onAccept(*this);
if (status == Network::FilterStatus::StopIteration) {
// The filter is responsible for calling us again at a later time to continue the filter
// chain from the next filter.
return;
}
}
// Successfully ran all the accept filters.
// Check if the socket may need to be redirected to another listener.
ActiveListener* new_listener = nullptr;
if (hand_off_restored_destination_connections_ && socket_->localAddressRestored()) {
// Find a listener associated with the original destination address.
new_listener = listener_.parent_.findActiveListenerByAddress(*socket_->localAddress());
}
if (new_listener != nullptr) {
// Hands off connections redirected by iptables to the listener associated with the
// original destination address. Pass 'hand_off_restored_destionations' as false to
// prevent further redirection.
new_listener->onAccept(std::move(socket_), false);
} else {
// Set default transport protocol if none of the listener filters did it.
if (socket_->detectedTransportProtocol().empty()) {
socket_->setDetectedTransportProtocol(
Extensions::TransportSockets::TransportSocketNames::get().RawBuffer);
}
// Create a new connection on this listener.
listener_.newConnection(std::move(socket_));
}
}
// Filter execution concluded, unlink and delete this ActiveSocket if it was linked.
if (inserted()) {
unlink();
}
}
void ConnectionHandlerImpl::ActiveListener::onAccept(
Network::ConnectionSocketPtr&& socket, bool hand_off_restored_destination_connections) {
auto active_socket = std::make_unique<ActiveSocket>(*this, std::move(socket),
hand_off_restored_destination_connections);
// Create and run the filters
config_.filterChainFactory().createListenerFilterChain(*active_socket);
active_socket->continueFilterChain(true);
// Move active_socket to the sockets_ list if filter iteration needs to continue later.
// Otherwise we let active_socket be destructed when it goes out of scope.
if (active_socket->iter_ != active_socket->accept_filters_.end()) {
active_socket->startTimer();
active_socket->moveIntoListBack(std::move(active_socket), sockets_);
}
}
void ConnectionHandlerImpl::ActiveListener::newConnection(Network::ConnectionSocketPtr&& socket) {
// Find matching filter chain.
const auto filter_chain = config_.filterChainManager().findFilterChain(*socket);
if (filter_chain == nullptr) {
ENVOY_LOG_TO_LOGGER(parent_.logger_, debug,
"closing connection: no matching filter chain found");
stats_.no_filter_chain_match_.inc();
socket->close();
return;
}
auto transport_socket = filter_chain->transportSocketFactory().createTransportSocket(nullptr);
Network::ConnectionPtr new_connection =
parent_.dispatcher_.createServerConnection(std::move(socket), std::move(transport_socket));
new_connection->setBufferLimits(config_.perConnectionBufferLimitBytes());
new_connection->setWriteFilterOrder(config_.reverseWriteFilterOrder());
const bool empty_filter_chain = !config_.filterChainFactory().createNetworkFilterChain(
*new_connection, filter_chain->networkFilterFactories());
if (empty_filter_chain) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "closing connection: no filters",
*new_connection);
new_connection->close(Network::ConnectionCloseType::NoFlush);
return;
}
onNewConnection(std::move(new_connection));
}
void ConnectionHandlerImpl::ActiveListener::onNewConnection(
Network::ConnectionPtr&& new_connection) {
ENVOY_CONN_LOG_TO_LOGGER(parent_.logger_, debug, "new connection", *new_connection);
// If the connection is already closed, we can just let this connection immediately die.
if (new_connection->state() != Network::Connection::State::Closed) {
ActiveConnectionPtr active_connection(
new ActiveConnection(*this, std::move(new_connection), parent_.dispatcher_.timeSystem()));
active_connection->moveIntoList(std::move(active_connection), connections_);
parent_.num_connections_++;
}
}
ConnectionHandlerImpl::ActiveConnection::ActiveConnection(ActiveListener& listener,
Network::ConnectionPtr&& new_connection,
Event::TimeSystem& time_system)
: listener_(listener), connection_(std::move(new_connection)),
conn_length_(new Stats::Timespan(listener_.stats_.downstream_cx_length_ms_, time_system)) {
// We just universally set no delay on connections. Theoretically we might at some point want
// to make this configurable.
connection_->noDelay(true);
connection_->addConnectionCallbacks(*this);
listener_.stats_.downstream_cx_total_.inc();
listener_.stats_.downstream_cx_active_.inc();
}
ConnectionHandlerImpl::ActiveConnection::~ActiveConnection() {
listener_.stats_.downstream_cx_active_.dec();
listener_.stats_.downstream_cx_destroy_.inc();
conn_length_->complete();
}
ListenerStats ConnectionHandlerImpl::generateStats(Stats::Scope& scope) {
return {ALL_LISTENER_STATS(POOL_COUNTER(scope), POOL_GAUGE(scope), POOL_HISTOGRAM(scope))};
}
} // namespace Server
} // namespace Envoy
<|endoftext|> |
<commit_before>//===- SymbolTable.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Config.h"
#include "Driver.h"
#include "Error.h"
#include "SymbolTable.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/LTO/LTOCodeGenerator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace lld {
namespace coff {
SymbolTable::SymbolTable() {
resolve(new (Alloc) DefinedAbsolute("__ImageBase", Config->ImageBase));
if (!Config->EntryName.empty())
resolve(new (Alloc) Undefined(Config->EntryName));
}
void SymbolTable::addFile(std::unique_ptr<InputFile> File) {
Files.push_back(std::move(File));
}
std::error_code SymbolTable::run() {
while (FileIdx < Files.size()) {
InputFile *F = Files[FileIdx++].get();
if (Config->Verbose)
llvm::outs() << "Reading " << F->getShortName() << "\n";
if (auto EC = F->parse())
return EC;
if (auto *P = dyn_cast<ObjectFile>(F)) {
ObjectFiles.push_back(P);
} else if (auto *P = dyn_cast<ArchiveFile>(F)) {
ArchiveFiles.push_back(P);
} else if (auto *P = dyn_cast<BitcodeFile>(F)) {
BitcodeFiles.push_back(P);
} else {
ImportFiles.push_back(cast<ImportFile>(F));
}
for (SymbolBody *B : F->getSymbols())
if (B->isExternal())
if (auto EC = resolve(B))
return EC;
// If a object file contains .drectve section,
// read that and add files listed there.
StringRef S = F->getDirectives();
if (!S.empty())
if (auto EC = Driver->parseDirectives(S))
return EC;
}
return std::error_code();
}
bool SymbolTable::reportRemainingUndefines() {
bool Ret = false;
for (auto &I : Symtab) {
Symbol *Sym = I.second;
auto *Undef = dyn_cast<Undefined>(Sym->Body);
if (!Undef)
continue;
if (SymbolBody *Alias = Undef->getWeakAlias()) {
Sym->Body = Alias->getReplacement();
if (!isa<Defined>(Sym->Body)) {
// Aliases are yet another symbols pointed by other symbols
// that could also remain undefined.
llvm::errs() << "undefined symbol: " << Undef->getName() << "\n";
Ret = true;
}
continue;
}
llvm::errs() << "undefined symbol: " << Undef->getName() << "\n";
Ret = true;
}
return Ret;
}
// This function resolves conflicts if there's an existing symbol with
// the same name. Decisions are made based on symbol type.
std::error_code SymbolTable::resolve(SymbolBody *New) {
// Find an existing Symbol or create and insert a new one.
StringRef Name = New->getName();
Symbol *&Sym = Symtab[Name];
if (!Sym) {
Sym = new (Alloc) Symbol(New);
New->setBackref(Sym);
++Version;
return std::error_code();
}
New->setBackref(Sym);
// compare() returns -1, 0, or 1 if the lhs symbol is less preferable,
// equivalent (conflicting), or more preferable, respectively.
SymbolBody *Existing = Sym->Body;
int comp = Existing->compare(New);
if (comp < 0) {
Sym->Body = New;
++Version;
}
if (comp == 0) {
llvm::errs() << "duplicate symbol: " << Name << "\n";
return make_error_code(LLDError::DuplicateSymbols);
}
// If we have an Undefined symbol for a Lazy symbol, we need
// to read an archive member to replace the Lazy symbol with
// a Defined symbol.
if (isa<Undefined>(Existing) || isa<Undefined>(New))
if (auto *B = dyn_cast<Lazy>(Sym->Body))
return addMemberFile(B);
return std::error_code();
}
// Reads an archive member file pointed by a given symbol.
std::error_code SymbolTable::addMemberFile(Lazy *Body) {
auto FileOrErr = Body->getMember();
if (auto EC = FileOrErr.getError())
return EC;
std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
// getMember returns an empty buffer if the member was already
// read from the library.
if (!File)
return std::error_code();
if (Config->Verbose)
llvm::outs() << "Loaded " << File->getShortName() << " for "
<< Body->getName() << "\n";
addFile(std::move(File));
return std::error_code();
}
std::vector<Chunk *> SymbolTable::getChunks() {
std::vector<Chunk *> Res;
for (ObjectFile *File : ObjectFiles) {
std::vector<Chunk *> &V = File->getChunks();
Res.insert(Res.end(), V.begin(), V.end());
}
return Res;
}
Defined *SymbolTable::find(StringRef Name) {
auto It = Symtab.find(Name);
if (It == Symtab.end())
return nullptr;
if (auto *Def = dyn_cast<Defined>(It->second->Body))
return Def;
return nullptr;
}
std::error_code SymbolTable::resolveLazy(StringRef Name) {
auto It = Symtab.find(Name);
if (It == Symtab.end())
return std::error_code();
if (auto *B = dyn_cast<Lazy>(It->second->Body)) {
if (auto EC = addMemberFile(B))
return EC;
return run();
}
return std::error_code();
}
// Windows specific -- Link default entry point name.
ErrorOr<StringRef> SymbolTable::findDefaultEntry() {
// If it's DLL, the rule is easy.
if (Config->DLL) {
StringRef Sym = "_DllMainCRTStartup";
if (auto EC = resolve(new (Alloc) Undefined(Sym)))
return EC;
return Sym;
}
// User-defined main functions and their corresponding entry points.
static const char *Entries[][2] = {
{"main", "mainCRTStartup"},
{"wmain", "wmainCRTStartup"},
{"WinMain", "WinMainCRTStartup"},
{"wWinMain", "wWinMainCRTStartup"},
};
for (auto E : Entries) {
resolveLazy(E[1]);
if (find(E[1]))
return StringRef(E[1]);
if (!find(E[0]))
continue;
if (auto EC = resolve(new (Alloc) Undefined(E[1])))
return EC;
return StringRef(E[1]);
}
llvm::errs() << "entry point must be defined\n";
return make_error_code(LLDError::InvalidOption);
}
std::error_code SymbolTable::addUndefined(StringRef Name) {
return resolve(new (Alloc) Undefined(Name));
}
// Resolve To, and make From an alias to To.
std::error_code SymbolTable::rename(StringRef From, StringRef To) {
// If From is not undefined, do nothing.
// Otherwise, rename it to see if To can be resolved instead.
auto It = Symtab.find(From);
if (It == Symtab.end())
return std::error_code();
Symbol *Sym = It->second;
if (!isa<Undefined>(Sym->Body))
return std::error_code();
SymbolBody *Body = new (Alloc) Undefined(To);
if (auto EC = resolve(Body))
return EC;
Sym->Body = Body->getReplacement();
Body->setBackref(Sym);
++Version;
return std::error_code();
}
void SymbolTable::dump() {
for (auto &P : Symtab) {
Symbol *Ref = P.second;
if (auto *Body = dyn_cast<Defined>(Ref->Body))
llvm::dbgs() << Twine::utohexstr(Config->ImageBase + Body->getRVA())
<< " " << Body->getName() << "\n";
}
}
std::error_code SymbolTable::addCombinedLTOObject() {
if (BitcodeFiles.empty())
return std::error_code();
// Create an object file and add it to the symbol table by replacing any
// DefinedBitcode symbols with the definitions in the object file.
LTOCodeGenerator CG;
auto FileOrErr = createLTOObject(&CG);
if (auto EC = FileOrErr.getError())
return EC;
ObjectFile *Obj = FileOrErr.get();
// Skip the combined object file as the file is processed below
// rather than by run().
++FileIdx;
for (SymbolBody *Body : Obj->getSymbols()) {
if (!Body->isExternal())
continue;
// Find an existing Symbol. We should not see any new undefined symbols at
// this point.
StringRef Name = Body->getName();
Symbol *&Sym = Symtab[Name];
if (!Sym) {
if (!isa<Defined>(Body)) {
llvm::errs() << "LTO: undefined symbol: " << Name << '\n';
return make_error_code(LLDError::BrokenFile);
}
Sym = new (Alloc) Symbol(Body);
Body->setBackref(Sym);
continue;
}
Body->setBackref(Sym);
if (isa<DefinedBitcode>(Sym->Body)) {
// The symbol should now be defined.
if (!isa<Defined>(Body)) {
llvm::errs() << "LTO: undefined symbol: " << Name << '\n';
return make_error_code(LLDError::BrokenFile);
}
Sym->Body = Body;
} else {
int comp = Sym->Body->compare(Body);
if (comp < 0)
Sym->Body = Body;
if (comp == 0) {
llvm::errs() << "LTO: unexpected duplicate symbol: " << Name << "\n";
return make_error_code(LLDError::BrokenFile);
}
}
// We may see new references to runtime library symbols such as __chkstk
// here. These symbols must be wholly defined in non-bitcode files.
if (auto *B = dyn_cast<Lazy>(Sym->Body))
addMemberFile(B);
}
size_t NumBitcodeFiles = BitcodeFiles.size();
if (auto EC = run())
return EC;
if (BitcodeFiles.size() != NumBitcodeFiles) {
llvm::errs() << "LTO: late loaded symbol created new bitcode reference\n";
return make_error_code(LLDError::BrokenFile);
}
// New runtime library symbol references may have created undefined references.
if (reportRemainingUndefines())
return make_error_code(LLDError::BrokenFile);
return std::error_code();
}
// Combine and compile bitcode files and then return the result
// as a regular COFF object file.
ErrorOr<ObjectFile *> SymbolTable::createLTOObject(LTOCodeGenerator *CG) {
// All symbols referenced by non-bitcode objects must be preserved.
for (ObjectFile *File : ObjectFiles)
for (SymbolBody *Body : File->getSymbols())
if (auto *S = dyn_cast<DefinedBitcode>(Body->getReplacement()))
CG->addMustPreserveSymbol(S->getName());
// Likewise for bitcode symbols which we initially resolved to non-bitcode.
for (BitcodeFile *File : BitcodeFiles)
for (SymbolBody *Body : File->getSymbols())
if (isa<DefinedBitcode>(Body) &&
!isa<DefinedBitcode>(Body->getReplacement()))
CG->addMustPreserveSymbol(Body->getName());
// Likewise for other symbols that must be preserved.
for (StringRef Name : Config->GCRoots)
if (isa<DefinedBitcode>(Symtab[Name]->Body))
CG->addMustPreserveSymbol(Name);
CG->setModule(BitcodeFiles[0]->releaseModule());
for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I)
CG->addModule(BitcodeFiles[I]->getModule());
std::string ErrMsg;
LTOMB = CG->compile(false, false, false, ErrMsg); // take MB ownership
if (!LTOMB) {
llvm::errs() << ErrMsg << '\n';
return make_error_code(LLDError::BrokenFile);
}
auto *Obj = new ObjectFile(LTOMB->getMemBufferRef());
Files.emplace_back(Obj);
ObjectFiles.push_back(Obj);
if (auto EC = Obj->parse())
return EC;
return Obj;
}
} // namespace coff
} // namespace lld
<commit_msg>COFF: Add some error checking to SymbolTable::addCombinedLTOObject().<commit_after>//===- SymbolTable.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Config.h"
#include "Driver.h"
#include "Error.h"
#include "SymbolTable.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/LTO/LTOCodeGenerator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace lld {
namespace coff {
SymbolTable::SymbolTable() {
resolve(new (Alloc) DefinedAbsolute("__ImageBase", Config->ImageBase));
if (!Config->EntryName.empty())
resolve(new (Alloc) Undefined(Config->EntryName));
}
void SymbolTable::addFile(std::unique_ptr<InputFile> File) {
Files.push_back(std::move(File));
}
std::error_code SymbolTable::run() {
while (FileIdx < Files.size()) {
InputFile *F = Files[FileIdx++].get();
if (Config->Verbose)
llvm::outs() << "Reading " << F->getShortName() << "\n";
if (auto EC = F->parse())
return EC;
if (auto *P = dyn_cast<ObjectFile>(F)) {
ObjectFiles.push_back(P);
} else if (auto *P = dyn_cast<ArchiveFile>(F)) {
ArchiveFiles.push_back(P);
} else if (auto *P = dyn_cast<BitcodeFile>(F)) {
BitcodeFiles.push_back(P);
} else {
ImportFiles.push_back(cast<ImportFile>(F));
}
for (SymbolBody *B : F->getSymbols())
if (B->isExternal())
if (auto EC = resolve(B))
return EC;
// If a object file contains .drectve section,
// read that and add files listed there.
StringRef S = F->getDirectives();
if (!S.empty())
if (auto EC = Driver->parseDirectives(S))
return EC;
}
return std::error_code();
}
bool SymbolTable::reportRemainingUndefines() {
bool Ret = false;
for (auto &I : Symtab) {
Symbol *Sym = I.second;
auto *Undef = dyn_cast<Undefined>(Sym->Body);
if (!Undef)
continue;
if (SymbolBody *Alias = Undef->getWeakAlias()) {
Sym->Body = Alias->getReplacement();
if (!isa<Defined>(Sym->Body)) {
// Aliases are yet another symbols pointed by other symbols
// that could also remain undefined.
llvm::errs() << "undefined symbol: " << Undef->getName() << "\n";
Ret = true;
}
continue;
}
llvm::errs() << "undefined symbol: " << Undef->getName() << "\n";
Ret = true;
}
return Ret;
}
// This function resolves conflicts if there's an existing symbol with
// the same name. Decisions are made based on symbol type.
std::error_code SymbolTable::resolve(SymbolBody *New) {
// Find an existing Symbol or create and insert a new one.
StringRef Name = New->getName();
Symbol *&Sym = Symtab[Name];
if (!Sym) {
Sym = new (Alloc) Symbol(New);
New->setBackref(Sym);
++Version;
return std::error_code();
}
New->setBackref(Sym);
// compare() returns -1, 0, or 1 if the lhs symbol is less preferable,
// equivalent (conflicting), or more preferable, respectively.
SymbolBody *Existing = Sym->Body;
int comp = Existing->compare(New);
if (comp < 0) {
Sym->Body = New;
++Version;
}
if (comp == 0) {
llvm::errs() << "duplicate symbol: " << Name << "\n";
return make_error_code(LLDError::DuplicateSymbols);
}
// If we have an Undefined symbol for a Lazy symbol, we need
// to read an archive member to replace the Lazy symbol with
// a Defined symbol.
if (isa<Undefined>(Existing) || isa<Undefined>(New))
if (auto *B = dyn_cast<Lazy>(Sym->Body))
return addMemberFile(B);
return std::error_code();
}
// Reads an archive member file pointed by a given symbol.
std::error_code SymbolTable::addMemberFile(Lazy *Body) {
auto FileOrErr = Body->getMember();
if (auto EC = FileOrErr.getError())
return EC;
std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
// getMember returns an empty buffer if the member was already
// read from the library.
if (!File)
return std::error_code();
if (Config->Verbose)
llvm::outs() << "Loaded " << File->getShortName() << " for "
<< Body->getName() << "\n";
addFile(std::move(File));
return std::error_code();
}
std::vector<Chunk *> SymbolTable::getChunks() {
std::vector<Chunk *> Res;
for (ObjectFile *File : ObjectFiles) {
std::vector<Chunk *> &V = File->getChunks();
Res.insert(Res.end(), V.begin(), V.end());
}
return Res;
}
Defined *SymbolTable::find(StringRef Name) {
auto It = Symtab.find(Name);
if (It == Symtab.end())
return nullptr;
if (auto *Def = dyn_cast<Defined>(It->second->Body))
return Def;
return nullptr;
}
std::error_code SymbolTable::resolveLazy(StringRef Name) {
auto It = Symtab.find(Name);
if (It == Symtab.end())
return std::error_code();
if (auto *B = dyn_cast<Lazy>(It->second->Body)) {
if (auto EC = addMemberFile(B))
return EC;
return run();
}
return std::error_code();
}
// Windows specific -- Link default entry point name.
ErrorOr<StringRef> SymbolTable::findDefaultEntry() {
// If it's DLL, the rule is easy.
if (Config->DLL) {
StringRef Sym = "_DllMainCRTStartup";
if (auto EC = resolve(new (Alloc) Undefined(Sym)))
return EC;
return Sym;
}
// User-defined main functions and their corresponding entry points.
static const char *Entries[][2] = {
{"main", "mainCRTStartup"},
{"wmain", "wmainCRTStartup"},
{"WinMain", "WinMainCRTStartup"},
{"wWinMain", "wWinMainCRTStartup"},
};
for (auto E : Entries) {
resolveLazy(E[1]);
if (find(E[1]))
return StringRef(E[1]);
if (!find(E[0]))
continue;
if (auto EC = resolve(new (Alloc) Undefined(E[1])))
return EC;
return StringRef(E[1]);
}
llvm::errs() << "entry point must be defined\n";
return make_error_code(LLDError::InvalidOption);
}
std::error_code SymbolTable::addUndefined(StringRef Name) {
return resolve(new (Alloc) Undefined(Name));
}
// Resolve To, and make From an alias to To.
std::error_code SymbolTable::rename(StringRef From, StringRef To) {
// If From is not undefined, do nothing.
// Otherwise, rename it to see if To can be resolved instead.
auto It = Symtab.find(From);
if (It == Symtab.end())
return std::error_code();
Symbol *Sym = It->second;
if (!isa<Undefined>(Sym->Body))
return std::error_code();
SymbolBody *Body = new (Alloc) Undefined(To);
if (auto EC = resolve(Body))
return EC;
Sym->Body = Body->getReplacement();
Body->setBackref(Sym);
++Version;
return std::error_code();
}
void SymbolTable::dump() {
for (auto &P : Symtab) {
Symbol *Ref = P.second;
if (auto *Body = dyn_cast<Defined>(Ref->Body))
llvm::dbgs() << Twine::utohexstr(Config->ImageBase + Body->getRVA())
<< " " << Body->getName() << "\n";
}
}
std::error_code SymbolTable::addCombinedLTOObject() {
if (BitcodeFiles.empty())
return std::error_code();
// Create an object file and add it to the symbol table by replacing any
// DefinedBitcode symbols with the definitions in the object file.
LTOCodeGenerator CG;
auto FileOrErr = createLTOObject(&CG);
if (auto EC = FileOrErr.getError())
return EC;
ObjectFile *Obj = FileOrErr.get();
// Skip the combined object file as the file is processed below
// rather than by run().
++FileIdx;
for (SymbolBody *Body : Obj->getSymbols()) {
if (!Body->isExternal())
continue;
// Find an existing Symbol. We should not see any new undefined symbols at
// this point.
StringRef Name = Body->getName();
Symbol *&Sym = Symtab[Name];
if (!Sym) {
if (!isa<Defined>(Body)) {
llvm::errs() << "LTO: undefined symbol: " << Name << '\n';
return make_error_code(LLDError::BrokenFile);
}
Sym = new (Alloc) Symbol(Body);
Body->setBackref(Sym);
continue;
}
Body->setBackref(Sym);
if (isa<DefinedBitcode>(Sym->Body)) {
// The symbol should now be defined.
if (!isa<Defined>(Body)) {
llvm::errs() << "LTO: undefined symbol: " << Name << '\n';
return make_error_code(LLDError::BrokenFile);
}
Sym->Body = Body;
} else {
int comp = Sym->Body->compare(Body);
if (comp < 0)
Sym->Body = Body;
if (comp == 0) {
llvm::errs() << "LTO: unexpected duplicate symbol: " << Name << "\n";
return make_error_code(LLDError::BrokenFile);
}
}
// We may see new references to runtime library symbols such as __chkstk
// here. These symbols must be wholly defined in non-bitcode files.
if (auto *B = dyn_cast<Lazy>(Sym->Body))
if (auto EC = addMemberFile(B))
return EC;
}
size_t NumBitcodeFiles = BitcodeFiles.size();
if (auto EC = run())
return EC;
if (BitcodeFiles.size() != NumBitcodeFiles) {
llvm::errs() << "LTO: late loaded symbol created new bitcode reference\n";
return make_error_code(LLDError::BrokenFile);
}
// New runtime library symbol references may have created undefined references.
if (reportRemainingUndefines())
return make_error_code(LLDError::BrokenFile);
return std::error_code();
}
// Combine and compile bitcode files and then return the result
// as a regular COFF object file.
ErrorOr<ObjectFile *> SymbolTable::createLTOObject(LTOCodeGenerator *CG) {
// All symbols referenced by non-bitcode objects must be preserved.
for (ObjectFile *File : ObjectFiles)
for (SymbolBody *Body : File->getSymbols())
if (auto *S = dyn_cast<DefinedBitcode>(Body->getReplacement()))
CG->addMustPreserveSymbol(S->getName());
// Likewise for bitcode symbols which we initially resolved to non-bitcode.
for (BitcodeFile *File : BitcodeFiles)
for (SymbolBody *Body : File->getSymbols())
if (isa<DefinedBitcode>(Body) &&
!isa<DefinedBitcode>(Body->getReplacement()))
CG->addMustPreserveSymbol(Body->getName());
// Likewise for other symbols that must be preserved.
for (StringRef Name : Config->GCRoots)
if (isa<DefinedBitcode>(Symtab[Name]->Body))
CG->addMustPreserveSymbol(Name);
CG->setModule(BitcodeFiles[0]->releaseModule());
for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I)
CG->addModule(BitcodeFiles[I]->getModule());
std::string ErrMsg;
LTOMB = CG->compile(false, false, false, ErrMsg); // take MB ownership
if (!LTOMB) {
llvm::errs() << ErrMsg << '\n';
return make_error_code(LLDError::BrokenFile);
}
auto *Obj = new ObjectFile(LTOMB->getMemBufferRef());
Files.emplace_back(Obj);
ObjectFiles.push_back(Obj);
if (auto EC = Obj->parse())
return EC;
return Obj;
}
} // namespace coff
} // namespace lld
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Xavier Leclercq
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.
*/
/*
Part of this file were copied from the Chart.js project (http://chartjs.org/)
and translated into C++.
The files of the Chart.js project have the following copyright and license.
Copyright (c) 2013-2016 Nick Downie
Released under the MIT license
https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
#include "wxchartgrid.h"
#include "wxchartutilities.h"
#include <wx/pen.h>
#include <sstream>
wxChartGrid::wxChartGrid(const wxPoint2DDouble &position,
const wxSize &size,
const wxVector<wxString> &labels,
wxDouble minValue,
wxDouble maxValue,
const wxChartGridOptions& options)
: m_options(options), m_position(position),
m_mapping(
size,
(options.GetXAxisOptions().GetLabelType() == wxCHARTAXISLABELTYPE_POINT ? labels.size() - 1: labels.size())
),
m_XAxis(new wxChartAxis(labels, options.GetXAxisOptions())),
m_YAxis(new wxChartAxis(options.GetYAxisOptions())),
m_needsFit(true)
{
wxDouble effectiveMinValue = minValue;
if (m_YAxis->GetOptions().GetStartValueMode() == wxCHARTAXISVALUEMODE_EXPLICIT)
{
effectiveMinValue = m_YAxis->GetOptions().GetStartValue();
}
wxDouble effectiveMaxValue = maxValue;
if (m_YAxis->GetOptions().GetEndValueMode() == wxCHARTAXISVALUEMODE_EXPLICIT)
{
effectiveMaxValue = m_YAxis->GetOptions().GetEndValue();
}
wxDouble graphMinValue;
wxDouble graphMaxValue;
wxDouble valueRange = 0;
wxChartUtilities::CalculateGridRange(effectiveMinValue, effectiveMaxValue,
graphMinValue, graphMaxValue, valueRange, m_steps, m_stepValue);
m_mapping.SetMinValue(graphMinValue);
m_mapping.SetMaxValue(graphMaxValue);
wxVector<wxChartLabel> yLabels;
BuildYLabels(m_mapping.GetMinValue(), m_steps, m_stepValue, yLabels);
m_YAxis->SetLabels(yLabels);
}
bool wxChartGrid::HitTest(const wxPoint &point) const
{
return false;
}
wxPoint2DDouble wxChartGrid::GetTooltipPosition() const
{
return wxPoint2DDouble(0, 0);
}
void wxChartGrid::Draw(wxGraphicsContext &gc)
{
Fit(gc);
wxDouble yLabelGap = (m_mapping.GetStartPoint().m_y - m_mapping.GetEndPoint().m_y) / m_steps;
wxDouble xStart = m_mapping.GetLeftPadding();
if (m_options.ShowHorizontalLines())
{
for (size_t i = 1; i < m_YAxis->GetNumberOfTickMarks(); ++i)
{
wxDouble yLabelCenter = m_mapping.GetStartPoint().m_y - (yLabelGap * i);
wxDouble linePositionY = yLabelCenter;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(xStart, linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth() - m_mapping.GetRightPadding() + m_XAxis->GetOptions().GetOverhang(), linePositionY);
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
}
}
if (m_options.ShowVerticalLines())
{
for (size_t i = 1; i < m_XAxis->GetNumberOfTickMarks(); ++i)
{
wxDouble linePosition = m_XAxis->GetTickMarkPosition(i).m_x;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetStartPoint().m_y);
path.AddLineToPoint(linePosition, m_mapping.GetEndPoint().m_y - m_YAxis->GetOptions().GetOverhang());
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
}
}
m_XAxis->Draw(gc);
m_YAxis->Draw(gc);
}
void wxChartGrid::Resize(const wxSize &size)
{
m_mapping.SetSize(size);
m_needsFit = true;
}
const wxChartGridMapping& wxChartGrid::GetMapping() const
{
return m_mapping;
}
void wxChartGrid::Fit(wxGraphicsContext &gc)
{
if (!m_needsFit)
{
return;
}
wxDouble startPoint = m_mapping.GetSize().GetHeight() - (m_YAxis->GetOptions().GetFontOptions().GetSize() + 15) - 5; // -5 to pad labels
wxDouble endPoint = m_YAxis->GetOptions().GetFontOptions().GetSize();
// Apply padding settings to the start and end point.
//this.startPoint += this.padding;
//this.endPoint -= this.padding;
m_YAxis->UpdateLabelSizes(gc);
m_XAxis->UpdateLabelSizes(gc);
wxDouble leftPadding = 0;
wxDouble rightPadding = 0;
CalculatePadding(*m_XAxis, *m_YAxis, leftPadding, rightPadding);
if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
m_XAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(m_mapping.GetSize().GetWidth() - rightPadding, startPoint));
m_YAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(leftPadding, endPoint));
}
else if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
m_XAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(leftPadding, endPoint));
m_YAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(m_mapping.GetSize().GetWidth() - rightPadding, startPoint));
}
m_XAxis->UpdateLabelPositions();
m_YAxis->UpdateLabelPositions();
m_mapping.Fit(leftPadding, rightPadding, wxPoint2DDouble(0, startPoint), wxPoint2DDouble(0, endPoint));
m_needsFit = false;
}
void wxChartGrid::BuildYLabels(wxDouble minValue,
size_t steps,
wxDouble stepValue,
wxVector<wxChartLabel> &labels)
{
size_t stepDecimalPlaces = wxChartUtilities::GetDecimalPlaces();
for (size_t i = 0; i <= steps; ++i)
{
wxDouble value = minValue + (i * stepValue);//.toFixed(stepDecimalPlaces);
std::stringstream valueStr;
valueStr << value;
labels.push_back(wxChartLabel(valueStr.str()));
}
}
void wxChartGrid::CalculatePadding(const wxChartAxis &xAxis,
const wxChartAxis &yAxis,
wxDouble &left,
wxDouble &right)
{
if (xAxis.GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
// Either the first x label or any of the y labels can be the widest
// so they are all taken into account to compute the left padding
left = yAxis.GetLabelMaxWidth();
if ((xAxis.GetLabels().size() > 0) && ((xAxis.GetLabels().front().GetSize().GetWidth() / 2) > left))
{
left = (xAxis.GetLabels().front().GetSize().GetWidth() / 2);
}
right = 0;
if (xAxis.GetLabels().size() > 0)
{
right = (xAxis.GetLabels().back().GetSize().GetWidth() / 2);
}
}
else if (xAxis.GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
// Either the first y label or any of the x labels can be the widest
// so they are all taken into account to compute the left padding
left = xAxis.GetLabelMaxWidth();
if ((yAxis.GetLabels().size() > 0) && ((yAxis.GetLabels().front().GetSize().GetWidth() / 2) > left))
{
left = (yAxis.GetLabels().front().GetSize().GetWidth() / 2);
}
right = 0;
if (yAxis.GetLabels().size() > 0)
{
right = (yAxis.GetLabels().back().GetSize().GetWidth() / 2);
}
}
}
<commit_msg>Fixed grid lines for bar charts<commit_after>/*
Copyright (c) 2016 Xavier Leclercq
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.
*/
/*
Part of this file were copied from the Chart.js project (http://chartjs.org/)
and translated into C++.
The files of the Chart.js project have the following copyright and license.
Copyright (c) 2013-2016 Nick Downie
Released under the MIT license
https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
#include "wxchartgrid.h"
#include "wxchartutilities.h"
#include <wx/pen.h>
#include <sstream>
wxChartGrid::wxChartGrid(const wxPoint2DDouble &position,
const wxSize &size,
const wxVector<wxString> &labels,
wxDouble minValue,
wxDouble maxValue,
const wxChartGridOptions& options)
: m_options(options), m_position(position),
m_mapping(
size,
(options.GetXAxisOptions().GetLabelType() == wxCHARTAXISLABELTYPE_POINT ? labels.size() - 1: labels.size())
),
m_XAxis(new wxChartAxis(labels, options.GetXAxisOptions())),
m_YAxis(new wxChartAxis(options.GetYAxisOptions())),
m_needsFit(true)
{
wxDouble effectiveMinValue = minValue;
if (m_YAxis->GetOptions().GetStartValueMode() == wxCHARTAXISVALUEMODE_EXPLICIT)
{
effectiveMinValue = m_YAxis->GetOptions().GetStartValue();
}
wxDouble effectiveMaxValue = maxValue;
if (m_YAxis->GetOptions().GetEndValueMode() == wxCHARTAXISVALUEMODE_EXPLICIT)
{
effectiveMaxValue = m_YAxis->GetOptions().GetEndValue();
}
wxDouble graphMinValue;
wxDouble graphMaxValue;
wxDouble valueRange = 0;
wxChartUtilities::CalculateGridRange(effectiveMinValue, effectiveMaxValue,
graphMinValue, graphMaxValue, valueRange, m_steps, m_stepValue);
m_mapping.SetMinValue(graphMinValue);
m_mapping.SetMaxValue(graphMaxValue);
wxVector<wxChartLabel> yLabels;
BuildYLabels(m_mapping.GetMinValue(), m_steps, m_stepValue, yLabels);
m_YAxis->SetLabels(yLabels);
}
bool wxChartGrid::HitTest(const wxPoint &point) const
{
return false;
}
wxPoint2DDouble wxChartGrid::GetTooltipPosition() const
{
return wxPoint2DDouble(0, 0);
}
void wxChartGrid::Draw(wxGraphicsContext &gc)
{
Fit(gc);
if (m_options.ShowHorizontalLines())
{
const wxChartAxis* verticalAxis = 0;
if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
verticalAxis = m_XAxis.get();
}
else if (m_YAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
verticalAxis = m_YAxis.get();
}
for (size_t i = 1; i < verticalAxis->GetNumberOfTickMarks(); ++i)
{
wxDouble yLabelCenter = verticalAxis->GetTickMarkPosition(i).m_y;
wxDouble linePositionY = yLabelCenter;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(m_mapping.GetLeftPadding(), linePositionY);
path.AddLineToPoint(m_mapping.GetSize().GetWidth() - m_mapping.GetRightPadding() + verticalAxis->GetOptions().GetOverhang(), linePositionY);
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
}
}
if (m_options.ShowVerticalLines())
{
const wxChartAxis* horizontalAxis = 0;
if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
horizontalAxis = m_XAxis.get();
}
else if (m_YAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
horizontalAxis = m_YAxis.get();
}
for (size_t i = 1; i < horizontalAxis->GetNumberOfTickMarks(); ++i)
{
wxDouble linePosition = horizontalAxis->GetTickMarkPosition(i).m_x;
wxGraphicsPath path = gc.CreatePath();
path.MoveToPoint(linePosition, m_mapping.GetStartPoint().m_y);
path.AddLineToPoint(linePosition, m_mapping.GetEndPoint().m_y - horizontalAxis->GetOptions().GetOverhang());
wxPen pen1(m_options.GetGridLineColor(), m_options.GetGridLineWidth());
gc.SetPen(pen1);
gc.StrokePath(path);
}
}
m_XAxis->Draw(gc);
m_YAxis->Draw(gc);
}
void wxChartGrid::Resize(const wxSize &size)
{
m_mapping.SetSize(size);
m_needsFit = true;
}
const wxChartGridMapping& wxChartGrid::GetMapping() const
{
return m_mapping;
}
void wxChartGrid::Fit(wxGraphicsContext &gc)
{
if (!m_needsFit)
{
return;
}
wxDouble startPoint = m_mapping.GetSize().GetHeight() - (m_YAxis->GetOptions().GetFontOptions().GetSize() + 15) - 5; // -5 to pad labels
wxDouble endPoint = m_YAxis->GetOptions().GetFontOptions().GetSize();
// Apply padding settings to the start and end point.
//this.startPoint += this.padding;
//this.endPoint -= this.padding;
m_YAxis->UpdateLabelSizes(gc);
m_XAxis->UpdateLabelSizes(gc);
wxDouble leftPadding = 0;
wxDouble rightPadding = 0;
CalculatePadding(*m_XAxis, *m_YAxis, leftPadding, rightPadding);
if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
m_XAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(m_mapping.GetSize().GetWidth() - rightPadding, startPoint));
m_YAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(leftPadding, endPoint));
}
else if (m_XAxis->GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
m_XAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(leftPadding, endPoint));
m_YAxis->Fit(wxPoint2DDouble(leftPadding, startPoint), wxPoint2DDouble(m_mapping.GetSize().GetWidth() - rightPadding, startPoint));
}
m_XAxis->UpdateLabelPositions();
m_YAxis->UpdateLabelPositions();
m_mapping.Fit(leftPadding, rightPadding, wxPoint2DDouble(0, startPoint), wxPoint2DDouble(0, endPoint));
m_needsFit = false;
}
void wxChartGrid::BuildYLabels(wxDouble minValue,
size_t steps,
wxDouble stepValue,
wxVector<wxChartLabel> &labels)
{
size_t stepDecimalPlaces = wxChartUtilities::GetDecimalPlaces();
for (size_t i = 0; i <= steps; ++i)
{
wxDouble value = minValue + (i * stepValue);//.toFixed(stepDecimalPlaces);
std::stringstream valueStr;
valueStr << value;
labels.push_back(wxChartLabel(valueStr.str()));
}
}
void wxChartGrid::CalculatePadding(const wxChartAxis &xAxis,
const wxChartAxis &yAxis,
wxDouble &left,
wxDouble &right)
{
if (xAxis.GetOptions().GetPosition() == wxCHARTAXISPOSITION_BOTTOM)
{
// Either the first x label or any of the y labels can be the widest
// so they are all taken into account to compute the left padding
left = yAxis.GetLabelMaxWidth();
if ((xAxis.GetLabels().size() > 0) && ((xAxis.GetLabels().front().GetSize().GetWidth() / 2) > left))
{
left = (xAxis.GetLabels().front().GetSize().GetWidth() / 2);
}
right = 0;
if (xAxis.GetLabels().size() > 0)
{
right = (xAxis.GetLabels().back().GetSize().GetWidth() / 2);
}
}
else if (xAxis.GetOptions().GetPosition() == wxCHARTAXISPOSITION_LEFT)
{
// Either the first y label or any of the x labels can be the widest
// so they are all taken into account to compute the left padding
left = xAxis.GetLabelMaxWidth();
if ((yAxis.GetLabels().size() > 0) && ((yAxis.GetLabels().front().GetSize().GetWidth() / 2) > left))
{
left = (yAxis.GetLabels().front().GetSize().GetWidth() / 2);
}
right = 0;
if (yAxis.GetLabels().size() > 0)
{
right = (yAxis.GetLabels().back().GetSize().GetWidth() / 2);
}
}
}
<|endoftext|> |
<commit_before>//
// Created by david on 2019-03-09.
//
#include <algorithms/class_algorithm_status.h>
#include <config/nmspc_settings.h>
#include <h5pp/h5pp.h>
#include <regex>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
using Scalar = std::complex<double>;
namespace tools::finite::io::h5dset{
void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> & save_log, const h5pp::File &h5ppFile, const std::vector<std::string> & links){
if(save_log.empty()){
try {
for(auto &link : links) {
if(h5ppFile.linkExists(link)) {
auto step = h5ppFile.readAttribute<uint64_t>("step", link);
auto iter = h5ppFile.readAttribute<uint64_t>("iteration", link);
save_log[link] = std::make_pair(iter, step);
}
}
}catch(const std::exception & ex){
tools::log->warn("Could not bootstrap save_log: {}", ex.what());
}
}
}
}
int tools::finite::io::h5dset::decide_layout(std::string_view prefix_path) {
return H5D_CHUNKED; // Let everything be chunked a while. When resuming, rewriting into checkpoint/iter_? can lead datasets of different sizes
std::string str(prefix_path);
std::regex rx(R"(checkpoint/iter_[0-9])"); // Declare the regex with a raw string literal
std::smatch m;
if(regex_search(str, m, rx)) return H5D_CONTIGUOUS;
else
return H5D_CHUNKED;
}
void tools::finite::io::h5dset::save_state(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
const class_state_finite &state, const class_algorithm_status &status) {
if(storage_level == StorageLevel::NONE) return;
tools::common::profile::get_default_prof()["t_hdf"]->tic();
// Checks if the current entry has already been saved
// If it is empty because we are resuming, check if there is a log entry on file already
static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;
bootstrap_save_log(save_log,h5ppFile,{state_prefix + "/schmidt_midchain", state_prefix + "/mps"});
auto save_point = std::make_pair(status.iter, status.step);
auto layout = static_cast<H5D_layout_t>(decide_layout(state_prefix));
std::string dsetName = state_prefix + "/schmidt_midchain";
if(save_log[dsetName] != save_point) {
/*! Writes down the center "Lambda" bond matrix (singular values). */
tools::log->trace("Storing [{: ^6}]: mid bond matrix", enum2str(storage_level));
h5ppFile.writeDataset(state.midchain_bond(), dsetName, layout);
h5ppFile.writeAttribute(state.get_truncation_error_midchain(), "truncation_error", dsetName);
h5ppFile.writeAttribute((state.get_length<long>() - 1) / 2, "position", dsetName);
h5ppFile.writeAttribute(status.iter, "iteration", dsetName);
h5ppFile.writeAttribute(status.step, "step", dsetName);
h5ppFile.writeAttribute(status.chi_lim, "chi_lim", dsetName);
h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", dsetName);
save_log[dsetName] = save_point;
}
if(storage_level < StorageLevel::NORMAL) {
tools::common::profile::get_default_prof()["t_hdf"]->toc();
return;
}
std::string mps_prefix = state_prefix + "/mps";
if(save_log[mps_prefix] != save_point) {
tools::log->trace("Storing [{: ^6}]: bond matrices", enum2str(storage_level));
// There should be one more sites+1 number of L's, because there is also a center bond
// However L_i always belongs M_i. Stick to this rule!
// This means that some M_i has two bonds, one L_i to the left, and one L_C to the right.
for(const auto & mps : state.mps_sites) {
dsetName = fmt::format("{}/L_{}", mps_prefix, mps->get_position<long>());
if(save_log[dsetName] == save_point) continue;
h5ppFile.writeDataset(mps->get_L(), dsetName, layout);
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_L().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_truncation_error(), "truncation_error", dsetName);
if(mps->isCenter()) {
dsetName = mps_prefix + "/L_C";
h5ppFile.writeDataset(mps->get_LC(), dsetName, layout);
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_LC().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_truncation_error_LC(), "truncation_error", dsetName);
}
save_log[dsetName] = save_point;
}
h5ppFile.writeAttribute(state.get_length(), "model_size", mps_prefix);
h5ppFile.writeAttribute(state.get_position<long>(), "position", mps_prefix);
h5ppFile.writeAttribute(state.get_truncation_errors(), "truncation_errors", mps_prefix);
h5ppFile.writeAttribute(state.get_labels(), "labels", mps_prefix);
h5ppFile.writeAttribute(status.iter, "iteration", mps_prefix);
h5ppFile.writeAttribute(status.step, "step", mps_prefix);
}
/*! Writes down the full MPS in "L-G-L-G- LC -G-L-G-L" notation. */
if(storage_level < StorageLevel::FULL) {
tools::common::profile::get_default_prof()["t_hdf"]->toc();
save_log[mps_prefix] = save_point;
return;
}
if(save_log[mps_prefix] != save_point) {
tools::log->trace("Storing [{: ^6}]: mps tensors", enum2str(storage_level));
for(const auto & mps : state.mps_sites){
dsetName = fmt::format("{}/M_{}", mps_prefix, mps->get_position<long>());
if(save_log[dsetName] == save_point) continue;
h5ppFile.writeDataset(mps->get_M_bare(), dsetName, layout); // Important to write bare matrices!!
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_M_bare().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_label(), "label", dsetName);
h5ppFile.writeAttribute(mps->get_unique_id(), "unique_id", dsetName);
save_log[dsetName] = save_point;
}
save_log[mps_prefix] = save_point;
}
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
/*! Write all the MPO's with site info in attributes */
void tools::finite::io::h5dset::save_model(h5pp::File &h5ppFile, const std::string &model_prefix, const StorageLevel &storage_level,
const class_model_finite &model) {
if(storage_level < StorageLevel::FULL) return;
// We do not expect the MPO's to change. Therefore if they exist, there is nothing else to do here
if(h5ppFile.linkExists(model_prefix)) return tools::log->trace("The MPO's have already been written to [{}]", model_prefix);
tools::log->trace("Storing [{: ^6}]: mpo tensors", enum2str(storage_level));
tools::common::profile::get_default_prof()["t_hdf"]->tic();
for(size_t pos = 0; pos < model.get_length(); pos++) { model.get_mpo(pos).save_mpo(h5ppFile, model_prefix); }
h5ppFile.writeAttribute(settings::model::model_size, "model_size", model_prefix);
h5ppFile.writeAttribute(enum2str(settings::model::model_type), "model_type", model_prefix);
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
/*! Write down measurements that can't fit in a table */
void tools::finite::io::h5dset::save_entgm(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
const class_state_finite &state, const class_algorithm_status &status) {
if(storage_level < StorageLevel::NORMAL) return;
state.do_all_measurements();
tools::common::profile::get_default_prof()["t_hdf"]->tic();
tools::log->trace("Storing [{: ^6}]: bond dimensions", enum2str(storage_level));
h5ppFile.writeDataset(tools::finite::measure::bond_dimensions(state), state_prefix + "/bond_dimensions");
h5ppFile.writeAttribute(status.chi_lim, "chi_lim", state_prefix + "/bond_dimensions");
h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", state_prefix + "/bond_dimensions");
tools::log->trace("Storing [{: ^6}]: entanglement entropies", enum2str(storage_level));
h5ppFile.writeDataset(tools::finite::measure::entanglement_entropies(state), state_prefix + "/entanglement_entropies");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 2), state_prefix + "/renyi_2");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 3), state_prefix + "/renyi_3");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 4), state_prefix + "/renyi_4");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 100), state_prefix + "/renyi_100");
tools::log->trace("Storing [{: ^6}]: truncation errors", enum2str(storage_level));
h5ppFile.writeDataset(state.get_truncation_errors(), state_prefix + "/truncation_errors");
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
<commit_msg>Introduce SAVEPOINT and CHECKPOINT storage reasons<commit_after>//
// Created by david on 2019-03-09.
//
#include <algorithms/class_algorithm_status.h>
#include <config/nmspc_settings.h>
#include <h5pp/h5pp.h>
#include <regex>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
using Scalar = std::complex<double>;
namespace tools::finite::io::h5dset{
void bootstrap_save_log(std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> & save_log, const h5pp::File &h5ppFile, const std::vector<std::string> & links){
if(save_log.empty()){
try {
for(auto &link : links) {
if(h5ppFile.linkExists(link)) {
auto step = h5ppFile.readAttribute<uint64_t>("step", link);
auto iter = h5ppFile.readAttribute<uint64_t>("iteration", link);
save_log[link] = std::make_pair(iter, step);
}
}
}catch(const std::exception & ex){
tools::log->warn("Could not bootstrap save_log: {}", ex.what());
}
}
}
}
int tools::finite::io::h5dset::decide_layout(std::string_view prefix_path) {
return H5D_CHUNKED; // Let everything be chunked a while. When resuming, rewriting into savepoint/iter_? can lead datasets of different sizes
std::string str(prefix_path);
std::regex rx(R"(savepoint/iter_[0-9])"); // Declare the regex with a raw string literal
std::smatch m;
if(regex_search(str, m, rx)) return H5D_CONTIGUOUS;
else
return H5D_CHUNKED;
}
void tools::finite::io::h5dset::save_state(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
const class_state_finite &state, const class_algorithm_status &status) {
if(storage_level == StorageLevel::NONE) return;
tools::common::profile::get_default_prof()["t_hdf"]->tic();
// Checks if the current entry has already been saved
// If it is empty because we are resuming, check if there is a log entry on file already
static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> save_log;
bootstrap_save_log(save_log,h5ppFile,{state_prefix + "/schmidt_midchain", state_prefix + "/mps"});
auto save_point = std::make_pair(status.iter, status.step);
auto layout = static_cast<H5D_layout_t>(decide_layout(state_prefix));
std::string dsetName = state_prefix + "/schmidt_midchain";
if(save_log[dsetName] != save_point) {
/*! Writes down the center "Lambda" bond matrix (singular values). */
tools::log->trace("Storing [{: ^6}]: mid bond matrix", enum2str(storage_level));
h5ppFile.writeDataset(state.midchain_bond(), dsetName, layout);
h5ppFile.writeAttribute(state.get_truncation_error_midchain(), "truncation_error", dsetName);
h5ppFile.writeAttribute((state.get_length<long>() - 1) / 2, "position", dsetName);
h5ppFile.writeAttribute(status.iter, "iteration", dsetName);
h5ppFile.writeAttribute(status.step, "step", dsetName);
h5ppFile.writeAttribute(status.chi_lim, "chi_lim", dsetName);
h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", dsetName);
save_log[dsetName] = save_point;
}
if(storage_level < StorageLevel::NORMAL) {
tools::common::profile::get_default_prof()["t_hdf"]->toc();
return;
}
std::string mps_prefix = state_prefix + "/mps";
if(save_log[mps_prefix] != save_point) {
tools::log->trace("Storing [{: ^6}]: bond matrices", enum2str(storage_level));
// There should be one more sites+1 number of L's, because there is also a center bond
// However L_i always belongs M_i. Stick to this rule!
// This means that some M_i has two bonds, one L_i to the left, and one L_C to the right.
for(const auto & mps : state.mps_sites) {
dsetName = fmt::format("{}/L_{}", mps_prefix, mps->get_position<long>());
if(save_log[dsetName] == save_point) continue;
h5ppFile.writeDataset(mps->get_L(), dsetName, layout);
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_L().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_truncation_error(), "truncation_error", dsetName);
if(mps->isCenter()) {
dsetName = mps_prefix + "/L_C";
h5ppFile.writeDataset(mps->get_LC(), dsetName, layout);
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_LC().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_truncation_error_LC(), "truncation_error", dsetName);
}
save_log[dsetName] = save_point;
}
h5ppFile.writeAttribute(state.get_length(), "model_size", mps_prefix);
h5ppFile.writeAttribute(state.get_position<long>(), "position", mps_prefix);
h5ppFile.writeAttribute(state.get_truncation_errors(), "truncation_errors", mps_prefix);
h5ppFile.writeAttribute(state.get_labels(), "labels", mps_prefix);
h5ppFile.writeAttribute(status.iter, "iteration", mps_prefix);
h5ppFile.writeAttribute(status.step, "step", mps_prefix);
}
/*! Writes down the full MPS in "L-G-L-G- LC -G-L-G-L" notation. */
if(storage_level < StorageLevel::FULL) {
tools::common::profile::get_default_prof()["t_hdf"]->toc();
save_log[mps_prefix] = save_point;
return;
}
if(save_log[mps_prefix] != save_point) {
tools::log->trace("Storing [{: ^6}]: mps tensors", enum2str(storage_level));
for(const auto & mps : state.mps_sites){
dsetName = fmt::format("{}/M_{}", mps_prefix, mps->get_position<long>());
if(save_log[dsetName] == save_point) continue;
h5ppFile.writeDataset(mps->get_M_bare(), dsetName, layout); // Important to write bare matrices!!
h5ppFile.writeAttribute(mps->get_position<long>(), "position", dsetName);
h5ppFile.writeAttribute(mps->get_M_bare().dimensions(), "dimensions", dsetName);
h5ppFile.writeAttribute(mps->get_label(), "label", dsetName);
h5ppFile.writeAttribute(mps->get_unique_id(), "unique_id", dsetName);
save_log[dsetName] = save_point;
}
save_log[mps_prefix] = save_point;
}
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
/*! Write all the MPO's with site info in attributes */
void tools::finite::io::h5dset::save_model(h5pp::File &h5ppFile, const std::string &model_prefix, const StorageLevel &storage_level,
const class_model_finite &model) {
if(storage_level < StorageLevel::FULL) return;
// We do not expect the MPO's to change. Therefore if they exist, there is nothing else to do here
if(h5ppFile.linkExists(model_prefix)) return tools::log->trace("The MPO's have already been written to [{}]", model_prefix);
tools::log->trace("Storing [{: ^6}]: mpo tensors", enum2str(storage_level));
tools::common::profile::get_default_prof()["t_hdf"]->tic();
for(size_t pos = 0; pos < model.get_length(); pos++) { model.get_mpo(pos).save_mpo(h5ppFile, model_prefix); }
h5ppFile.writeAttribute(settings::model::model_size, "model_size", model_prefix);
h5ppFile.writeAttribute(enum2str(settings::model::model_type), "model_type", model_prefix);
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
/*! Write down measurements that can't fit in a table */
void tools::finite::io::h5dset::save_entgm(h5pp::File &h5ppFile, const std::string &state_prefix, const StorageLevel &storage_level,
const class_state_finite &state, const class_algorithm_status &status) {
if(storage_level < StorageLevel::NORMAL) return;
state.do_all_measurements();
tools::common::profile::get_default_prof()["t_hdf"]->tic();
tools::log->trace("Storing [{: ^6}]: bond dimensions", enum2str(storage_level));
h5ppFile.writeDataset(tools::finite::measure::bond_dimensions(state), state_prefix + "/bond_dimensions");
h5ppFile.writeAttribute(status.chi_lim, "chi_lim", state_prefix + "/bond_dimensions");
h5ppFile.writeAttribute(status.chi_lim_max, "chi_lim_max", state_prefix + "/bond_dimensions");
tools::log->trace("Storing [{: ^6}]: entanglement entropies", enum2str(storage_level));
h5ppFile.writeDataset(tools::finite::measure::entanglement_entropies(state), state_prefix + "/entanglement_entropies");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 2), state_prefix + "/renyi_2");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 3), state_prefix + "/renyi_3");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 4), state_prefix + "/renyi_4");
h5ppFile.writeDataset(tools::finite::measure::renyi_entropies(state, 100), state_prefix + "/renyi_100");
tools::log->trace("Storing [{: ^6}]: truncation errors", enum2str(storage_level));
h5ppFile.writeDataset(state.get_truncation_errors(), state_prefix + "/truncation_errors");
tools::common::profile::get_default_prof()["t_hdf"]->toc();
}
<|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011-2012
* The PPCoin Developers 2013
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & wxMODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
void MainFrameRepaint()
{
if(clientmodel)
QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}
void AddressBookRepaint()
{
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("PPCoin");
app.setOrganizationDomain("ppcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("PPCoin-Qt-testnet");
else
app.setApplicationName("PPCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale ("en_US") from command line or system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
BitcoinGUI window;
guiref = &window;
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
clientmodel = &clientModel;
WalletModel walletModel(pwalletMain, &optionsModel);
walletmodel = &walletModel;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
clientmodel = 0;
walletmodel = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Update bitcoin.cpp<commit_after>/*
* W.J. van der Laan 2011-2012
* The PPCoin Developers 2013
* The Platinum Developers 2013-2014
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static WalletModel *walletmodel;
static ClientModel *clientmodel;
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & wxMODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
void MainFrameRepaint()
{
if(clientmodel)
QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection);
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection);
}
void AddressBookRepaint()
{
if(walletmodel)
QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. PPCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifdef WIN32
#define strncasecmp strnicmp
#endif
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("PPCoin");
app.setOrganizationDomain("ppcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("PPCoin-Qt-testnet");
else
app.setApplicationName("PPCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale ("en_US") from command line or system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
BitcoinGUI window;
guiref = &window;
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
clientmodel = &clientModel;
WalletModel walletModel(pwalletMain, &optionsModel);
walletmodel = &walletModel;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) >= 7 && strncasecmp(argv[i], "ppcoin:", 7) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
clientmodel = 0;
walletmodel = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: PColumn.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2003-12-16 12:26:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
namespace connectivity
{
namespace parse
{
class OParseColumn;
typedef sdbcx::OColumn OParseColumn_BASE;
typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;
class OParseColumn : public OParseColumn_BASE,
public OParseColumn_PROP
{
::rtl::OUString m_aRealName;
::rtl::OUString m_aTableName;
sal_Bool m_bFunction;
sal_Bool m_bDbasePrecisionChanged;
protected:
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual ~OParseColumn();
public:
OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
OParseColumn(const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase);
virtual void construct();
void setRealName(const ::rtl::OUString& _rName) { m_aRealName = _rName; }
void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
void setFunction(sal_Bool _bFunction) { m_bFunction = _bFunction; }
void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }
::rtl::OUString getRealName() const { return m_aRealName; }
::rtl::OUString getTableName() const { return m_aTableName; }
sal_Bool getFunction() const { return m_bFunction; }
sal_Bool getDbasePrecisionChanged() const { return m_bDbasePrecisionChanged; }
};
class OOrderColumn;
typedef sdbcx::OColumn OOrderColumn_BASE;
typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;
class OOrderColumn : public OOrderColumn_BASE,
public OOrderColumn_PROP
{
sal_Bool m_bAscending;
sal_Bool m_bOrder;
protected:
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual ~OOrderColumn();
public:
OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
OOrderColumn(const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
,sal_Bool _bAscending);
virtual void construct();
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
};
}
}
#endif //_CONNECTIVITY_PCOLUMN_HXX_
<commit_msg>INTEGRATION: CWS dba16 (1.10.66); FILE MERGED 2004/10/11 11:38:54 oj 1.10.66.1: #i30220# enable having, group by for queries<commit_after>/*************************************************************************
*
* $RCSfile: PColumn.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2004-10-22 08:40:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_PCOLUMN_HXX_
#define _CONNECTIVITY_PCOLUMN_HXX_
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
namespace connectivity
{
namespace parse
{
class OParseColumn;
typedef sdbcx::OColumn OParseColumn_BASE;
typedef ::comphelper::OIdPropertyArrayUsageHelper<OParseColumn> OParseColumn_PROP;
class OParseColumn : public OParseColumn_BASE,
public OParseColumn_PROP
{
::rtl::OUString m_aRealName;
::rtl::OUString m_aTableName;
sal_Bool m_bFunction;
sal_Bool m_bDbasePrecisionChanged;
sal_Bool m_bAggregateFunction;
protected:
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual ~OParseColumn();
public:
OParseColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase);
OParseColumn(const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase);
virtual void construct();
void setRealName(const ::rtl::OUString& _rName) { m_aRealName = _rName; }
void setTableName(const ::rtl::OUString& _rName) { m_aTableName = _rName; }
void setFunction(sal_Bool _bFunction) { m_bFunction = _bFunction; }
void setAggregateFunction(sal_Bool _bFunction) { m_bAggregateFunction = _bFunction; }
void setDbasePrecisionChanged(sal_Bool _bDbasePrecisionChanged) { m_bDbasePrecisionChanged = _bDbasePrecisionChanged; }
::rtl::OUString getRealName() const { return m_aRealName; }
::rtl::OUString getTableName() const { return m_aTableName; }
sal_Bool getFunction() const { return m_bFunction; }
sal_Bool getDbasePrecisionChanged() const { return m_bDbasePrecisionChanged; }
};
class OOrderColumn;
typedef sdbcx::OColumn OOrderColumn_BASE;
typedef ::comphelper::OIdPropertyArrayUsageHelper<OOrderColumn> OOrderColumn_PROP;
class OOrderColumn : public OOrderColumn_BASE,
public OOrderColumn_PROP
{
sal_Bool m_bAscending;
sal_Bool m_bOrder;
protected:
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual ~OOrderColumn();
public:
OOrderColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xColumn,sal_Bool _bCase,sal_Bool _bAscending);
OOrderColumn(const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
,sal_Bool _bAscending);
virtual void construct();
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
};
}
}
#endif //_CONNECTIVITY_PCOLUMN_HXX_
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName NFCEctypeModule.cpp
// @Author LvSheng.Huang
// @Date 2012-12-15
// @Module NFCEctypeModule
//
// -------------------------------------------------------------------------
#include "NFCEctypeModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include "NFComm/Define/NFStringInfo.h"
bool NFCEctypeModule::Init()
{
return true;
}
bool NFCEctypeModule::Shut()
{
return true;
}
bool NFCEctypeModule::Execute(const float fLasFrametime, const float fStartedTime)
{
return true;
}
bool NFCEctypeModule::AfterInit()
{
m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
m_pSceneProcessModule = dynamic_cast<NFISceneProcessModule*>(pPluginManager->FindModule("NFCSceneProcessModule"));
m_pAwardModule = dynamic_cast<NFIAwardPackModule*>(pPluginManager->FindModule("NFCAwardPackModule"));
m_pPackModule = dynamic_cast<NFIPackModule*>(pPluginManager->FindModule("NFCPackModule"));
m_pPropertyModule = dynamic_cast<NFIPropertyModule*>(pPluginManager->FindModule("NFCPropertyModule"));
m_pLevelModule = dynamic_cast<NFILevelModule*>(pPluginManager->FindModule("NFCLevelModule"));
m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule"));
m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule"));
assert(NULL != m_pLevelModule);
assert(NULL != m_pPropertyModule);
assert(NULL != m_pPackModule);
assert(NULL != m_pAwardModule);
assert(NULL != m_pEventProcessModule);
assert(NULL != m_pElementInfoModule);
assert(NULL != m_pKernelModule);
assert(NULL != m_pSceneProcessModule);
assert(NULL != m_pLogModule);
assert(NULL != m_pLogicClassModule);
m_pEventProcessModule->AddClassCallBack("Player", this, &NFCEctypeModule::OnObjectClassEvent);
return true;
}
bool NFCEctypeModule::CanEntryCloneScene(const NFIDENTID self, const int nContainerID)
{
std::string strSceneID = boost::lexical_cast<std::string>(nContainerID);
//ûҵжǷǵһIsFirstCloneScene
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
if (nLevel < m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneLevelLimit"))
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "Level limit for scene:" + strSceneID, nLevel, __FUNCTION__, __LINE__);
return false;
}
//ĺֱӿǷ
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (!pRecord.get())
{
return false;
}
NFCDataList valNormalResult;
pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
if (valNormalResult.GetCount() <= 0)
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "no this scene in record", nContainerID, __FUNCTION__, __LINE__);
return false;
}
return true;
}
int NFCEctypeModule::OnObjectClassEvent(const NFIDENTID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
if (strClassName == "Player")
{
if (COE_CREATE_BEFORE_EFFECT == eClassEvent)
{
int nOnlineCount = m_pKernelModule->GetPropertyInt(self, "OnlineCount");
if (nOnlineCount <= 0)
{
NF_SHARE_PTR<NFILogicClass> pLogicCLass = m_pLogicClassModule->GetElement("Scene");
if (!pLogicCLass.get())
{
return 0;
}
NFList<std::string>& configList = pLogicCLass->GetConfigNameList();
std::string strSceneConfigID;
for (bool bRet = configList.First(strSceneConfigID); bRet; bRet = configList.Next(strSceneConfigID))
{
int nFirstScene = m_pElementInfoModule->GetPropertyInt(strSceneConfigID, "IsFirstCloneScene");
//һأͨģʽſԣģʽҪͨģʽ
if (nFirstScene > 0)
{
int nSceneId = 0;
if(NF_StrTo(strSceneConfigID, nSceneId))
{//⼤ĵͼֱӿԽֶһ£EctypeListû
AddEctypeActiveState(self, nSceneId);
}
}
}
}
}
else if (COE_CREATE_FINISH == eClassEvent)
{
m_pKernelModule->AddPropertyCallBack(self, "GroupID", this, &NFCEctypeModule::OnObjectGroupIDEvent);
//m_pEventProcessModule->AddEventCallBack(self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, this, &NFCEctypeModule::OnEntrySceneEvent);
}
}
return 0;
}
bool NFCEctypeModule::AddEctypeActiveState(const NFIDENTID self, const int nContainerID)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (pRecord.get() && nContainerID > 0)
{
NFCDataList valNormalResult;
pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
if (valNormalResult.GetCount() <= 0)
{
NFCDataList valValue;
valValue.AddInt(nContainerID);
valValue.AddInt(ECS_HAS_OPEN);
valValue.AddInt(0);
pRecord->AddRow(-1, valValue);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "EctypeList AddEctypeActiveState", nContainerID);
}
}
return true;
}
int NFCEctypeModule::OnEctypeSettleEvent(const NFIDENTID& self, int nResult, int nStar)
{
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (!pObject.get())
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not exit", "", __FUNCTION__, __LINE__);
return 1;
}
int nSceneID = pObject->GetPropertyInt("SceneID");
if (nSceneID <= 0)
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "scene id error", "", __FUNCTION__, __LINE__);
return 1;
}
// ʧ
if (nResult == 0)
{
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
const std::string& strAccout = m_pKernelModule->GetPropertyString(self, "Account");
std::ostringstream stream;
stream << "[ExitEctype] Account[" << strAccout << "] Level[" << nLevel << "] Scene[" << nSceneID << "] [0]";
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, stream, __FUNCTION__, __LINE__);
return 1;
}
if (!m_pSceneProcessModule->IsCloneScene(nSceneID))
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not int clone scene", "", __FUNCTION__, __LINE__);
return 1;
}
// ͨؼ¼
// TODO
// ͨؽ
AddEctypeAward(self, nSceneID);
return 0;
}
bool NFCEctypeModule::CompleteEctypeMode(const NFIDENTID self, const int nContainerID, const int nStar)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (NULL == pRecord.get())
{
return false;
}
//
return true;
}
int NFCEctypeModule::OnObjectGroupIDEvent(const NFIDENTID& self, const std::string& strPropertyName, const NFIDataList& oldVar, const NFIDataList& newVar, const NFIDataList& argVar)
{
return 0;
}
int NFCEctypeModule::AddEctypeAward(const NFIDENTID& self, const int nSceneID)
{
std::string strSceneID = boost::lexical_cast<std::string>(nSceneID);
int nType = m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneType");
int nAddMoney = 0;
int nAddExp = 0;
NFCDataList xItemList;
NFCDataList xCountList;
// 佱
m_pPackModule->DrawDropAward(self, nAddMoney, nAddExp, xItemList, xCountList);
// ͨؽ
// ֪ͨͻ
NFCDataList xAwardInfoList;
xAwardInfoList << nAddMoney;
xAwardInfoList << nAddExp;
if (xItemList.GetCount() == xCountList.GetCount())
{
for (int i = 0; i < xItemList.GetCount(); ++i)
{
xAwardInfoList << xItemList.String(i);
xAwardInfoList << xCountList.Int(i);
}
}
m_pEventProcessModule->DoEvent(self, NFED_ON_NOTICE_ECTYPE_AWARD, xAwardInfoList);
return 0;
}
bool NFCEctypeModule::AddNewEctype(const NFIDENTID self)
{
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
//
return true;
}<commit_msg>end battle function add diamond<commit_after>// -------------------------------------------------------------------------
// @FileName NFCEctypeModule.cpp
// @Author LvSheng.Huang
// @Date 2012-12-15
// @Module NFCEctypeModule
//
// -------------------------------------------------------------------------
#include "NFCEctypeModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include "NFComm/Define/NFStringInfo.h"
bool NFCEctypeModule::Init()
{
return true;
}
bool NFCEctypeModule::Shut()
{
return true;
}
bool NFCEctypeModule::Execute(const float fLasFrametime, const float fStartedTime)
{
return true;
}
bool NFCEctypeModule::AfterInit()
{
m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));
m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
m_pSceneProcessModule = dynamic_cast<NFISceneProcessModule*>(pPluginManager->FindModule("NFCSceneProcessModule"));
m_pAwardModule = dynamic_cast<NFIAwardPackModule*>(pPluginManager->FindModule("NFCAwardPackModule"));
m_pPackModule = dynamic_cast<NFIPackModule*>(pPluginManager->FindModule("NFCPackModule"));
m_pPropertyModule = dynamic_cast<NFIPropertyModule*>(pPluginManager->FindModule("NFCPropertyModule"));
m_pLevelModule = dynamic_cast<NFILevelModule*>(pPluginManager->FindModule("NFCLevelModule"));
m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule"));
m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule"));
assert(NULL != m_pLevelModule);
assert(NULL != m_pPropertyModule);
assert(NULL != m_pPackModule);
assert(NULL != m_pAwardModule);
assert(NULL != m_pEventProcessModule);
assert(NULL != m_pElementInfoModule);
assert(NULL != m_pKernelModule);
assert(NULL != m_pSceneProcessModule);
assert(NULL != m_pLogModule);
assert(NULL != m_pLogicClassModule);
m_pEventProcessModule->AddClassCallBack("Player", this, &NFCEctypeModule::OnObjectClassEvent);
return true;
}
bool NFCEctypeModule::CanEntryCloneScene(const NFIDENTID self, const int nContainerID)
{
std::string strSceneID = boost::lexical_cast<std::string>(nContainerID);
//ûҵжǷǵһIsFirstCloneScene
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
if (nLevel < m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneLevelLimit"))
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "Level limit for scene:" + strSceneID, nLevel, __FUNCTION__, __LINE__);
return false;
}
//ĺֱӿǷ
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (!pRecord.get())
{
return false;
}
NFCDataList valNormalResult;
pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
if (valNormalResult.GetCount() <= 0)
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "no this scene in record", nContainerID, __FUNCTION__, __LINE__);
return false;
}
return true;
}
int NFCEctypeModule::OnObjectClassEvent(const NFIDENTID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
if (strClassName == "Player")
{
if (COE_CREATE_BEFORE_EFFECT == eClassEvent)
{
int nOnlineCount = m_pKernelModule->GetPropertyInt(self, "OnlineCount");
if (nOnlineCount <= 0)
{
NF_SHARE_PTR<NFILogicClass> pLogicCLass = m_pLogicClassModule->GetElement("Scene");
if (!pLogicCLass.get())
{
return 0;
}
NFList<std::string>& configList = pLogicCLass->GetConfigNameList();
std::string strSceneConfigID;
for (bool bRet = configList.First(strSceneConfigID); bRet; bRet = configList.Next(strSceneConfigID))
{
int nFirstScene = m_pElementInfoModule->GetPropertyInt(strSceneConfigID, "IsFirstCloneScene");
//һأͨģʽſԣģʽҪͨģʽ
if (nFirstScene > 0)
{
int nSceneId = 0;
if(NF_StrTo(strSceneConfigID, nSceneId))
{//⼤ĵͼֱӿԽֶһ£EctypeListû
AddEctypeActiveState(self, nSceneId);
}
}
}
}
}
else if (COE_CREATE_FINISH == eClassEvent)
{
m_pKernelModule->AddPropertyCallBack(self, "GroupID", this, &NFCEctypeModule::OnObjectGroupIDEvent);
//m_pEventProcessModule->AddEventCallBack(self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, this, &NFCEctypeModule::OnEntrySceneEvent);
}
}
return 0;
}
bool NFCEctypeModule::AddEctypeActiveState(const NFIDENTID self, const int nContainerID)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (pRecord.get() && nContainerID > 0)
{
NFCDataList valNormalResult;
pRecord->FindInt(EXTYPE_RC_SCENEID, nContainerID, valNormalResult);
if (valNormalResult.GetCount() <= 0)
{
NFCDataList valValue;
valValue.AddInt(nContainerID);
valValue.AddInt(ECS_HAS_OPEN);
valValue.AddInt(0);
pRecord->AddRow(-1, valValue);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "EctypeList AddEctypeActiveState", nContainerID);
}
}
return true;
}
int NFCEctypeModule::OnEctypeSettleEvent(const NFIDENTID& self, int nResult, int nStar)
{
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (!pObject.get())
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not exit", "", __FUNCTION__, __LINE__);
return 1;
}
int nSceneID = pObject->GetPropertyInt("SceneID");
if (nSceneID <= 0)
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "scene id error", "", __FUNCTION__, __LINE__);
return 1;
}
// ʧ
if (nResult == 0)
{
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
const std::string& strAccout = m_pKernelModule->GetPropertyString(self, "Account");
std::ostringstream stream;
stream << "[ExitEctype] Account[" << strAccout << "] Level[" << nLevel << "] Scene[" << nSceneID << "] [0]";
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, stream, __FUNCTION__, __LINE__);
return 1;
}
if (!m_pSceneProcessModule->IsCloneScene(nSceneID))
{
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, self, "player not int clone scene", "", __FUNCTION__, __LINE__);
return 1;
}
// ͨؼ¼
// TODO
// ͨؽ
AddEctypeAward(self, nSceneID);
return 0;
}
bool NFCEctypeModule::CompleteEctypeMode(const NFIDENTID self, const int nContainerID, const int nStar)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, "EctypeList");
if (NULL == pRecord.get())
{
return false;
}
//
return true;
}
int NFCEctypeModule::OnObjectGroupIDEvent(const NFIDENTID& self, const std::string& strPropertyName, const NFIDataList& oldVar, const NFIDataList& newVar, const NFIDataList& argVar)
{
return 0;
}
int NFCEctypeModule::AddEctypeAward(const NFIDENTID& self, const int nSceneID)
{
std::string strSceneID = boost::lexical_cast<std::string>(nSceneID);
int nType = m_pElementInfoModule->GetPropertyInt(strSceneID, "SceneType");
int nAddMoney = 0;
int nAddExp = 0;
int nAddDiamnod = 0;
NFCDataList xItemList;
NFCDataList xCountList;
// 佱
m_pPackModule->DrawDropAward(self, nAddMoney, nAddExp, xItemList, xCountList);
// ͨؽ
// ֪ͨͻ
NFCDataList xAwardInfoList;
xAwardInfoList << nAddMoney;
xAwardInfoList << nAddExp;
xAwardInfoList << nAddDiamnod;
if (xItemList.GetCount() == xCountList.GetCount())
{
for (int i = 0; i < xItemList.GetCount(); ++i)
{
xAwardInfoList << xItemList.String(i);
xAwardInfoList << xCountList.Int(i);
}
}
m_pEventProcessModule->DoEvent(self, NFED_ON_NOTICE_ECTYPE_AWARD, xAwardInfoList);
return 0;
}
bool NFCEctypeModule::AddNewEctype(const NFIDENTID self)
{
int nLevel = m_pKernelModule->GetPropertyInt(self, "Level");
//
return true;
}<|endoftext|> |
<commit_before>#include "CustomSimulation.h"
#include <Visualization/IRenderer.h>
#include <Simulation/Dynamics/Connection/ConnectorFactory.h>
#include <Simulation/Integration/Implementations/ExplicitEuler.h>
#include <Simulation/Integration/Implementations/ImplicitEuler.h>
#include <Simulation/Integration/Implementations/RungeKutta4.h>
#include <Simulation/Integration/Implementations/RungeKuttaFehlberg45.h>
#include <Visualization/Renderers/LightRenderer.h>
#include <Visualization/Renderers/CoordinateSystemRenderer.h>
#include <Visualization/Renderers/CameraRenderer.h>
#include <Visualization/Renderers/SimulationRunnerRenderer.h>
#include <Visualization/Renderers/TextRenderer.h>
#include <Visualization/Renderers/ConnectorRenderer.h>
#include <Visualization/Renderers/ConnectorVelocityRenderer.h>
#include <Visualization/Renderers/ConnectorForceRenderer.h>
#include <Visualization/Renderers/ParticleRenderer.h>
#include <Visualization/Renderers/BoxRenderer.h>
#include <Visualization/Renderers/SpringRenderer.h>
#include <Visualization/Renderers/TweakBar/TweakBarRenderer.h>
#include <Visualization/UserInterface/DelegateAction.h>
#include <Visualization/UserInterface/RealValue.h>
#include <Visualization/Renderers/PlaneRenderer.h>
#include <Visualization/InputHandler.h>
#include <Simulation/SimulationBuilder.h>
#include <Simulation/Textiles/TextileModel.h>
#include <Simulation/DynamicsAlgorithm.h>
#include <Visualization/Renderers/SphereRenderer.h>
#include <Visualization/Renderers/CollisionRenderer.h>
#include <Visualization/Renderers/OctreeRenderer.h>
#include <Simulation/Geometry/Plane.h>
#include <Simulation/Geometry/BoundingVolumes/BoundingSphere.h>
#include <map>
#include <sstream>
#include <Visualization/Renderers/PolygonRenderer.h>
#include <Visualization/UserInterface/Vector3DValue.h>
#include <Simulation/Geometry/Mesh/Ply/PlyMesh.h>
using namespace IBDS;
using namespace std;
int integratorIndex=0;
vector<SingleStepIntegrator*> integrators;
void CustomSimulation::buildModel(){
setName("Collision Handling Example");
CollisionRenderer * collisionRenderer =new CollisionRenderer(dynamicsAlgorithm.collisionDetector);
addSimulationObject(collisionRenderer);
SimulationBuilder b(*this);
Gravity & g = *(b.setGravity(Vector3D(0,-1,0)));
g.setGravityMagnitude(0.1);
addSimulationObject(new DelegateAction("Render Collisions", [collisionRenderer](){collisionRenderer->renderCollisions()=!collisionRenderer->renderCollisions();}));
addSimulationObject(new RealValue("Collisiontrace Timeout",collisionRenderer->timeout()));
addSimulationObject(new DelegateAction("Collisiontrace", [collisionRenderer](){
collisionRenderer->renderCollisionTrace() = !collisionRenderer->renderCollisionTrace();
}));
g.setGravityMagnitude(0.1);
addSimulationObject( new RealValue("Gravity Magnitude",
[&g](){return g.getGravityMagnitude();},
[&g](Real val){g.setGravityMagnitude(val);}));
{
auto plane = new DynamicGeometry<Plane>(*new Plane(),0,Matrix3x3::Identity());
plane->coordinates().position() = Vector3D(0,-4,0);
plane->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),-0.2);
addSimulationObject(new Vector3DValue("plane ",plane->coordinates().position()));
addSimulationObject(plane);
auto renderer = new PlaneRenderer(plane->geometry());
addSimulationObject(renderer);
addSimulationObject(new RealValue("plane extent",renderer->extent()));
addSimulationObject(DynamicCollidable::create(plane->geometry(),plane->body(),0.5,0.01,0.01));
}
DynamicBox *body = new DynamicBox(1,1,1,1);
Real planeAngle = -0.2;
body->coordinates().position().set(0+5*cos(planeAngle)-0.5*sin(planeAngle),-3.99+5*sin(planeAngle)+0.5*cos(planeAngle),0);
body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
addSimulationObject(new BoxRenderer(body->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,0.02));
body = new DynamicBox(1,1,1,1);
body->coordinates().position().set(0+10*cos(planeAngle)-0.5*sin(planeAngle),-3.99+10*sin(planeAngle)+0.5*cos(planeAngle),0);
body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
addSimulationObject(new BoxRenderer(body->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,10));
{
auto sphere = new DynamicSphere(1,1);
addSimulationObject(sphere);
addSimulationObject(new Vector3DValue("sphere",sphere->coordinates().position()));
addSimulationObject(new SphereRenderer(sphere->geometry()));
sphere->coordinates().position() = Vector3D(1,-2,0);
addSimulationObject(DynamicCollidable::create(sphere->geometry(),sphere->body(),0.1,100,50));
}
{
auto box = new DynamicBox();
addSimulationObject(box);
addSimulationObject(new Vector3DValue("box", box->coordinates().position()));
addSimulationObject(new BoxRenderer(box->geometry()));
box->coordinates().position().set(3,2,0);
addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,* new BoundingSphereFactory()),box->body(),0.3,100,50));
}
//{
//auto pyramid = new DynamicGeometry<Pyramid>(*new Pyramid(),1,Matrix3x3::Identity());
//addSimulationObject(pyramid);
//addSimulationObject(new Vector3DValue("pyramid",pyramid->coordinates().position()));
//addSimulationObject(new PolygonRenderer(pyramid->geometry()));
//pyramid->coordinates().position().set(3,1,0);
//addSimulationObject(DynamicCollidable::create(*new Octree(pyramid->geometry(),3,* new BoundingSphereFactory()),pyramid->body(),0.3));
//}
{
DynamicSphere * sphere = 0;
DynamicCollidable * collidable;
b.setOffset(Vector3D(10,3,4));
Real radius = 0.5;
Particle *particle ;
particle = b.createParticle("p6",Vector3D(-2,-1,0),1);
sphere = b.createSphere("s6",Vector3D(-2,-1,0),1,radius);
b.createBallJoint("j6","s6","p6",Vector3D(-2,-1,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p5",Vector3D(-2,0,0),0);
sphere = b.createSphere("s5",Vector3D(-2,-2,0),2,radius);
b.createBallJoint("j5","s5","p5",Vector3D(-2,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p4",Vector3D(-1,0,0),0);
sphere = b.createSphere("s4",Vector3D(-1,-2,0),2,radius);
b.createBallJoint("j4","s4","p4",Vector3D(-1,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p1",Vector3D(0,0,0),0);
//sphere = b.createSphere("s1",Vector3D(-3,-0.3,0),1,radius);
sphere = b.createSphere("s1",Vector3D(0,-2,0),2,radius);
b.createBallJoint("j1","s1","p1",Vector3D(0,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p2",Vector3D(1,0,0),0);
sphere= b.createSphere("s2",Vector3D(3,0,0),1,radius);
b.createBallJoint("j2","s2","p2",Vector3D(1,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
}
//{
//for(int i= 0; i < 2; i++){
// Particle * p = new Particle();
// Sphere * sphere = new Sphere(0.1);
// p->position << sphere->coordinates().position;
// Vector3D randVector((rand()%1000)/1000.0,(rand()%1000)/1000.0,(rand()%1000)/1000.0);
// p->position() = randVector*5+Vector3D(7,0,0);
// p->velocity() = randVector*5 - Vector3D(2.5,2.5,2.5);
// DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*p);
// addSimulationObject(p);
// addSimulationObject(sphere);
// addSimulationObject(collidable);
// addSimulationObject(new SphereRenderer(*sphere));
// }
//}
{
Quaternion orientation;
orientation.setFromAxisAngle(Vector3D(1,0,0),PI /2);
int clothDim = 20;
//TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),200,8,8,clothDim,clothDim);
TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),clothDim*clothDim,clothDim/5,clothDim/5,clothDim,clothDim);
cloth->setElongationSpringConstant(80);
cloth->setFlexionSpringConstant(80);
cloth->setShearSpringConstant(80);
cloth->getNode(0,0)->particle->setMass(0);
cloth->getNode(clothDim-1,clothDim-1)->particle->setMass(0);
cloth->getNode(0,clothDim-1)->particle->setMass(0);
cloth->getNode(clothDim-1,0)->particle->setMass(0);
addSimulationObject(cloth);
for_each(cloth->getSimulationObjects().begin(), cloth->getSimulationObjects().end(), [this](ISimulationObject * obj){
addSimulationObject(obj);
});
cloth->foreachNode([this](TextileNode * node){
Sphere * sphere = new Sphere(0.1);
DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*node->particle);
sphere->coordinates().position.mirror(node->particle->position);
addSimulationObject(sphere);
//addSimulationObject(new SphereRenderer(*sphere));
addSimulationObject(collidable);
});
DynamicBox * box = new DynamicBox(90);
box->kinematics().position() = Vector3D(10,2,12);
addSimulationObject(box);
addSimulationObject(new PolygonRenderer(box->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,*new BoundingSphereFactory()),box->body()));
}
{
/*
PlyMesh * mesh = new PlyMesh("cube.ply");
mesh->initialize();
// mesh->scale(60,60,60);
addSimulationObject(mesh);
PolygonRenderer * r = new PolygonRenderer(*mesh);
r->drawLabels = false;
r->drawNormals = false;
addSimulationObject(r);//*/
}
}
void CustomSimulation::onSimulationObjectAdded(ISimulationObject * simulationObject){
Connector * connector = dynamic_cast<Connector*>(simulationObject);
if(connector){
addSimulationObject(new ConnectorRenderer(*connector));
}
Particle * particle = dynamic_cast<Particle*>(simulationObject);
if(particle){
addSimulationObject(new ParticleRenderer(*particle));
}
}
void CustomSimulation::buildAlgorithms(){
integrators.push_back(new ExplicitEuler(0.01));
integrators.push_back(new ImplicitEuler(0.02));
integrators.push_back(new RungeKutta4(0.01));
addSimulationObject(&dynamicsAlgorithm);
integrator = integrators.at(0);
integrator->setSystemFunction(dynamicsAlgorithm);
setIntegrator(*integrator);
addSimulationObject(new DelegateAction("toggle collision detection",[this](){
dynamicsAlgorithm.detectCollisions = ! dynamicsAlgorithm.detectCollisions;
dynamicsAlgorithm.collisionDetector.resetCollisions();
}));
addSimulationObject(new DelegateAction("toggle multibody",[this](){
dynamicsAlgorithm.doMultiBody = ! dynamicsAlgorithm.doMultiBody;
}));
addSimulationObject(new RealValue("time", [this](){return getTime();}, [](Real r){}));
addSimulationObject(new IntValue("Integrator 0-2 (0=ee, 1=ie,2=rk4)",
[this](){
return integratorIndex;
},
[this](int val){
integratorIndex = val % 3;
integrator= integrators.at(integratorIndex);
integrator->setSystemFunction(dynamicsAlgorithm);
setIntegrator(*integrator);
}));
addSimulationObject( new RealValue("Integrator Step Size",
[this](){return integrator->getStepSize();},
[this](Real value){integrator->setStepSize(value);}));
addSimulationObject(new LightRenderer());
addSimulationObject(new CoordinateSystemRenderer());// renders coordinate system at world origin
auto cam = new CameraRenderer();
cam->position() =Vector3D(8,0,30);
cam->orientation().setFromAxisAngle(Vector3D(0,1,0),PI/2);
addSimulationObject(cam);
addSimulationObject(new Vector3DValue("camera position", cam->position()));
}
<commit_msg>added an example <commit_after>#include "CustomSimulation.h"
#include <Visualization/IRenderer.h>
#include <Simulation/Dynamics/Connection/ConnectorFactory.h>
#include <Simulation/Integration/Implementations/ExplicitEuler.h>
#include <Simulation/Integration/Implementations/ImplicitEuler.h>
#include <Simulation/Integration/Implementations/RungeKutta4.h>
#include <Simulation/Integration/Implementations/RungeKuttaFehlberg45.h>
#include <Visualization/Renderers/LightRenderer.h>
#include <Visualization/Renderers/CoordinateSystemRenderer.h>
#include <Visualization/Renderers/CameraRenderer.h>
#include <Visualization/Renderers/SimulationRunnerRenderer.h>
#include <Visualization/Renderers/TextRenderer.h>
#include <Visualization/Renderers/ConnectorRenderer.h>
#include <Visualization/Renderers/ConnectorVelocityRenderer.h>
#include <Visualization/Renderers/ConnectorForceRenderer.h>
#include <Visualization/Renderers/ParticleRenderer.h>
#include <Visualization/Renderers/BoxRenderer.h>
#include <Visualization/Renderers/SpringRenderer.h>
#include <Visualization/Renderers/TweakBar/TweakBarRenderer.h>
#include <Visualization/UserInterface/DelegateAction.h>
#include <Visualization/UserInterface/RealValue.h>
#include <Visualization/Renderers/PlaneRenderer.h>
#include <Visualization/InputHandler.h>
#include <Simulation/SimulationBuilder.h>
#include <Simulation/Textiles/TextileModel.h>
#include <Simulation/DynamicsAlgorithm.h>
#include <Visualization/Renderers/SphereRenderer.h>
#include <Visualization/Renderers/CollisionRenderer.h>
#include <Visualization/Renderers/OctreeRenderer.h>
#include <Simulation/Geometry/Plane.h>
#include <Simulation/Geometry/BoundingVolumes/BoundingSphere.h>
#include <map>
#include <sstream>
#include <Visualization/Renderers/PolygonRenderer.h>
#include <Visualization/UserInterface/Vector3DValue.h>
#include <Simulation/Geometry/Mesh/Ply/PlyMesh.h>
using namespace IBDS;
using namespace std;
int integratorIndex=0;
vector<SingleStepIntegrator*> integrators;
void CustomSimulation::buildModel(){
setName("Collision Handling Example");
CollisionRenderer * collisionRenderer =new CollisionRenderer(dynamicsAlgorithm.collisionDetector);
addSimulationObject(collisionRenderer);
SimulationBuilder b(*this);
Gravity & g = *(b.setGravity(Vector3D(0,-1,0)));
g.setGravityMagnitude(0.1);
addSimulationObject(new DelegateAction("Render Collisions", [collisionRenderer](){collisionRenderer->renderCollisions()=!collisionRenderer->renderCollisions();}));
addSimulationObject(new RealValue("Collisiontrace Timeout",collisionRenderer->timeout()));
addSimulationObject(new DelegateAction("Collisiontrace", [collisionRenderer](){
collisionRenderer->renderCollisionTrace() = !collisionRenderer->renderCollisionTrace();
}));
g.setGravityMagnitude(0.1);
addSimulationObject( new RealValue("Gravity Magnitude",
[&g](){return g.getGravityMagnitude();},
[&g](Real val){g.setGravityMagnitude(val);}));
{
auto plane = new DynamicGeometry<Plane>(*new Plane(),0,Matrix3x3::Identity());
plane->coordinates().position() = Vector3D(0,-4,0);
plane->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),-0.2);
addSimulationObject(new Vector3DValue("plane ",plane->coordinates().position()));
addSimulationObject(plane);
auto renderer = new PlaneRenderer(plane->geometry());
addSimulationObject(renderer);
addSimulationObject(new RealValue("plane extent",renderer->extent()));
addSimulationObject(DynamicCollidable::create(plane->geometry(),plane->body(),0.5,0.01,0.01));
}
DynamicBox *body = new DynamicBox(1,1,1,1);
Real planeAngle = -0.2;
body->coordinates().position().set(0+5*cos(planeAngle)-0.5*sin(planeAngle),-3.99+5*sin(planeAngle)+0.5*cos(planeAngle),0);
body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
addSimulationObject(new BoxRenderer(body->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,0.02));
body = new DynamicBox(1,1,1,1);
body->coordinates().position().set(0+10*cos(planeAngle)-0.5*sin(planeAngle),-3.99+10*sin(planeAngle)+0.5*cos(planeAngle),0);
body->coordinates().orientation().setFromAxisAngle(Vector3D(0,0,1),planeAngle);
addSimulationObject(new BoxRenderer(body->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(body->geometry(),5,* new BoundingSphereFactory()),body->body(),0.5,0.01,10));
{
auto sphere = new DynamicSphere(1,1);
addSimulationObject(sphere);
addSimulationObject(new Vector3DValue("sphere",sphere->coordinates().position()));
addSimulationObject(new SphereRenderer(sphere->geometry()));
sphere->coordinates().position() = Vector3D(1,-2,0);
addSimulationObject(DynamicCollidable::create(sphere->geometry(),sphere->body(),0.1,100,50));
}
{
auto box = new DynamicBox();
addSimulationObject(box);
addSimulationObject(new Vector3DValue("box", box->coordinates().position()));
addSimulationObject(new BoxRenderer(box->geometry()));
box->coordinates().position().set(3,2,0);
addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,* new BoundingSphereFactory()),box->body(),0.3,100,50));
}
//{
//auto pyramid = new DynamicGeometry<Pyramid>(*new Pyramid(),1,Matrix3x3::Identity());
//addSimulationObject(pyramid);
//addSimulationObject(new Vector3DValue("pyramid",pyramid->coordinates().position()));
//addSimulationObject(new PolygonRenderer(pyramid->geometry()));
//pyramid->coordinates().position().set(3,1,0);
//addSimulationObject(DynamicCollidable::create(*new Octree(pyramid->geometry(),3,* new BoundingSphereFactory()),pyramid->body(),0.3));
//}
{
DynamicSphere * sphere = 0;
DynamicCollidable * collidable;
b.setOffset(Vector3D(10,3,4));
Real radius = 0.5;
Particle *particle ;
particle = b.createParticle("p6",Vector3D(-2,-1,0),1);
sphere = b.createSphere("s6",Vector3D(-2,-1,0),1,radius);
b.createBallJoint("j6","s6","p6",Vector3D(-2,-1,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p5",Vector3D(-2,0,0),0);
sphere = b.createSphere("s5",Vector3D(-2,-2,0),2,radius);
b.createBallJoint("j5","s5","p5",Vector3D(-2,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p4",Vector3D(-1,0,0),0);
sphere = b.createSphere("s4",Vector3D(-1,-2,0),2,radius);
b.createBallJoint("j4","s4","p4",Vector3D(-1,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p1",Vector3D(0,0,0),0);
//sphere = b.createSphere("s1",Vector3D(-3,-0.3,0),1,radius);
sphere = b.createSphere("s1",Vector3D(0,-2,0),2,radius);
b.createBallJoint("j1","s1","p1",Vector3D(0,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
particle = b.createParticle("p2",Vector3D(1,0,0),0);
sphere= b.createSphere("s2",Vector3D(3,0,0),1,radius);
b.createBallJoint("j2","s2","p2",Vector3D(1,0,0));
addSimulationObject(new SphereRenderer(sphere->geometry()));
collidable = DynamicCollidable::create(sphere->geometry(),sphere->body());
addSimulationObject(collidable);
}
//{
//for(int i= 0; i < 2; i++){
// Particle * p = new Particle();
// Sphere * sphere = new Sphere(0.1);
// p->position << sphere->coordinates().position;
// Vector3D randVector((rand()%1000)/1000.0,(rand()%1000)/1000.0,(rand()%1000)/1000.0);
// p->position() = randVector*5+Vector3D(7,0,0);
// p->velocity() = randVector*5 - Vector3D(2.5,2.5,2.5);
// DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*p);
// addSimulationObject(p);
// addSimulationObject(sphere);
// addSimulationObject(collidable);
// addSimulationObject(new SphereRenderer(*sphere));
// }
//}
{
Quaternion orientation;
orientation.setFromAxisAngle(Vector3D(1,0,0),PI /2);
int clothDim = 20;
//TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),200,8,8,clothDim,clothDim);
TextileModel * cloth = TextileModel::createTextileModel(Vector3D(10,0,12),orientation.getMatrix3x3(),clothDim*clothDim,clothDim/5,clothDim/5,clothDim,clothDim);
cloth->setElongationSpringConstant(80);
cloth->setFlexionSpringConstant(80);
cloth->setShearSpringConstant(80);
cloth->getNode(0,0)->particle->setMass(0);
cloth->getNode(clothDim-1,clothDim-1)->particle->setMass(0);
cloth->getNode(0,clothDim-1)->particle->setMass(0);
cloth->getNode(clothDim-1,0)->particle->setMass(0);
addSimulationObject(cloth);
for_each(cloth->getSimulationObjects().begin(), cloth->getSimulationObjects().end(), [this](ISimulationObject * obj){
addSimulationObject(obj);
});
cloth->foreachNode([this](TextileNode * node){
Sphere * sphere = new Sphere(0.1);
DynamicCollidable * collidable = DynamicCollidable::create(*sphere,*node->particle);
sphere->coordinates().position.mirror(node->particle->position);
addSimulationObject(sphere);
//addSimulationObject(new SphereRenderer(*sphere));
addSimulationObject(collidable);
});
DynamicBox * box = new DynamicBox(90);
box->kinematics().position() = Vector3D(10,2,12);
addSimulationObject(box);
addSimulationObject(new PolygonRenderer(box->geometry()));
addSimulationObject(DynamicCollidable::create(*new Octree(box->geometry(),3,*new BoundingSphereFactory()),box->body()));
addSimulationObject(new DelegateAction("box mass",[box](){
if(box->body().getMass()){
box->body().setMass(0);
}else{
box->body().setMass(1);
}
}));
}
{
DynamicGeometry<Rectangle> * rectangle;
PolygonRenderer * renderer;
Real spacing=3;
DynamicCollidable * collidable;
Vector3D offset(0,0,-3);
Vector3D left(-1,0,0);
Vector3D right(1,0,0);
Real angle = PI/6;
Vector3D axis(0,0,1);
Vector2D rectangleDim(3,2);
Quaternion q;
Vector3D pos;
q.setFromAxisAngle(Vector3D(1,0,0),PI/2);
for(int i=0; i< 4; i++){
rectangle = new DynamicGeometry<Rectangle>(
*new Rectangle(rectangleDim),
0,
Matrix3x3::Zero());
renderer = new PolygonRenderer(rectangle->geometry());
collidable = DynamicCollidable::create(*new Octree(rectangle->geometry(),4,*new BoundingSphereFactory()),rectangle->body(),0.1);
pos = offset + Vector3D(0,spacing * i,0);
Quaternion ori;
if(i%2){
pos = pos + right;
ori.setFromAxisAngle(axis,angle);
}else{
pos = pos + left;
ori.setFromAxisAngle(axis,-angle);
}
rectangle->coordinates().position() = pos;
rectangle->coordinates().orientation() =ori*q;
addSimulationObject(rectangle);
addSimulationObject(renderer);
addSimulationObject(collidable);
}
DynamicSphere * sphere = new DynamicSphere(0.1,0.6);
addSimulationObject(sphere);
addSimulationObject(new SphereRenderer(sphere->geometry()));
addSimulationObject(DynamicCollidable::create(sphere->geometry(), sphere->body(),0.4,10,6));
sphere->coordinates().position() = pos+Vector3D(0,1,0);
}
{
/*
PlyMesh * mesh = new PlyMesh("cube.ply");
mesh->initialize();
// mesh->scale(60,60,60);
addSimulationObject(mesh);
PolygonRenderer * r = new PolygonRenderer(*mesh);
r->drawLabels = false;
r->drawNormals = false;
addSimulationObject(r);//*/
}
}
void CustomSimulation::onSimulationObjectAdded(ISimulationObject * simulationObject){
Connector * connector = dynamic_cast<Connector*>(simulationObject);
if(connector){
addSimulationObject(new ConnectorRenderer(*connector));
}
Particle * particle = dynamic_cast<Particle*>(simulationObject);
if(particle){
addSimulationObject(new ParticleRenderer(*particle));
}
}
void CustomSimulation::buildAlgorithms(){
integrators.push_back(new ExplicitEuler(0.01));
integrators.push_back(new ImplicitEuler(0.02));
integrators.push_back(new RungeKutta4(0.01));
addSimulationObject(&dynamicsAlgorithm);
integrator = integrators.at(0);
integrator->setSystemFunction(dynamicsAlgorithm);
setIntegrator(*integrator);
addSimulationObject(new DelegateAction("toggle collision detection",[this](){
dynamicsAlgorithm.detectCollisions = ! dynamicsAlgorithm.detectCollisions;
dynamicsAlgorithm.collisionDetector.resetCollisions();
}));
addSimulationObject(new DelegateAction("toggle multibody",[this](){
dynamicsAlgorithm.doMultiBody = ! dynamicsAlgorithm.doMultiBody;
}));
addSimulationObject(new RealValue("time", [this](){return getTime();}, [](Real r){}));
addSimulationObject(new IntValue("Integrator 0-2 (0=ee, 1=ie,2=rk4)",
[this](){
return integratorIndex;
},
[this](int val){
integratorIndex = val % 3;
integrator= integrators.at(integratorIndex);
integrator->setSystemFunction(dynamicsAlgorithm);
setIntegrator(*integrator);
}));
addSimulationObject( new RealValue("Integrator Step Size",
[this](){return integrator->getStepSize();},
[this](Real value){integrator->setStepSize(value);}));
addSimulationObject(new LightRenderer());
addSimulationObject(new CoordinateSystemRenderer());// renders coordinate system at world origin
auto cam = new CameraRenderer();
cam->position() =Vector3D(8,0,30);
cam->orientation().setFromAxisAngle(Vector3D(0,1,0),PI/2);
addSimulationObject(cam);
addSimulationObject(new Vector3DValue("camera position", cam->position()));
}
<|endoftext|> |
<commit_before>#ifndef JOEDB_PORTABLE
#include "joedb/concurrency/Local_Connection.h"
#include "joedb/journal/File.h"
#include "joedb/concurrency/Interpreted_Client.h"
#include "joedb/journal/Memory_File.h"
#include "gtest/gtest.h"
using namespace joedb;
static const char * const file_name = "local_connection.joedb";
/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, bad_journal)
/////////////////////////////////////////////////////////////////////////////
{
std::remove(file_name);
Local_Connection<File> connection(file_name);
{
Memory_File client_file;
EXPECT_ANY_THROW
(
Interpreted_Client client(connection, client_file)
);
}
Interpreted_Client client(connection, connection.get_file());
}
/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, simple_operation)
/////////////////////////////////////////////////////////////////////////////
{
std::remove(file_name);
Local_Connection<File> connection1(file_name);
Local_Connection<File> connection2(file_name);
Interpreted_Client client1(connection1, connection1.get_file());
Interpreted_Client client2(connection2, connection2.get_file());
client1.transaction
(
[](Readable &readable, Writable &writable)
{
writable.create_table("person");
}
);
EXPECT_EQ(0, int(client2.get_database().get_tables().size()));
client2.pull();
EXPECT_EQ(1, int(client2.get_database().get_tables().size()));
client2.transaction
(
[](Readable &readable, Writable &writable)
{
writable.create_table("city");
}
);
EXPECT_EQ(1, int(client1.get_database().get_tables().size()));
client1.pull();
EXPECT_EQ(2, int(client1.get_database().get_tables().size()));
}
#endif
<commit_msg>unit test for Local_Connection size_check.<commit_after>#include <joedb/Writable.h>
#include <joedb/journal/Generic_File.h>
#include <joedb/journal/Writable_Journal.h>
#ifndef JOEDB_PORTABLE
#include "joedb/concurrency/Local_Connection.h"
#include "joedb/journal/File.h"
#include "joedb/concurrency/Interpreted_Client.h"
#include "joedb/journal/Memory_File.h"
#include "gtest/gtest.h"
using namespace joedb;
static const char * const file_name = "local_connection.joedb";
/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, bad_journal)
/////////////////////////////////////////////////////////////////////////////
{
std::remove(file_name);
Local_Connection<File> connection(file_name);
{
Memory_File client_file;
EXPECT_ANY_THROW
(
Interpreted_Client client(connection, client_file)
);
}
Interpreted_Client client(connection, connection.get_file());
}
/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, simple_operation)
/////////////////////////////////////////////////////////////////////////////
{
std::remove(file_name);
Local_Connection<File> connection1(file_name);
Local_Connection<File> connection2(file_name);
Interpreted_Client client1(connection1, connection1.get_file());
Interpreted_Client client2(connection2, connection2.get_file());
client1.transaction
(
[](Readable &readable, Writable &writable)
{
writable.create_table("person");
}
);
EXPECT_EQ(0, int(client2.get_database().get_tables().size()));
client2.pull();
EXPECT_EQ(1, int(client2.get_database().get_tables().size()));
client2.transaction
(
[](Readable &readable, Writable &writable)
{
writable.create_table("city");
}
);
EXPECT_EQ(1, int(client1.get_database().get_tables().size()));
client1.pull();
EXPECT_EQ(2, int(client1.get_database().get_tables().size()));
}
/////////////////////////////////////////////////////////////////////////////
TEST(Local_Connection, size_check)
/////////////////////////////////////////////////////////////////////////////
{
std::remove(file_name);
{
joedb::File file(file_name, joedb::Open_Mode::create_new);
joedb::Writable_Journal journal(file);
journal.timestamp(0);
journal.flush();
}
try
{
Local_Connection<File> connection(file_name);
FAIL() << "Expected an exception\n";
}
catch(...)
{
}
}
#endif
<|endoftext|> |
<commit_before>#pragma ident "$Id: //depot/msn/main/wonky/gpstkplot/lib/plot/Splitter.cpp#4 $"
/// @file Splitter.cpp Used to help with splitting sets of points. Class
/// definitions.
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
#include "Splitter.hpp"
using namespace std;
using namespace vdraw;
namespace vplot
{
pair<list<Path*>*, list<Path*>*> Splitter::splith(double splitter, Path* p, bool top, bool bottom, bool continuous)
{
if(!(top || bottom) || p->empty())
return pair<list<Path* >*, list<Path*>*>(0, 0);
list<Path*> *tl, *bl;
if(top)
tl = new list<Path*> ();
if(bottom)
bl = new list<Path*> ();
Path* current = new Path(0,0);
Path::iterator i=p->begin(),j=(Path::iterator)0;
bool above = i->second > splitter;
if(above && top) current->addPointAbsolute(i->first, i->second);
else if(!above && bottom) current->addPointAbsolute(i->first, i->second);
i++;
double tdouble = 0;
for (;i != p->end(); i++)
{
if (above && (i->second < splitter))
{
if(top)
{
if(continuous)
{
j = i;
j--;
tdouble = intersecth(splitter,*i,*j);
current->addPointAbsolute(tdouble,splitter);
}
if(!current->empty()) tl->push_back(current);
current = new Path(0,0);
if(continuous)
current->addPointAbsolute(tdouble,splitter);
}
above = false;
}
else if(!above && (i->second > splitter))
{
if(bottom)
{
if(continuous)
{
j = i;
j--;
tdouble = intersecth(splitter,*i,*j);
current->addPointAbsolute(tdouble,splitter);
}
if(!current->empty()) bl->push_back(current);
current = new Path(0,0);
if(continuous)
current->addPointAbsolute(tdouble,splitter);
}
above = true;
}
else if(i->second == splitter)
{
Path::iterator j=i;
j++;
/*
* Only add, push, and make a new path if it doesn't "bounce" off of the
* splitter.
* So we do a lookahead of one with j.
* We will _skip_ this area iff:
* - j is at the end of p
* - (i-1) is above and j is below
* - (i-1) is below and j is above
*/
if( (j != p->end()) &&
((above && (j->second < splitter)) ||
(!above && (j->second > splitter))) )
{
current->addPointAbsolute(i->first, i->second);
if (above && top)
tl->push_back(current);
else if(!above && bottom)
bl->push_back(current);
current = new Path(0,0);
above = !above;
}
}
if ((above && top) || (!above && bottom))
current->addPointAbsolute(i->first, i->second);
}
if(!current->empty())
{
if(above && top) tl->push_back(current);
else if(!above && bottom) bl->push_back(current);
}
return pair<list<Path*>*, list<Path*>*>(tl, bl);
}
list<Path*>* Splitter::splitvgap(double gap, Path* p)
{
if((p==0)||(p->empty()))
return 0;
list<Path*> *paths = new list<Path*> ();
Path* current = new Path(0,0);
Path::iterator i=p->begin();
Path::iterator last=i;
current->addPointAbsolute(i->first, i->second);
i++;
gap = (gap<0?-gap:gap);
for (;i != p->end(); i++, last++)
{
double dist = i->first - last->first;
dist = (dist<0?-dist:dist);
if (dist >= gap)
{
paths->push_back(current);
current = new Path(0,0);
}
current->addPointAbsolute(i->first, i->second);
}
if(!current->empty())
paths->push_back(current);
return paths;
}
std::pair<double,double> Splitter::intersectBox(
const std::pair<double,double> inside, const std::pair<double,double> outside,
double minX, double maxX, double minY, double maxY)
{
double x,y;
if(outside.first < minX)
{
x = minX;
y = intersectv(x, inside, outside);
if(y>minY && y<maxY) return std::pair<double,double>(x,y);
}
else if(outside.first > maxX)
{
x = maxX;
y = intersectv(x, inside, outside);
if(y>minY && y<maxY) return std::pair<double,double>(x,y);
}
if(outside.second < minY)
{
y = minY;
x = intersecth(y, inside, outside);
return std::pair<double,double>(x,y);
}
else if(outside.second > maxY)
{
y = maxY;
x = intersecth(y, inside, outside);
return std::pair<double,double>(x,y);
}
// outside isn't out of the box, maybe inside is...
if(!inBox(inside,minX,maxX,minY,maxY))
return intersectBox(outside,inside,minX,maxX,minY,maxY);
// Neither outside nor inside are out of the box. Just give back one of
// the points (the first)
return inside;
}
std::auto_ptr< std::list< vdraw::Path > > Splitter::interpToBox(double minX, double maxX, double minY, double maxY, const vdraw::Path& p)
{
using namespace vdraw;
Path::const_iterator i=p.begin(),j=p.begin();
bool inside = inBox(*i,minX,maxX,minY,maxY);
bool lastinside = inside;
double cx, cy;
p.getOrigin(cx,cy);
std::auto_ptr< std::list< Path > > thelist(new std::list<Path>());
Path current(cx,cy);
if(inside)
current.push_back(*i);
i++;
for(;i!=p.end();i++,j++,lastinside=inside)
{
inside = inBox(*i,minX,maxX,minY,maxY);
if(!inside && lastinside)
{
current.push_back(intersectBox(*j,*i,minX,maxX,minY,maxY));
thelist->push_back(current);
current = Path(cx,cy);
}
else if(inside && !lastinside)
{
current.push_back(intersectBox(*i,*j,minX,maxX,minY,maxY));
current.push_back(*i);
}
else if(inside)
{
current.push_back(*i);
}
}
if(current.size() != 0)
thelist->push_back(current);
return thelist;
}
std::auto_ptr< vdraw::Path > Splitter::cropToBox(double minX, double maxX, double minY, double maxY, const vdraw::Path& p)
{
using namespace vdraw;
Path::const_iterator i=p.begin();
bool inside = inBox(*i,minX,maxX,minY,maxY);
std::auto_ptr< Path > newpath(new Path(0,0,p.size()));
if(inside) newpath->push_back(*i);
i++;
for(;i!=p.end();i++)
{
inside = inBox(*i,minX,maxX,minY,maxY);
if(inside) newpath->push_back(*i);
}
newpath->tighten();
return newpath;
}
}
<commit_msg>Another Windows compile fix.<commit_after>#pragma ident "$Id: //depot/msn/main/wonky/gpstkplot/lib/plot/Splitter.cpp#4 $"
/// @file Splitter.cpp Used to help with splitting sets of points. Class
/// definitions.
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
#include "Splitter.hpp"
using namespace std;
using namespace vdraw;
namespace vplot
{
pair<list<Path*>*, list<Path*>*> Splitter::splith(double splitter, Path* p, bool top, bool bottom, bool continuous)
{
if(!(top || bottom) || p->empty())
return pair<list<Path* >*, list<Path*>*>(0, 0);
list<Path*> *tl, *bl;
if(top)
tl = new list<Path*> ();
if(bottom)
bl = new list<Path*> ();
Path* current = new Path(0,0);
Path::iterator i=p->begin();
bool above = i->second > splitter;
if(above && top) current->addPointAbsolute(i->first, i->second);
else if(!above && bottom) current->addPointAbsolute(i->first, i->second);
i++;
double tdouble = 0;
for (;i != p->end(); i++)
{
if (above && (i->second < splitter))
{
if(top)
{
if(continuous)
{
Path::iterator j = i;
j--;
tdouble = intersecth(splitter,*i,*j);
current->addPointAbsolute(tdouble,splitter);
}
if(!current->empty()) tl->push_back(current);
current = new Path(0,0);
if(continuous)
current->addPointAbsolute(tdouble,splitter);
}
above = false;
}
else if(!above && (i->second > splitter))
{
if(bottom)
{
if(continuous)
{
Path::iterator j = i;
j--;
tdouble = intersecth(splitter,*i,*j);
current->addPointAbsolute(tdouble,splitter);
}
if(!current->empty()) bl->push_back(current);
current = new Path(0,0);
if(continuous)
current->addPointAbsolute(tdouble,splitter);
}
above = true;
}
else if(i->second == splitter)
{
Path::iterator j=i;
j++;
/*
* Only add, push, and make a new path if it doesn't "bounce" off of the
* splitter.
* So we do a lookahead of one with j.
* We will _skip_ this area iff:
* - j is at the end of p
* - (i-1) is above and j is below
* - (i-1) is below and j is above
*/
if( (j != p->end()) &&
((above && (j->second < splitter)) ||
(!above && (j->second > splitter))) )
{
current->addPointAbsolute(i->first, i->second);
if (above && top)
tl->push_back(current);
else if(!above && bottom)
bl->push_back(current);
current = new Path(0,0);
above = !above;
}
}
if ((above && top) || (!above && bottom))
current->addPointAbsolute(i->first, i->second);
}
if(!current->empty())
{
if(above && top) tl->push_back(current);
else if(!above && bottom) bl->push_back(current);
}
return pair<list<Path*>*, list<Path*>*>(tl, bl);
}
list<Path*>* Splitter::splitvgap(double gap, Path* p)
{
if((p==0)||(p->empty()))
return 0;
list<Path*> *paths = new list<Path*> ();
Path* current = new Path(0,0);
Path::iterator i=p->begin();
Path::iterator last=i;
current->addPointAbsolute(i->first, i->second);
i++;
gap = (gap<0?-gap:gap);
for (;i != p->end(); i++, last++)
{
double dist = i->first - last->first;
dist = (dist<0?-dist:dist);
if (dist >= gap)
{
paths->push_back(current);
current = new Path(0,0);
}
current->addPointAbsolute(i->first, i->second);
}
if(!current->empty())
paths->push_back(current);
return paths;
}
std::pair<double,double> Splitter::intersectBox(
const std::pair<double,double> inside, const std::pair<double,double> outside,
double minX, double maxX, double minY, double maxY)
{
double x,y;
if(outside.first < minX)
{
x = minX;
y = intersectv(x, inside, outside);
if(y>minY && y<maxY) return std::pair<double,double>(x,y);
}
else if(outside.first > maxX)
{
x = maxX;
y = intersectv(x, inside, outside);
if(y>minY && y<maxY) return std::pair<double,double>(x,y);
}
if(outside.second < minY)
{
y = minY;
x = intersecth(y, inside, outside);
return std::pair<double,double>(x,y);
}
else if(outside.second > maxY)
{
y = maxY;
x = intersecth(y, inside, outside);
return std::pair<double,double>(x,y);
}
// outside isn't out of the box, maybe inside is...
if(!inBox(inside,minX,maxX,minY,maxY))
return intersectBox(outside,inside,minX,maxX,minY,maxY);
// Neither outside nor inside are out of the box. Just give back one of
// the points (the first)
return inside;
}
std::auto_ptr< std::list< vdraw::Path > > Splitter::interpToBox(double minX, double maxX, double minY, double maxY, const vdraw::Path& p)
{
using namespace vdraw;
Path::const_iterator i=p.begin(),j=p.begin();
bool inside = inBox(*i,minX,maxX,minY,maxY);
bool lastinside = inside;
double cx, cy;
p.getOrigin(cx,cy);
std::auto_ptr< std::list< Path > > thelist(new std::list<Path>());
Path current(cx,cy);
if(inside)
current.push_back(*i);
i++;
for(;i!=p.end();i++,j++,lastinside=inside)
{
inside = inBox(*i,minX,maxX,minY,maxY);
if(!inside && lastinside)
{
current.push_back(intersectBox(*j,*i,minX,maxX,minY,maxY));
thelist->push_back(current);
current = Path(cx,cy);
}
else if(inside && !lastinside)
{
current.push_back(intersectBox(*i,*j,minX,maxX,minY,maxY));
current.push_back(*i);
}
else if(inside)
{
current.push_back(*i);
}
}
if(current.size() != 0)
thelist->push_back(current);
return thelist;
}
std::auto_ptr< vdraw::Path > Splitter::cropToBox(double minX, double maxX, double minY, double maxY, const vdraw::Path& p)
{
using namespace vdraw;
Path::const_iterator i=p.begin();
bool inside = inBox(*i,minX,maxX,minY,maxY);
std::auto_ptr< Path > newpath(new Path(0,0,p.size()));
if(inside) newpath->push_back(*i);
i++;
for(;i!=p.end();i++)
{
inside = inBox(*i,minX,maxX,minY,maxY);
if(inside) newpath->push_back(*i);
}
newpath->tighten();
return newpath;
}
}
<|endoftext|> |
<commit_before><commit_msg>modify XeXe Cuts<commit_after><|endoftext|> |
<commit_before>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <string>
// Armadillo
#include <armadillo>
// Mantella
#include <mantella>
extern std::string testDirectory;
TEST_CASE("bbob::AttractiveSectorFunction", "") {
for (const auto& numberOfDimensions : {2, 40}) {
mant::bbob::AttractiveSectorFunction<> attractiveSectorFunction(numberOfDimensions);
arma::Mat<double> parameters;
CHECK( parameters.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_parameters_" + std::to_string(numberOfDimensions) +"x10.input") );
arma::Col<double> translation;
CHECK( translation.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_translation_" + std::to_string(numberOfDimensions) +"x1.input") );
arma::Mat<double> rotationR;
CHECK( rotationR.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_randomRotationMatrix_" + std::to_string(numberOfDimensions) + "x" + std::to_string(numberOfDimensions) + "_2.input") );
arma::Mat<double> rotationQ;
CHECK( rotationQ.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_randomRotationMatrix_" + std::to_string(numberOfDimensions) + "x" + std::to_string(numberOfDimensions) + "_1.input") );
arma::Col<double> expected;
CHECK( expected.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/bbob_attractiveSectorFunction_dim" + std::to_string(numberOfDimensions) +".expected") );
attractiveSectorFunction.setObjectiveValueTranslation(0);
attractiveSectorFunction.setParameterTranslation(translation);
attractiveSectorFunction.setParameterRotation(rotationR);
attractiveSectorFunction.setRotationQ(rotationQ);
for (std::size_t n = 0; n < parameters.n_cols; ++n) {
CHECK(attractiveSectorFunction.getObjectiveValue(parameters.col(n)) == Approx(expected.at(n)));
}
}
SECTION("Returns the specified class name.") {
CHECK(mant::bbob::AttractiveSectorFunction<>(5).toString() == "bbob_attractive_sector_function");
}
}
<commit_msg>Updated code format<commit_after>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <string>
// Armadillo
#include <armadillo>
// Mantella
#include <mantella>
extern std::string testDirectory;
TEST_CASE("bbob::AttractiveSectorFunction", "") {
for (const auto& numberOfDimensions : {2, 40}) {
mant::bbob::AttractiveSectorFunction<> attractiveSectorFunction(numberOfDimensions);
arma::Mat<double> parameters;
CHECK( parameters.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_parameters_" + std::to_string(numberOfDimensions) + "x10.input") );
arma::Col<double> translation;
CHECK( translation.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_translation_" + std::to_string(numberOfDimensions) + "x1.input") );
arma::Mat<double> rotationR;
CHECK( rotationR.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_randomRotationMatrix_" + std::to_string(numberOfDimensions) + "x" + std::to_string(numberOfDimensions) + "_2.input") );
arma::Mat<double> rotationQ;
CHECK( rotationQ.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/_randomRotationMatrix_" + std::to_string(numberOfDimensions) + "x" + std::to_string(numberOfDimensions) + "_1.input") );
arma::Col<double> expected;
CHECK( expected.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/bbob_attractiveSectorFunction_dim" + std::to_string(numberOfDimensions) + ".expected") );
attractiveSectorFunction.setObjectiveValueTranslation(0);
attractiveSectorFunction.setParameterTranslation(translation);
attractiveSectorFunction.setParameterRotation(rotationR);
attractiveSectorFunction.setRotationQ(rotationQ);
for (std::size_t n = 0; n < parameters.n_cols; ++n) {
CHECK(attractiveSectorFunction.getObjectiveValue(parameters.col(n)) == Approx(expected.at(n)));
}
}
SECTION("Returns the specified class name.") {
CHECK(mant::bbob::AttractiveSectorFunction<>(5).toString() == "bbob_attractive_sector_function");
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
// TODO(csilv): Remove when dom-ui options is enabled by default.
launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions);
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
ASSERT_EQ(L"Chromium Options", title);
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Go to the options tab via URL.
NavigateToURL(GURL(chrome::kChromeUIOptionsURL));
AssertIsOptionsPage(tab);
}
TEST_F(OptionsUITest, CommandOpensOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
}
// TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521
TEST_F(OptionsUITest, FAILS_CommandAgainGoesBackToOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
// Switch to first tab and run command again.
ASSERT_TRUE(browser->ActivateTab(0));
ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));
ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));
// Ensure the options ui tab is active.
ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms()));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
// TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix.
// http://crbug.com/48521
TEST_F(OptionsUITest, FLAKY_TwoCommandsOneTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
} // namespace
<commit_msg>Make product name dynamic in DOMUI pref unit tests<commit_after>// Copyright (c) 2010 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 "app/l10n_util.h"
#include "base/command_line.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
// TODO(csilv): Remove when dom-ui options is enabled by default.
launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions);
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
std::wstring expected_title =
l10n_util::GetStringF(IDS_OPTIONS_DIALOG_TITLE,
l10n_util::GetString(IDS_PRODUCT_NAME));
ASSERT_EQ(expected_title, title);
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Go to the options tab via URL.
NavigateToURL(GURL(chrome::kChromeUIOptionsURL));
AssertIsOptionsPage(tab);
}
TEST_F(OptionsUITest, CommandOpensOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
}
// TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521
TEST_F(OptionsUITest, FAILS_CommandAgainGoesBackToOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
// Switch to first tab and run command again.
ASSERT_TRUE(browser->ActivateTab(0));
ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));
ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));
// Ensure the options ui tab is active.
ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms()));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
// TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix.
// http://crbug.com/48521
TEST_F(OptionsUITest, FLAKY_TwoCommandsOneTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
} // namespace
<|endoftext|> |
<commit_before><commit_msg>Disabling a couple of UI tests while I investigate.<commit_after><|endoftext|> |
<commit_before><commit_msg>Don't reload whole chrome://extensions page when interacting with single extension (disable/enable...).<commit_after><|endoftext|> |
<commit_before><commit_msg>Small "fix" to make window deallocation similar to window allocation.<commit_after><|endoftext|> |
<commit_before>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <iostream>
#include "tokenan.h"
#include "ident.h"
TokenAn::TokenAn( const char *filename)
{
read_file_contents( filename);
}
void TokenAn::init_file_length( const char *filename)
{
FILE *f = fopen( filename, "r");
fseek( f, 0, SEEK_END);
filelength = ftell( f);
fclose( f);
}
void TokenAn::read_file_contents( const char *filename)
{
init_file_length( filename);
data = new char[filelength + 1];
data[filelength] = '\0';
FILE *f = fopen( filename, "r");
if ( fread( data, 1, filelength, f) != filelength)
throw;
fclose( f);
// for ( int i = 0; i < filelength; i ++)
// printf( "f[%d] = %d\n", i, (int)data[i]);
}
std::vector<TokenAn::Token *> TokenAn::run()
{
ptr = data;
std::vector<TokenAn::Token *> res;
while ( *ptr != '\0')
{
skip_spaces();
if ( *ptr == '%' || isidstart( *ptr))
{
char *id_start = ptr ++;
while ( isidchar( *ptr))
ptr ++;
res.push_back( TokenAn::Token::createId(
std::string( id_start, ptr - id_start)));
}
else if ( *ptr == ',')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_COMMA));
ptr ++;
}
else if ( *ptr == '(')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_LBRACKET));
ptr ++;
}
else if ( *ptr == ')')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_RBRACKET));
ptr ++;
}
else if ( *ptr == ':')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_COLON));
ptr ++;
}
else if ( *ptr == '$' && isdigit( ptr[1]))
{
ptr ++;
int iVal = 0;
sscanf( ptr, "%d", &iVal);
res.push_back( TokenAn::Token::createConstInt( iVal));
while ( isdigit( *ptr))
ptr ++;
}
else if ( *ptr == '\n')
{
res.push_back( TokenAn::Token::createEos());
ptr ++;
}
else if ( *ptr == '\0')
{
res.push_back( TokenAn::Token::createEos());
// res.push_back( TokenAn::Token::createScalar( TOKEN_EOF));
}
else
{
std::cerr << "bad char: " << *ptr <<
" (code: " << (int)*ptr << ")" << std::endl;
assert(0);
}
}
return res;
}
void TokenAn::skip_spaces()
{
while ( *ptr != '\0' && isblank( *ptr))
ptr ++;
}
TokenAn::Token *TokenAn::Token::createId( const std::string id_string)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = TOKEN_ID;
res->sVal = id_string;
return res;
}
TokenAn::Token *TokenAn::Token::createConstInt( int iVal)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = TOKEN_CONST_INT;
res->iVal = iVal;
return res;
}
TokenAn::Token *TokenAn::Token::createScalar( enum TOKEN_TYPE type)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = type;
return res;
}
TokenAn::Token *TokenAn::Token::createEos() // end of line
{
return createScalar( TOKEN_EOS);
}
void TokenAn::Token::dump()
{
switch ( type)
{
case TOKEN_ID: std::cout << sVal; break;
case TOKEN_EOS: std::cout << "--------------- (\\n)"; break;
case TOKEN_COMMA: std::cout << ","; break;
case TOKEN_LBRACKET: std::cout << "("; break;
case TOKEN_RBRACKET: std::cout << ")"; break;
case TOKEN_CONST_INT: std::cout << iVal; break;
case TOKEN_COLON: std::cout << ":"; break;
default: throw;
}
}
<commit_msg>support DOS- and Mac-style line breaks<commit_after>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <iostream>
#include "tokenan.h"
#include "ident.h"
TokenAn::TokenAn( const char *filename)
{
read_file_contents( filename);
}
void TokenAn::init_file_length( const char *filename)
{
FILE *f = fopen( filename, "r");
fseek( f, 0, SEEK_END);
filelength = ftell( f);
fclose( f);
}
void TokenAn::read_file_contents( const char *filename)
{
init_file_length( filename);
data = new char[filelength + 1];
data[filelength] = '\0';
FILE *f = fopen( filename, "r");
if ( fread( data, 1, filelength, f) != filelength)
throw;
fclose( f);
// for ( int i = 0; i < filelength; i ++)
// printf( "f[%d] = %d\n", i, (int)data[i]);
}
std::vector<TokenAn::Token *> TokenAn::run()
{
ptr = data;
std::vector<TokenAn::Token *> res;
while ( *ptr != '\0')
{
skip_spaces();
if ( *ptr == '%' || isidstart( *ptr))
{
char *id_start = ptr ++;
while ( isidchar( *ptr))
ptr ++;
res.push_back( TokenAn::Token::createId(
std::string( id_start, ptr - id_start)));
}
else if ( *ptr == ',')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_COMMA));
ptr ++;
}
else if ( *ptr == '(')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_LBRACKET));
ptr ++;
}
else if ( *ptr == ')')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_RBRACKET));
ptr ++;
}
else if ( *ptr == ':')
{
res.push_back( TokenAn::Token::createScalar( TOKEN_COLON));
ptr ++;
}
else if ( *ptr == '$' && isdigit( ptr[1]))
{
ptr ++;
int iVal = 0;
sscanf( ptr, "%d", &iVal);
res.push_back( TokenAn::Token::createConstInt( iVal));
while ( isdigit( *ptr))
ptr ++;
}
else if ( *ptr == '\r' && ptr[1] == '\n') // DOS
{
res.push_back( TokenAn::Token::createEos());
ptr += 2;
}
else if ( *ptr == '\n' || *ptr == '\r') // Unix, Mac
{
res.push_back( TokenAn::Token::createEos());
ptr ++;
}
else if ( *ptr == '\0')
{
res.push_back( TokenAn::Token::createEos());
// res.push_back( TokenAn::Token::createScalar( TOKEN_EOF));
}
else
{
std::cerr << "bad char: " << *ptr <<
" (code: " << (int)*ptr << ")" << std::endl;
assert(0);
}
}
return res;
}
void TokenAn::skip_spaces()
{
while ( *ptr != '\0' && isblank( *ptr))
ptr ++;
}
TokenAn::Token *TokenAn::Token::createId( const std::string id_string)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = TOKEN_ID;
res->sVal = id_string;
return res;
}
TokenAn::Token *TokenAn::Token::createConstInt( int iVal)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = TOKEN_CONST_INT;
res->iVal = iVal;
return res;
}
TokenAn::Token *TokenAn::Token::createScalar( enum TOKEN_TYPE type)
{
TokenAn::Token *res = new TokenAn::Token;
res->type = type;
return res;
}
TokenAn::Token *TokenAn::Token::createEos() // end of line
{
return createScalar( TOKEN_EOS);
}
void TokenAn::Token::dump()
{
switch ( type)
{
case TOKEN_ID: std::cout << sVal; break;
case TOKEN_EOS: std::cout << "--------------- (\\n)"; break;
case TOKEN_COMMA: std::cout << ","; break;
case TOKEN_LBRACKET: std::cout << "("; break;
case TOKEN_RBRACKET: std::cout << ")"; break;
case TOKEN_CONST_INT: std::cout << iVal; break;
case TOKEN_COLON: std::cout << ":"; break;
default: throw;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* 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 <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-eventdb/EventDBServlet.h"
#include "fnord-eventdb/TableRepository.h"
#include "fnord-eventdb/TableJanitor.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "schemas.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "analytics/AnalyticsServlet.h"
#include "analytics/CTRByPageServlet.h"
#include "analytics/CTRStatsServlet.h"
#include "analytics/CTRByPositionQuery.h"
#include "analytics/CTRByPageQuery.h"
#include "analytics/TopSearchQueriesQuery.h"
#include "analytics/DiscoveryKPIQuery.h"
#include "analytics/DiscoveryCategoryStatsQuery.h"
#include "analytics/AnalyticsQueryEngine.h"
#include "analytics/AnalyticsQueryEngine.h"
using namespace fnord;
std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;
void quit(int n) {
shutdown_sig = true;
fnord::logInfo("cm.repotserver", "Shutting down...");
// FIXPAUL: wait for http server stop...
ev.shutdown();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
/* shutdown hook */
shutdown_sig = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"artifacts path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
WhitelistVFS vfs;
/* start http server */
fnord::thread::ThreadPool tpool;
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
/* sstable servlet */
sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);
/* file servlet */
http::VFSFileServlet file_servlet("/file", &vfs);
http_router.addRouteByPrefixMatch("/file", &file_servlet);
/* add all files to whitelist vfs */
auto dir = flags.getString("artifacts");
FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool {
vfs.registerFile(file, FileUtil::joinPaths(dir, file));
fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
return true;
});
/* eventdb */
auto replica = flags.getString("replica");
eventdb::TableRepository table_repo;
table_repo.addTable(
eventdb::Table::open(
"dawanda_joined_sessions",
replica,
dir,
joinedSessionsSchema()));
eventdb::TableJanitor table_janitor(&table_repo);
table_janitor.start();
eventdb::EventDBServlet eventdb_servlet(&table_repo);
/* analytics */
cm::AnalyticsQueryEngine analytics(8, dir);
cm::AnalyticsServlet analytics_servlet(&analytics);
http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet, &tpool);
http_router.addRouteByPrefixMatch("/eventdb", &eventdb_servlet, &tpool);
analytics.registerQueryFactory("ctr_by_position", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::CTRByPositionQuery(scan, segments);
});
analytics.registerQueryFactory("ctr_by_page", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::CTRByPageQuery(scan, segments);
});
analytics.registerQueryFactory("discovery_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryKPIQuery(
scan,
segments,
query.start_time,
query.end_time);
});
analytics.registerQueryFactory("discovery_category0_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category1",
"queries.category1",
params);
});
analytics.registerQueryFactory("discovery_category1_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category1",
"queries.category2",
params);
});
analytics.registerQueryFactory("discovery_category2_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category2",
"queries.category3",
params);
});
analytics.registerQueryFactory("discovery_category3_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category3",
"queries.category3",
params);
});
analytics.registerQueryFactory("top_search_queries", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::TopSearchQueriesQuery(scan, segments, params);
});
ev.run();
table_janitor.stop();
table_janitor.check();
fnord::logInfo("cm.repotserver", "Exiting...");
return 0;
}
<commit_msg>typo fix<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* 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 <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-eventdb/EventDBServlet.h"
#include "fnord-eventdb/TableRepository.h"
#include "fnord-eventdb/TableJanitor.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "schemas.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "analytics/AnalyticsServlet.h"
#include "analytics/CTRByPageServlet.h"
#include "analytics/CTRStatsServlet.h"
#include "analytics/CTRByPositionQuery.h"
#include "analytics/CTRByPageQuery.h"
#include "analytics/TopSearchQueriesQuery.h"
#include "analytics/DiscoveryKPIQuery.h"
#include "analytics/DiscoveryCategoryStatsQuery.h"
#include "analytics/AnalyticsQueryEngine.h"
#include "analytics/AnalyticsQueryEngine.h"
using namespace fnord;
std::atomic<bool> shutdown_sig;
fnord::thread::EventLoop ev;
void quit(int n) {
shutdown_sig = true;
fnord::logInfo("cm.reportserver", "Shutting down...");
// FIXPAUL: wait for http server stop...
ev.shutdown();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
/* shutdown hook */
shutdown_sig = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"artifacts",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"artifacts path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
WhitelistVFS vfs;
/* start http server */
fnord::thread::ThreadPool tpool;
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
/* sstable servlet */
sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);
/* file servlet */
http::VFSFileServlet file_servlet("/file", &vfs);
http_router.addRouteByPrefixMatch("/file", &file_servlet);
/* add all files to whitelist vfs */
auto dir = flags.getString("artifacts");
FileUtil::ls(dir, [&vfs, &dir] (const String& file) -> bool {
vfs.registerFile(file, FileUtil::joinPaths(dir, file));
fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
return true;
});
/* eventdb */
auto replica = flags.getString("replica");
eventdb::TableRepository table_repo;
table_repo.addTable(
eventdb::Table::open(
"dawanda_joined_sessions",
replica,
dir,
joinedSessionsSchema()));
eventdb::TableJanitor table_janitor(&table_repo);
table_janitor.start();
eventdb::EventDBServlet eventdb_servlet(&table_repo);
/* analytics */
cm::AnalyticsQueryEngine analytics(8, dir);
cm::AnalyticsServlet analytics_servlet(&analytics);
http_router.addRouteByPrefixMatch("/analytics", &analytics_servlet, &tpool);
http_router.addRouteByPrefixMatch("/eventdb", &eventdb_servlet, &tpool);
analytics.registerQueryFactory("ctr_by_position", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::CTRByPositionQuery(scan, segments);
});
analytics.registerQueryFactory("ctr_by_page", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::CTRByPageQuery(scan, segments);
});
analytics.registerQueryFactory("discovery_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryKPIQuery(
scan,
segments,
query.start_time,
query.end_time);
});
analytics.registerQueryFactory("discovery_category0_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category1",
"queries.category1",
params);
});
analytics.registerQueryFactory("discovery_category1_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category1",
"queries.category2",
params);
});
analytics.registerQueryFactory("discovery_category2_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category2",
"queries.category3",
params);
});
analytics.registerQueryFactory("discovery_category3_kpis", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::DiscoveryCategoryStatsQuery(
scan,
segments,
"queries.category3",
"queries.category3",
params);
});
analytics.registerQueryFactory("top_search_queries", [] (
const cm::AnalyticsQuery& query,
const cm::AnalyticsQuery::SubQueryParams params,
const Vector<RefPtr<cm::TrafficSegment>>& segments,
cm::AnalyticsTableScan* scan) {
return new cm::TopSearchQueriesQuery(scan, segments, params);
});
ev.run();
table_janitor.stop();
table_janitor.check();
fnord::logInfo("cm.reportserver", "Exiting...");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.
*/
#define __STDC_CONSTANT_MACROS
#include <cstdlib>
#include <cstdio>
#include "monarch/app/App.h"
#include "monarch/app/AppPluginFactory.h"
#include "monarch/app/ConfigPlugin.h"
#include "monarch/app/LoggingPlugin.h"
#include "monarch/app/MonarchPlugin.h"
#include "monarch/app/KernelPlugin.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/event/EventWaiter.h"
#include "monarch/logging/Logging.h"
#include "monarch/validation/Validation.h"
#include "monarch/app/KernelPlugin.h"
using namespace std;
using namespace monarch::app;
using namespace monarch::config;
using namespace monarch::data::json;
using namespace monarch::event;
using namespace monarch::fiber;
using namespace monarch::io;
using namespace monarch::kernel;
using namespace monarch::logging;
using namespace monarch::modest;
using namespace monarch::net;
using namespace monarch::rt;
namespace v = monarch::validation;
#define PLUGIN_NAME "monarch.app.Kernel"
#define PLUGIN_CL_CFG_ID PLUGIN_NAME ".commandLine"
#define SHUTDOWN_EVENT_TYPE "monarch.kernel.Kernel.shutdown"
#define RESTART_EVENT_TYPE "monarch.kernel.Kernel.restart"
KernelPlugin::KernelPlugin() :
mState(Stopped),
mKernel(NULL)
{
}
KernelPlugin::~KernelPlugin()
{
}
bool KernelPlugin::initMetaConfig(Config& meta)
{
bool rval = monarch::app::AppPlugin::initMetaConfig(meta);
// defaults
if(rval)
{
Config& c =
App::makeMetaConfig(meta, PLUGIN_NAME ".defaults", "defaults")
[ConfigManager::MERGE][PLUGIN_NAME];
// modulePath is an array of module paths
c["modulePath"]->setType(Array);
c["env"] = true;
c["printModuleVersions"] = false;
c["maxThreadCount"] = (uint32_t)100;
c["maxConnectionCount"] = (uint32_t)100;
// waitEvents is a map of arrays of event ids. The map keys should be
// unique such as plugin ids. The kernel will wait for all these events
// to occur before exiting. (Some special kernel events also can cause
// a quicker exit.)
c["waitEvents"]->setType(Map);
}
// command line options
if(rval)
{
Config& c = App::makeMetaConfig(
meta, PLUGIN_CL_CFG_ID, "command line", "options")
[ConfigManager::APPEND][PLUGIN_NAME];
c["modulePath"]->setType(Array);
}
return rval;
}
DynamicObject KernelPlugin::getCommandLineSpecs()
{
DynamicObject spec;
spec["help"] =
"Module options:\n"
" -m, --module-path PATH\n"
" A colon separated list of modules or directories where\n"
" modules are stored. May be specified multiple times.\n"
" Loaded after modules in MONARCH_MODULE_PATH.\n"
" --no-module-path-env\n"
" Disable MONARCH_MODULE_PATH.\n"
" --module-versions\n"
" Prints the module versions.\n"
"\n";
DynamicObject opt;
Config& options = getApp()->getMetaConfig()
["options"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE];
Config& configOptions = options[PLUGIN_NAME];
opt = spec["options"]->append();
opt["short"] = "-m";
opt["long"] = "--module-path";
opt["append"] = configOptions["modulePath"];
opt["argError"] = "No path specified.";
opt = spec["options"]->append();
opt["long"] = "--no-module-path-env";
opt["setFalse"]["root"] = configOptions;
opt["setFalse"]["path"] = "env";
opt = spec["options"]->append();
opt["long"] = "--module-versions";
opt["setTrue"]["root"] = configOptions;
opt["setTrue"]["path"] = "printModuleVersions";
DynamicObject specs = AppPlugin::getCommandLineSpecs();
specs->append(spec);
return specs;
}
/**
* Validates the wait events.
*
* @param waitEvents the wait events.
*
* @return true if successful, false if an exception occurred.
*/
static bool _validateWaitEvents(DynamicObject& waitEvents)
{
bool rval = false;
// create validator for node configuration
v::ValidatorRef v = new v::All(
new v::Type(Array),
new v::Each(
new v::Map(
"id", new v::Type(String),
"type", new v::Type(String),
NULL)),
NULL);
rval = v->isValid(waitEvents);
if(!rval)
{
ExceptionRef e = new Exception(
"Invalid AppPlugin wait event configuration.",
"monarch.app.Kernel.InvalidWaitEvents");
e->getDetails()["waitEvents"] = waitEvents;
Exception::push(e);
}
return rval;
}
bool KernelPlugin::didParseCommandLine()
{
bool rval = AppPlugin::didParseCommandLine();
// process flags
// only done after bootstrap mode so that all modules info is available
if(rval && getApp()->getMode() != App::BOOTSTRAP)
{
Config& cfg = getApp()->getMetaConfig()
["options"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE][PLUGIN_NAME];
if(cfg->hasMember("printModuleVersions") &&
cfg["printModuleVersions"]->getBoolean())
{
// FIXME: print out module info
/*
printf("%s v%s\n", ...);
// Raise known exit exception.
ExceptionRef e = new Exception(
"Module versions printed.",
"monarch.app.Exit", EXIT_SUCCESS);
Exception::set(e);
rval = false;
*/
ExceptionRef e = new Exception(
"Not implemented.",
"monarch.app.NotImplemented", EXIT_FAILURE);
Exception::set(e);
rval = false;
}
}
return rval;
}
bool KernelPlugin::runApp()
{
bool rval = true;
mState = Starting;
while(mState == Starting || mState == Restarting)
{
// [re]start the node
MO_CAT_INFO(MO_KERNEL_CAT,
(mState == Restarting) ?
"Restarting kernel..." : "Starting kernel...");
// get kernel config
Config cfg = getApp()->getConfig()[PLUGIN_NAME];
App* app = new App;
// create and start kernel
mKernel = new MicroKernel();
mKernel->setConfigManager(app->getConfigManager(), false);
mKernel->setFiberScheduler(new FiberScheduler(), true);
mKernel->setFiberMessageCenter(new FiberMessageCenter(), true);
mKernel->setEventController(new EventController(), true);
mKernel->setEventDaemon(new EventDaemon(), true);
mKernel->setServer(new Server(), true);
// set thread and connection limits
mKernel->setMaxAuxiliaryThreads(cfg["maxThreadCount"]->getUInt32());
mKernel->setMaxServerConnections(cfg["maxConnectionCount"]->getUInt32());
rval = mKernel->start();
if(rval)
{
rval =
mKernel->loadModule(
createMonarchPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createConfigPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createLoggingPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createKernelPluginFactory, freeAppPluginFactory);
// FIXME: in did load configs should add env paths to config
// Collect all module paths so they can be loaded in bulk.
// This helps to avoid issues with needing to specify load order
// explicitly.
FileList modulePaths;
ConfigIterator mpi = cfg["modulePath"].getIterator();
while(rval && mpi->hasNext())
{
const char* path = mpi->next()->getString();
FileList pathList = File::parsePath(path);
modulePaths->concat(*pathList);
}
// load all module paths at once
rval = mKernel->loadModules(modulePaths);
if(!rval)
{
MO_CAT_INFO(MO_KERNEL_CAT, "Stopping kernel due to exception.");
mKernel->stop();
}
}
mState = Running;
if(rval)
{
MO_CAT_INFO(MO_KERNEL_CAT, "Kernel started.");
// send ready event
{
Event e;
e["type"] = "monarch.kernel.Kernel.ready";
mKernel->getEventController()->schedule(e);
}
if(rval)
{
{
// create AppPlugins from all loaded AppPluginFactories
MicroKernel::ModuleApiList factories;
mKernel->getModuleApisByType(
"monarch.app.AppPluginFactory", factories);
for(MicroKernel::ModuleApiList::iterator i = factories.begin();
rval && i != factories.end(); i++)
{
ModuleId id = dynamic_cast<Module*>(*i)->getId();
AppPluginFactory* f = dynamic_cast<AppPluginFactory*>(*i);
AppPluginRef p = f->createAppPlugin();
MO_CAT_INFO(MO_KERNEL_CAT,
"Adding AppPlugin to App: %s v%s.", id.name, id.version);
rval = app->addPlugin(p);
}
}
// waiter for kernel and plugin events
// used to wait for plugins to complete or for kernel control events
EventWaiter waiter(mKernel->getEventController());
// wait for generic kernel events
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: kernel waiting on \"%s\"", SHUTDOWN_EVENT_TYPE);
waiter.start(SHUTDOWN_EVENT_TYPE);
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: kernel waiting on \"%s\"", RESTART_EVENT_TYPE);
waiter.start(RESTART_EVENT_TYPE);
// make a map of event types to waiting ids
DynamicObject waitEvents;
waitEvents->setType(Map);
{
// array of events and counts
DynamicObject appWaitEvents = app->getWaitEvents();
rval = _validateWaitEvents(appWaitEvents);
DynamicObjectIterator i = appWaitEvents.getIterator();
while(rval && i->hasNext())
{
DynamicObject next = i->next();
const char* id = next["id"]->getString();
const char* type = next["type"]->getString();
if(!waitEvents->hasMember(type))
{
DynamicObject newInfo;
newInfo["ids"]->setType(Array);
waitEvents[type] = newInfo;
}
DynamicObject newId;
newId = id;
waitEvents[type]["ids"]->append(newId);
// start waiting for event
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: \"%s\" waiting on \"%s\"", id, type);
waiter.start(type);
}
}
int status;
if(rval)
{
// run sub app
status = app->start(getApp()->getCommandLine());
rval = (status == EXIT_SUCCESS);
}
// wait for events if app started successfully
// checking for exception in case of success with an exit exception
if(rval && !Exception::isSet())
{
while(mState == Running && waitEvents->length() != 0)
{
waiter.waitForEvent();
Event e = waiter.popEvent();
const char* type = e["type"]->getString();
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter got event: %s", type);
if(strcmp(SHUTDOWN_EVENT_TYPE, type) == 0)
{
mState = Stopping;
}
else if(strcmp(RESTART_EVENT_TYPE, type) == 0)
{
mState = Restarting;
}
else
{
if(waitEvents->hasMember(type))
{
waitEvents->removeMember(type);
}
}
}
mState = Stopping;
}
if(!rval)
{
getApp()->setExitStatus(app->getExitStatus());
}
}
delete app;
app = NULL;
// FIXME: actually stopping microkernel, not just node
// stop node
MO_CAT_INFO(MO_KERNEL_CAT,
(mState == Restarting) ?
"Stopping kernel for restart..." :
"Stopping kernel...");
mKernel->stop();
MO_CAT_INFO(MO_KERNEL_CAT, "Kernel stopped.");
// set to stopped unless restarting
mState = (mState == Stopping) ? Stopped : mState;
}
else
{
MO_CAT_ERROR(MO_KERNEL_CAT, "Kernel start failed: %s",
JsonWriter::writeToString(Exception::getAsDynamicObject()).c_str());
}
if(app != NULL)
{
delete app;
app = NULL;
}
// clean up kernel
delete mKernel;
mKernel = NULL;
}
return rval;
}
bool KernelPlugin::run()
{
bool rval = AppPlugin::run();
if(rval && getApp()->getMode() == App::BOOTSTRAP)
{
rval = runApp();
}
return rval;
}
class KernelPluginFactory :
public AppPluginFactory
{
public:
KernelPluginFactory() :
AppPluginFactory(PLUGIN_NAME, "1.0")
{
addDependency("monarch.app.Config", "1.0");
addDependency("monarch.app.Logging", "1.0");
}
virtual ~KernelPluginFactory() {}
virtual AppPluginRef createAppPlugin()
{
return new KernelPlugin();
}
};
Module* monarch::app::createKernelPluginFactory()
{
return new KernelPluginFactory();
}
<commit_msg>Fixed command line option handling.<commit_after>/*
* Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.
*/
#define __STDC_CONSTANT_MACROS
#include <cstdlib>
#include <cstdio>
#include "monarch/app/App.h"
#include "monarch/app/AppPluginFactory.h"
#include "monarch/app/ConfigPlugin.h"
#include "monarch/app/LoggingPlugin.h"
#include "monarch/app/MonarchPlugin.h"
#include "monarch/app/KernelPlugin.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/event/EventWaiter.h"
#include "monarch/logging/Logging.h"
#include "monarch/validation/Validation.h"
#include "monarch/app/KernelPlugin.h"
using namespace std;
using namespace monarch::app;
using namespace monarch::config;
using namespace monarch::data::json;
using namespace monarch::event;
using namespace monarch::fiber;
using namespace monarch::io;
using namespace monarch::kernel;
using namespace monarch::logging;
using namespace monarch::modest;
using namespace monarch::net;
using namespace monarch::rt;
namespace v = monarch::validation;
#define PLUGIN_NAME "monarch.app.Kernel"
#define PLUGIN_CL_CFG_ID PLUGIN_NAME ".commandLine"
#define SHUTDOWN_EVENT_TYPE "monarch.kernel.Kernel.shutdown"
#define RESTART_EVENT_TYPE "monarch.kernel.Kernel.restart"
KernelPlugin::KernelPlugin() :
mState(Stopped),
mKernel(NULL)
{
}
KernelPlugin::~KernelPlugin()
{
}
bool KernelPlugin::initMetaConfig(Config& meta)
{
bool rval = monarch::app::AppPlugin::initMetaConfig(meta);
// defaults
if(rval)
{
Config& c =
App::makeMetaConfig(meta, PLUGIN_NAME ".defaults", "defaults")
[ConfigManager::MERGE][PLUGIN_NAME];
// modulePath is an array of module paths
c["modulePath"]->setType(Array);
c["env"] = true;
c["printModuleVersions"] = false;
c["maxThreadCount"] = (uint32_t)100;
c["maxConnectionCount"] = (uint32_t)100;
// waitEvents is a map of arrays of event ids. The map keys should be
// unique such as plugin ids. The kernel will wait for all these events
// to occur before exiting. (Some special kernel events also can cause
// a quicker exit.)
c["waitEvents"]->setType(Map);
}
// command line options
if(rval)
{
Config c = App::makeMetaConfig(
meta, PLUGIN_CL_CFG_ID, "command line", "options");
c[ConfigManager::APPEND][PLUGIN_NAME]["modulePath"]->setType(Array);
c[ConfigManager::MERGE][PLUGIN_NAME]->setType(Map);
}
return rval;
}
DynamicObject KernelPlugin::getCommandLineSpecs()
{
DynamicObject spec;
spec["help"] =
"Module options:\n"
" -m, --module-path PATH\n"
" A colon separated list of modules or directories where\n"
" modules are stored. May be specified multiple times.\n"
" Loaded after modules in MONARCH_MODULE_PATH.\n"
" --no-module-path-env\n"
" Disable MONARCH_MODULE_PATH.\n"
" --module-versions\n"
" Prints the module versions.\n"
"\n";
DynamicObject opt;
Config& options = getApp()->getMetaConfig()["options"][PLUGIN_CL_CFG_ID];
Config& oa = options[ConfigManager::APPEND];
Config& om = options[ConfigManager::MERGE];
opt = spec["options"]->append();
opt["short"] = "-m";
opt["long"] = "--module-path";
opt["append"]["root"] = oa;
opt["append"]["path"] = PLUGIN_NAME ".modulePath";
opt["argError"] = "No path specified.";
opt = spec["options"]->append();
opt["long"] = "--no-module-path-env";
opt["setFalse"]["root"] = om;
opt["setFalse"]["path"] = PLUGIN_NAME ".env";
opt = spec["options"]->append();
opt["long"] = "--module-versions";
opt["setTrue"]["root"] = om;
opt["setTrue"]["path"] = PLUGIN_NAME ".printModuleVersions";
DynamicObject specs = AppPlugin::getCommandLineSpecs();
specs->append(spec);
return specs;
}
/**
* Validates the wait events.
*
* @param waitEvents the wait events.
*
* @return true if successful, false if an exception occurred.
*/
static bool _validateWaitEvents(DynamicObject& waitEvents)
{
bool rval = false;
// create validator for node configuration
v::ValidatorRef v = new v::All(
new v::Type(Array),
new v::Each(
new v::Map(
"id", new v::Type(String),
"type", new v::Type(String),
NULL)),
NULL);
rval = v->isValid(waitEvents);
if(!rval)
{
ExceptionRef e = new Exception(
"Invalid AppPlugin wait event configuration.",
"monarch.app.Kernel.InvalidWaitEvents");
e->getDetails()["waitEvents"] = waitEvents;
Exception::push(e);
}
return rval;
}
bool KernelPlugin::didParseCommandLine()
{
bool rval = AppPlugin::didParseCommandLine();
// process flags
// only done after bootstrap mode so that all modules info is available
if(rval && getApp()->getMode() != App::BOOTSTRAP)
{
Config& cfg = getApp()->getMetaConfig()
["options"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE][PLUGIN_NAME];
if(cfg->hasMember("printModuleVersions") &&
cfg["printModuleVersions"]->getBoolean())
{
// FIXME: print out module info
/*
printf("%s v%s\n", ...);
// Raise known exit exception.
ExceptionRef e = new Exception(
"Module versions printed.",
"monarch.app.Exit", EXIT_SUCCESS);
Exception::set(e);
rval = false;
*/
ExceptionRef e = new Exception(
"Not implemented.",
"monarch.app.NotImplemented", EXIT_FAILURE);
Exception::set(e);
rval = false;
}
}
return rval;
}
bool KernelPlugin::runApp()
{
bool rval = true;
mState = Starting;
while(mState == Starting || mState == Restarting)
{
// [re]start the node
MO_CAT_INFO(MO_KERNEL_CAT,
(mState == Restarting) ?
"Restarting kernel..." : "Starting kernel...");
// get kernel config
Config cfg = getApp()->getConfig()[PLUGIN_NAME];
App* app = new App;
// create and start kernel
mKernel = new MicroKernel();
mKernel->setConfigManager(app->getConfigManager(), false);
mKernel->setFiberScheduler(new FiberScheduler(), true);
mKernel->setFiberMessageCenter(new FiberMessageCenter(), true);
mKernel->setEventController(new EventController(), true);
mKernel->setEventDaemon(new EventDaemon(), true);
mKernel->setServer(new Server(), true);
// set thread and connection limits
mKernel->setMaxAuxiliaryThreads(cfg["maxThreadCount"]->getUInt32());
mKernel->setMaxServerConnections(cfg["maxConnectionCount"]->getUInt32());
rval = mKernel->start();
if(rval)
{
rval =
mKernel->loadModule(
createMonarchPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createConfigPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createLoggingPluginFactory, freeAppPluginFactory) &&
mKernel->loadModule(
createKernelPluginFactory, freeAppPluginFactory);
// FIXME: in did load configs should add env paths to config
// Collect all module paths so they can be loaded in bulk.
// This helps to avoid issues with needing to specify load order
// explicitly.
FileList modulePaths;
ConfigIterator mpi = cfg["modulePath"].getIterator();
while(rval && mpi->hasNext())
{
const char* path = mpi->next()->getString();
FileList pathList = File::parsePath(path);
modulePaths->concat(*pathList);
}
// load all module paths at once
rval = mKernel->loadModules(modulePaths);
if(!rval)
{
MO_CAT_INFO(MO_KERNEL_CAT, "Stopping kernel due to exception.");
mKernel->stop();
}
}
mState = Running;
if(rval)
{
MO_CAT_INFO(MO_KERNEL_CAT, "Kernel started.");
// send ready event
{
Event e;
e["type"] = "monarch.kernel.Kernel.ready";
mKernel->getEventController()->schedule(e);
}
if(rval)
{
{
// create AppPlugins from all loaded AppPluginFactories
MicroKernel::ModuleApiList factories;
mKernel->getModuleApisByType(
"monarch.app.AppPluginFactory", factories);
for(MicroKernel::ModuleApiList::iterator i = factories.begin();
rval && i != factories.end(); i++)
{
ModuleId id = dynamic_cast<Module*>(*i)->getId();
AppPluginFactory* f = dynamic_cast<AppPluginFactory*>(*i);
AppPluginRef p = f->createAppPlugin();
MO_CAT_INFO(MO_KERNEL_CAT,
"Adding AppPlugin to App: %s v%s.", id.name, id.version);
rval = app->addPlugin(p);
}
}
// waiter for kernel and plugin events
// used to wait for plugins to complete or for kernel control events
EventWaiter waiter(mKernel->getEventController());
// wait for generic kernel events
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: kernel waiting on \"%s\"", SHUTDOWN_EVENT_TYPE);
waiter.start(SHUTDOWN_EVENT_TYPE);
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: kernel waiting on \"%s\"", RESTART_EVENT_TYPE);
waiter.start(RESTART_EVENT_TYPE);
// make a map of event types to waiting ids
DynamicObject waitEvents;
waitEvents->setType(Map);
{
// array of events and counts
DynamicObject appWaitEvents = app->getWaitEvents();
rval = _validateWaitEvents(appWaitEvents);
DynamicObjectIterator i = appWaitEvents.getIterator();
while(rval && i->hasNext())
{
DynamicObject next = i->next();
const char* id = next["id"]->getString();
const char* type = next["type"]->getString();
if(!waitEvents->hasMember(type))
{
DynamicObject newInfo;
newInfo["ids"]->setType(Array);
waitEvents[type] = newInfo;
}
DynamicObject newId;
newId = id;
waitEvents[type]["ids"]->append(newId);
// start waiting for event
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter: \"%s\" waiting on \"%s\"", id, type);
waiter.start(type);
}
}
int status;
if(rval)
{
// run sub app
status = app->start(getApp()->getCommandLine());
rval = (status == EXIT_SUCCESS);
}
// wait for events if app started successfully
// checking for exception in case of success with an exit exception
if(rval && !Exception::isSet())
{
while(mState == Running && waitEvents->length() != 0)
{
waiter.waitForEvent();
Event e = waiter.popEvent();
const char* type = e["type"]->getString();
MO_CAT_INFO(MO_KERNEL_CAT,
"EventWaiter got event: %s", type);
if(strcmp(SHUTDOWN_EVENT_TYPE, type) == 0)
{
mState = Stopping;
}
else if(strcmp(RESTART_EVENT_TYPE, type) == 0)
{
mState = Restarting;
}
else
{
if(waitEvents->hasMember(type))
{
waitEvents->removeMember(type);
}
}
}
mState = Stopping;
}
if(!rval)
{
getApp()->setExitStatus(app->getExitStatus());
}
}
delete app;
app = NULL;
// FIXME: actually stopping microkernel, not just node
// stop node
MO_CAT_INFO(MO_KERNEL_CAT,
(mState == Restarting) ?
"Stopping kernel for restart..." :
"Stopping kernel...");
mKernel->stop();
MO_CAT_INFO(MO_KERNEL_CAT, "Kernel stopped.");
// set to stopped unless restarting
mState = (mState == Stopping) ? Stopped : mState;
}
else
{
MO_CAT_ERROR(MO_KERNEL_CAT, "Kernel start failed: %s",
JsonWriter::writeToString(Exception::getAsDynamicObject()).c_str());
}
if(app != NULL)
{
delete app;
app = NULL;
}
// clean up kernel
delete mKernel;
mKernel = NULL;
}
return rval;
}
bool KernelPlugin::run()
{
bool rval = AppPlugin::run();
if(rval && getApp()->getMode() == App::BOOTSTRAP)
{
rval = runApp();
}
return rval;
}
class KernelPluginFactory :
public AppPluginFactory
{
public:
KernelPluginFactory() :
AppPluginFactory(PLUGIN_NAME, "1.0")
{
addDependency("monarch.app.Config", "1.0");
addDependency("monarch.app.Logging", "1.0");
}
virtual ~KernelPluginFactory() {}
virtual AppPluginRef createAppPlugin()
{
return new KernelPlugin();
}
};
Module* monarch::app::createKernelPluginFactory()
{
return new KernelPluginFactory();
}
<|endoftext|> |
<commit_before>#include <QColorDialog>
#include <qlayout/qeffectdescription.h>
#include <qlayout/qeffectdescriptionedit.h>
QEffectDescriptionEdit::QEffectDescriptionEdit(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
setupUi(this);
}
QEffectDescriptionEdit::~QEffectDescriptionEdit()
{
}
void setColor(QLabel *widget, const QColor& color)
{
QPalette palette(color);
palette.setColor(QPalette::Base, color);
palette.setColor(QPalette::Background, color);
palette.setColor(QPalette::Window, color);
palette.setColor(QPalette::Foreground, color);
widget->setPalette(palette);
QImage image(widget->rect().size(), QImage::Format_ARGB32);
image.fill(color);
QPixmap pix = QPixmap::fromImage(image);
widget->setPixmap(pix);
}
void QEffectDescriptionEdit::initFrom(const QEffectDescription* other, bool multiple)
{
setColor(txtColorEnd, other->getEndColor());
setColor(txtColorStart, other->getStartColor());
if (multiple)
txtObjectName->setText("");
else
txtObjectName->setText(other->getCN().c_str());
txtScaleStart->setText(QString::number(other->getScaleStart()));
txtScaleEnd->setText(QString::number(other->getScaleEnd()));
switch(other->getMode())
{
case QEffectDescription::Colorize:
radColorize->setChecked(true);
break;
case QEffectDescription::DropShadow:
radShadow->setChecked(true);
break;
default:
case QEffectDescription::Scale:
radScale->setChecked(true);
break;
}
}
void QEffectDescriptionEdit::saveTo(QEffectDescription* other, bool /* multiple*/)
{
other->setStartColor(txtColorStart->palette().color(QPalette::Background));
other->setEndColor(txtColorEnd->palette().color(QPalette::Background));
other->setScaleStart(txtScaleStart->text().toDouble());
other->setScaleEnd(txtScaleEnd->text().toDouble());
if (radColorize->isChecked())
other->setMode(QEffectDescription::Colorize);
else if (radShadow->isChecked())
other->setMode(QEffectDescription::DropShadow);
else
other->setMode(QEffectDescription::Scale);
}
QEffectDescription* QEffectDescriptionEdit::toDescription() const
{
QEffectDescription *result = new QEffectDescription(txtObjectName->text().toStdString());
result->setStartColor(txtColorStart->palette().color(QPalette::Background));
result->setEndColor(txtColorEnd->palette().color(QPalette::Background));
result->setScaleStart(txtScaleStart->text().toDouble());
result->setScaleEnd(txtScaleEnd->text().toDouble());
if (radColorize->isChecked())
result->setMode(QEffectDescription::Colorize);
else if (radShadow->isChecked())
result->setMode(QEffectDescription::DropShadow);
else
result->setMode(QEffectDescription::Scale);
return result;
}
void QEffectDescriptionEdit::slotModeChanged()
{
}
void QEffectDescriptionEdit::slotScaleEndChanged(QString)
{
}
void QEffectDescriptionEdit::slotScaleStartChanged(QString)
{
}
void QEffectDescriptionEdit::slotSelectObject()
{
}
void QEffectDescriptionEdit::slotSelectColorEnd()
{
setColor(txtColorEnd, QColorDialog::getColor(txtColorEnd->palette().color(QPalette::Background), this));
}
void QEffectDescriptionEdit::slotSelectColorStart()
{
setColor(txtColorStart, QColorDialog::getColor(txtColorStart->palette().color(QPalette::Background), this));
}
<commit_msg>- fix compile error on qt 4.7<commit_after>// Copyright (C) 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <QColorDialog>
#include <qlayout/qeffectdescription.h>
#include <qlayout/qeffectdescriptionedit.h>
#if QT_VERSION < 40800
#include <QPainter>
#endif
QEffectDescriptionEdit::QEffectDescriptionEdit(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
setupUi(this);
}
QEffectDescriptionEdit::~QEffectDescriptionEdit()
{
}
void setColor(QLabel *widget, const QColor& color)
{
QPalette palette(color);
palette.setColor(QPalette::Base, color);
palette.setColor(QPalette::Background, color);
palette.setColor(QPalette::Window, color);
palette.setColor(QPalette::Foreground, color);
widget->setPalette(palette);
QImage image(widget->rect().size(), QImage::Format_ARGB32);
#if QT_VERSION >= 40800
image.fill(color);
#else
QPainter painter(&image);
painter.fillRect(widget->rect(), color);
#endif
QPixmap pix = QPixmap::fromImage(image);
widget->setPixmap(pix);
}
void QEffectDescriptionEdit::initFrom(const QEffectDescription* other, bool multiple)
{
setColor(txtColorEnd, other->getEndColor());
setColor(txtColorStart, other->getStartColor());
if (multiple)
txtObjectName->setText("");
else
txtObjectName->setText(other->getCN().c_str());
txtScaleStart->setText(QString::number(other->getScaleStart()));
txtScaleEnd->setText(QString::number(other->getScaleEnd()));
switch (other->getMode())
{
case QEffectDescription::Colorize:
radColorize->setChecked(true);
break;
case QEffectDescription::DropShadow:
radShadow->setChecked(true);
break;
default:
case QEffectDescription::Scale:
radScale->setChecked(true);
break;
}
}
void QEffectDescriptionEdit::saveTo(QEffectDescription* other, bool /* multiple*/)
{
other->setStartColor(txtColorStart->palette().color(QPalette::Background));
other->setEndColor(txtColorEnd->palette().color(QPalette::Background));
other->setScaleStart(txtScaleStart->text().toDouble());
other->setScaleEnd(txtScaleEnd->text().toDouble());
if (radColorize->isChecked())
other->setMode(QEffectDescription::Colorize);
else if (radShadow->isChecked())
other->setMode(QEffectDescription::DropShadow);
else
other->setMode(QEffectDescription::Scale);
}
QEffectDescription* QEffectDescriptionEdit::toDescription() const
{
QEffectDescription *result = new QEffectDescription(txtObjectName->text().toStdString());
result->setStartColor(txtColorStart->palette().color(QPalette::Background));
result->setEndColor(txtColorEnd->palette().color(QPalette::Background));
result->setScaleStart(txtScaleStart->text().toDouble());
result->setScaleEnd(txtScaleEnd->text().toDouble());
if (radColorize->isChecked())
result->setMode(QEffectDescription::Colorize);
else if (radShadow->isChecked())
result->setMode(QEffectDescription::DropShadow);
else
result->setMode(QEffectDescription::Scale);
return result;
}
void QEffectDescriptionEdit::slotModeChanged()
{
}
void QEffectDescriptionEdit::slotScaleEndChanged(QString)
{
}
void QEffectDescriptionEdit::slotScaleStartChanged(QString)
{
}
void QEffectDescriptionEdit::slotSelectObject()
{
}
void QEffectDescriptionEdit::slotSelectColorEnd()
{
setColor(txtColorEnd, QColorDialog::getColor(txtColorEnd->palette().color(QPalette::Background), this));
}
void QEffectDescriptionEdit::slotSelectColorStart()
{
setColor(txtColorStart, QColorDialog::getColor(txtColorStart->palette().color(QPalette::Background), this));
}
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to [email protected]
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author$
Version : $Revision$
Location : $URL$
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include <iostream>
#include "LiveSupport/Widgets/WidgetFactory.h"
#include "LiveSupport/Widgets/Colors.h"
#include "LiveSupport/Widgets/Button.h"
#include "LiveSupport/Widgets/DialogWindow.h"
using namespace LiveSupport::Widgets;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
DialogWindow :: DialogWindow (Ptr<Glib::ustring>::Ref message,
int buttonTypes,
Ptr<ResourceBundle>::Ref bundle)
throw ()
: WhiteWindow("",
Colors::White,
WidgetFactory::getInstance()->getWhiteWindowCorners(),
WhiteWindow::isModal),
LocalizedObject(bundle)
{
Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();
Gtk::Label * messageLabel = Gtk::manage(new Gtk::Label(*message,
Gtk::ALIGN_CENTER,
Gtk::ALIGN_CENTER ));
messageLabel->set_justify(Gtk::JUSTIFY_CENTER);
Gtk::Box * messageBox = Gtk::manage(new Gtk::HBox);
messageBox->pack_start(*messageLabel, true, false, 10);
Gtk::ButtonBox * buttonBox = Gtk::manage(new Gtk::HButtonBox(
Gtk::BUTTONBOX_END, 5));
int buttonCount = 0;
try {
if (buttonTypes & cancelButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("cancelButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onCancelButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & noButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("noButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onNoButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & yesButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("yesButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onYesButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & okButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("okButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onOkButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
Gtk::Box * bottomBox = Gtk::manage(new Gtk::HBox);
bottomBox->pack_start(*buttonBox, true, true, 10);
Gtk::Box * layout = Gtk::manage(new Gtk::VBox);
layout->pack_start(*messageBox, true, false, 5);
layout->pack_start(*bottomBox, false, false, 0);
set_default_size(100*buttonCount + 50, 120);
property_window_position().set_value(Gtk::WIN_POS_CENTER);
add(*layout);
}
/*------------------------------------------------------------------------------
* Destructor.
*----------------------------------------------------------------------------*/
DialogWindow :: ~DialogWindow (void) throw ()
{
}
/*------------------------------------------------------------------------------
* Event handler for the Cancel button clicked
*----------------------------------------------------------------------------*/
void
DialogWindow :: onCancelButtonClicked(void) throw ()
{
buttonClicked = cancelButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the No button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onNoButtonClicked(void) throw ()
{
buttonClicked = noButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the Yes button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onYesButtonClicked(void) throw ()
{
buttonClicked = yesButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the OK button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onOkButtonClicked(void) throw ()
{
buttonClicked = okButton;
hide();
}
/*------------------------------------------------------------------------------
* Show the window and return the button clicked.
*----------------------------------------------------------------------------*/
DialogWindow::ButtonType
DialogWindow :: run(void) throw ()
{
show_all();
Gtk::Main::run(*this);
return buttonClicked;
}
<commit_msg>fixing the last part of #1755 (do not show dialog windows in the task bar as "untitled window") -- except for nicer icon images, which is now #1774<commit_after>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to [email protected]
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author$
Version : $Revision$
Location : $URL$
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include <iostream>
#include "LiveSupport/Widgets/WidgetFactory.h"
#include "LiveSupport/Widgets/Colors.h"
#include "LiveSupport/Widgets/Button.h"
#include "LiveSupport/Widgets/DialogWindow.h"
using namespace LiveSupport::Widgets;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
DialogWindow :: DialogWindow (Ptr<Glib::ustring>::Ref message,
int buttonTypes,
Ptr<ResourceBundle>::Ref bundle)
throw ()
: WhiteWindow("",
Colors::White,
WidgetFactory::getInstance()->getWhiteWindowCorners(),
WhiteWindow::isModal),
LocalizedObject(bundle)
{
Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();
Gtk::Label * messageLabel = Gtk::manage(new Gtk::Label(*message,
Gtk::ALIGN_CENTER,
Gtk::ALIGN_CENTER ));
messageLabel->set_justify(Gtk::JUSTIFY_CENTER);
Gtk::Box * messageBox = Gtk::manage(new Gtk::HBox);
messageBox->pack_start(*messageLabel, true, false, 10);
Gtk::ButtonBox * buttonBox = Gtk::manage(new Gtk::HButtonBox(
Gtk::BUTTONBOX_END, 5));
int buttonCount = 0;
try {
if (buttonTypes & cancelButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("cancelButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onCancelButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & noButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("noButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onNoButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & yesButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("yesButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onYesButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
if (buttonTypes & okButton) {
Button * button = Gtk::manage(widgetFactory->createButton(
*getResourceUstring("okButtonLabel") ));
button->signal_clicked().connect(sigc::mem_fun(*this,
&DialogWindow::onOkButtonClicked));
buttonBox->pack_start(*button);
++buttonCount;
}
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
Gtk::Box * bottomBox = Gtk::manage(new Gtk::HBox);
bottomBox->pack_start(*buttonBox, true, true, 10);
Gtk::Box * layout = Gtk::manage(new Gtk::VBox);
layout->pack_start(*messageBox, true, false, 5);
layout->pack_start(*bottomBox, false, false, 0);
set_default_size(100*buttonCount + 50, 120);
property_window_position().set_value(Gtk::WIN_POS_CENTER);
set_skip_taskbar_hint(true); // do not show in the task bar
add(*layout);
}
/*------------------------------------------------------------------------------
* Destructor.
*----------------------------------------------------------------------------*/
DialogWindow :: ~DialogWindow (void) throw ()
{
}
/*------------------------------------------------------------------------------
* Event handler for the Cancel button clicked
*----------------------------------------------------------------------------*/
void
DialogWindow :: onCancelButtonClicked(void) throw ()
{
buttonClicked = cancelButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the No button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onNoButtonClicked(void) throw ()
{
buttonClicked = noButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the Yes button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onYesButtonClicked(void) throw ()
{
buttonClicked = yesButton;
hide();
}
/*------------------------------------------------------------------------------
* Event handler for the OK button clicked.
*----------------------------------------------------------------------------*/
void
DialogWindow :: onOkButtonClicked(void) throw ()
{
buttonClicked = okButton;
hide();
}
/*------------------------------------------------------------------------------
* Show the window and return the button clicked.
*----------------------------------------------------------------------------*/
DialogWindow::ButtonType
DialogWindow :: run(void) throw ()
{
show_all();
Gtk::Main::run(*this);
return buttonClicked;
}
<|endoftext|> |
<commit_before>/*
* TLS echo server using BSD sockets
* (C) 2014 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "apps.h"
#if defined(BOTAN_HAS_TLS) \
&& defined(BOTAN_HAS_DSA) \
&& !defined(BOTAN_TARGET_OS_IS_WINDOWS)
#include <botan/tls_server.h>
#include <botan/hex.h>
#include <botan/rsa.h>
#include <botan/dsa.h>
#include <botan/x509self.h>
#include <botan/secqueue.h>
#include "credentials.h"
using namespace Botan;
using namespace std::placeholders;
#include <list>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
namespace {
int make_server_socket(bool is_tcp, u16bit port)
{
const int type = is_tcp ? SOCK_STREAM : SOCK_DGRAM;
int fd = ::socket(PF_INET, type, 0);
if(fd == -1)
throw std::runtime_error("Unable to acquire socket");
sockaddr_in socket_info;
::memset(&socket_info, 0, sizeof(socket_info));
socket_info.sin_family = AF_INET;
socket_info.sin_port = htons(port);
// FIXME: support limiting listeners
socket_info.sin_addr.s_addr = INADDR_ANY;
if(::bind(fd, (sockaddr*)&socket_info, sizeof(struct sockaddr)) != 0)
{
::close(fd);
throw std::runtime_error("server bind failed");
}
if(is_tcp)
{
if(::listen(fd, 100) != 0)
{
::close(fd);
throw std::runtime_error("listen failed");
}
}
return fd;
}
bool handshake_complete(const TLS::Session& session)
{
std::cout << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << std::endl;
if(!session.session_id().empty())
std::cout << "Session ID " << hex_encode(session.session_id()) << std::endl;
if(!session.session_ticket().empty())
std::cout << "Session ticket " << hex_encode(session.session_ticket()) << std::endl;
return true;
}
void dgram_socket_write(int sockfd, const byte buf[], size_t length)
{
ssize_t sent = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(sent == -1)
std::cout << "Error writing to socket - " << strerror(errno) << std::endl;
else if(sent != static_cast<ssize_t>(length))
std::cout << "Packet of length " << length << " truncated to " << sent << std::endl;
}
void stream_socket_write(int sockfd, const byte buf[], size_t length)
{
while(length)
{
ssize_t sent = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(sent == -1)
{
if(errno == EINTR)
sent = 0;
else
throw std::runtime_error("Socket write failed");
}
buf += sent;
length -= sent;
}
}
void alert_received(TLS::Alert alert, const byte[], size_t)
{
std::cout << "Alert: " << alert.type_string() << std::endl;
}
int tls_server(int argc, char* argv[])
{
if(argc != 4 && argc != 5)
{
std::cout << "Usage: " << argv[0] << " server.crt server.key port [tcp|udp]" << std::endl;
return 1;
}
const std::string server_crt = argv[1];
const std::string server_key = argv[2];
const int port = to_u32bit(argv[3]);
const std::string transport = (argc >= 5) ? argv[4] : "tcp";
const bool is_tcp = (transport == "tcp");
try
{
AutoSeeded_RNG rng;
TLS::Policy policy;
TLS::Session_Manager_In_Memory session_manager(rng);
Basic_Credentials_Manager creds(rng, server_crt, server_key);
auto protocol_chooser = [](const std::vector<std::string>& protocols) -> std::string {
for(size_t i = 0; i != protocols.size(); ++i)
std::cout << "Client offered protocol " << i << " = " << protocols[i] << std::endl;
return "echo/1.0"; // too bad
};
std::cout << "Listening for new connections on " << transport << " port " << port << std::endl;
int server_fd = make_server_socket(is_tcp, port);
while(true)
{
try
{
int fd;
if(is_tcp)
fd = ::accept(server_fd, nullptr, nullptr);
else
{
struct sockaddr_in from;
socklen_t from_len = sizeof(sockaddr_in);
if(::recvfrom(server_fd, nullptr, 0, MSG_PEEK,
(struct sockaddr*)&from, &from_len) != 0)
throw std::runtime_error("Could not peek next packet");
if(::connect(server_fd, (struct sockaddr*)&from, from_len) != 0)
throw std::runtime_error("Could not connect UDP socket");
fd = server_fd;
}
std::cout << "New connection received" << std::endl;
auto socket_write = is_tcp ? std::bind(stream_socket_write, fd, _1, _2) :
std::bind(dgram_socket_write, fd, _1, _2);
std::string s;
std::list<std::string> pending_output;
auto proc_fn = [&](const byte input[], size_t input_len)
{
for(size_t i = 0; i != input_len; ++i)
{
const char c = static_cast<char>(input[i]);
s += c;
if(c == '\n')
{
pending_output.push_back(s);
s.clear();
}
}
};
TLS::Server server(socket_write,
proc_fn,
alert_received,
handshake_complete,
session_manager,
creds,
policy,
rng,
protocol_chooser,
!is_tcp);
while(!server.is_closed())
{
byte buf[4*1024] = { 0 };
ssize_t got = ::read(fd, buf, sizeof(buf));
if(got == -1)
{
std::cout << "Error in socket read - " << strerror(errno) << std::endl;
break;
}
if(got == 0)
{
std::cout << "EOF on socket" << std::endl;
break;
}
server.received_data(buf, got);
while(server.is_active() && !pending_output.empty())
{
std::string s = pending_output.front();
pending_output.pop_front();
server.send(s);
if(s == "quit\n")
server.close();
}
}
if(is_tcp)
::close(fd);
}
catch(std::exception& e)
{
std::cout << "Connection problem: " << e.what() << std::endl;
return 1;
}
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
REGISTER_APP(tls_server);
}
#endif
<commit_msg>Avoid building tls_server on MinGW. GH #39<commit_after>/*
* TLS echo server using BSD sockets
* (C) 2014 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "apps.h"
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_HAS_DSA) \
&& !defined(BOTAN_TARGET_OS_IS_WINDOWS) \
&& !defined(BOTAN_TARGET_OS_IS_MINGW)
#include <botan/tls_server.h>
#include <botan/hex.h>
#include <botan/rsa.h>
#include <botan/dsa.h>
#include <botan/x509self.h>
#include <botan/secqueue.h>
#include "credentials.h"
using namespace Botan;
using namespace std::placeholders;
#include <list>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
namespace {
int make_server_socket(bool is_tcp, u16bit port)
{
const int type = is_tcp ? SOCK_STREAM : SOCK_DGRAM;
int fd = ::socket(PF_INET, type, 0);
if(fd == -1)
throw std::runtime_error("Unable to acquire socket");
sockaddr_in socket_info;
::memset(&socket_info, 0, sizeof(socket_info));
socket_info.sin_family = AF_INET;
socket_info.sin_port = htons(port);
// FIXME: support limiting listeners
socket_info.sin_addr.s_addr = INADDR_ANY;
if(::bind(fd, (sockaddr*)&socket_info, sizeof(struct sockaddr)) != 0)
{
::close(fd);
throw std::runtime_error("server bind failed");
}
if(is_tcp)
{
if(::listen(fd, 100) != 0)
{
::close(fd);
throw std::runtime_error("listen failed");
}
}
return fd;
}
bool handshake_complete(const TLS::Session& session)
{
std::cout << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << std::endl;
if(!session.session_id().empty())
std::cout << "Session ID " << hex_encode(session.session_id()) << std::endl;
if(!session.session_ticket().empty())
std::cout << "Session ticket " << hex_encode(session.session_ticket()) << std::endl;
return true;
}
void dgram_socket_write(int sockfd, const byte buf[], size_t length)
{
ssize_t sent = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(sent == -1)
std::cout << "Error writing to socket - " << strerror(errno) << std::endl;
else if(sent != static_cast<ssize_t>(length))
std::cout << "Packet of length " << length << " truncated to " << sent << std::endl;
}
void stream_socket_write(int sockfd, const byte buf[], size_t length)
{
while(length)
{
ssize_t sent = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(sent == -1)
{
if(errno == EINTR)
sent = 0;
else
throw std::runtime_error("Socket write failed");
}
buf += sent;
length -= sent;
}
}
void alert_received(TLS::Alert alert, const byte[], size_t)
{
std::cout << "Alert: " << alert.type_string() << std::endl;
}
int tls_server(int argc, char* argv[])
{
if(argc != 4 && argc != 5)
{
std::cout << "Usage: " << argv[0] << " server.crt server.key port [tcp|udp]" << std::endl;
return 1;
}
const std::string server_crt = argv[1];
const std::string server_key = argv[2];
const int port = to_u32bit(argv[3]);
const std::string transport = (argc >= 5) ? argv[4] : "tcp";
const bool is_tcp = (transport == "tcp");
try
{
AutoSeeded_RNG rng;
TLS::Policy policy;
TLS::Session_Manager_In_Memory session_manager(rng);
Basic_Credentials_Manager creds(rng, server_crt, server_key);
auto protocol_chooser = [](const std::vector<std::string>& protocols) -> std::string {
for(size_t i = 0; i != protocols.size(); ++i)
std::cout << "Client offered protocol " << i << " = " << protocols[i] << std::endl;
return "echo/1.0"; // too bad
};
std::cout << "Listening for new connections on " << transport << " port " << port << std::endl;
int server_fd = make_server_socket(is_tcp, port);
while(true)
{
try
{
int fd;
if(is_tcp)
fd = ::accept(server_fd, nullptr, nullptr);
else
{
struct sockaddr_in from;
socklen_t from_len = sizeof(sockaddr_in);
if(::recvfrom(server_fd, nullptr, 0, MSG_PEEK,
(struct sockaddr*)&from, &from_len) != 0)
throw std::runtime_error("Could not peek next packet");
if(::connect(server_fd, (struct sockaddr*)&from, from_len) != 0)
throw std::runtime_error("Could not connect UDP socket");
fd = server_fd;
}
std::cout << "New connection received" << std::endl;
auto socket_write = is_tcp ? std::bind(stream_socket_write, fd, _1, _2) :
std::bind(dgram_socket_write, fd, _1, _2);
std::string s;
std::list<std::string> pending_output;
auto proc_fn = [&](const byte input[], size_t input_len)
{
for(size_t i = 0; i != input_len; ++i)
{
const char c = static_cast<char>(input[i]);
s += c;
if(c == '\n')
{
pending_output.push_back(s);
s.clear();
}
}
};
TLS::Server server(socket_write,
proc_fn,
alert_received,
handshake_complete,
session_manager,
creds,
policy,
rng,
protocol_chooser,
!is_tcp);
while(!server.is_closed())
{
byte buf[4*1024] = { 0 };
ssize_t got = ::read(fd, buf, sizeof(buf));
if(got == -1)
{
std::cout << "Error in socket read - " << strerror(errno) << std::endl;
break;
}
if(got == 0)
{
std::cout << "EOF on socket" << std::endl;
break;
}
server.received_data(buf, got);
while(server.is_active() && !pending_output.empty())
{
std::string s = pending_output.front();
pending_output.pop_front();
server.send(s);
if(s == "quit\n")
server.close();
}
}
if(is_tcp)
::close(fd);
}
catch(std::exception& e)
{
std::cout << "Connection problem: " << e.what() << std::endl;
return 1;
}
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
return 0;
}
REGISTER_APP(tls_server);
}
#endif
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief R8C MAX7219 メイン @n
P1_0: DIN @n
P1_1: /CS @n
P1_2: CLK
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include <cstring>
#include "common/vect.h"
#include "system.hpp"
#include "clock.hpp"
#include "port.hpp"
#include "intr.hpp"
#include "common/intr_utils.hpp"
#include "common/delay.hpp"
#include "common/port_map.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/format.hpp"
#include "common/trb_io.hpp"
#include "common/spi_io.hpp"
#include "chip/MAX7219.hpp"
namespace {
device::trb_io<utils::null_task, uint8_t> timer_b_;
typedef utils::fifo<uint8_t, 16> buffer;
typedef device::uart_io<device::UART0, buffer, buffer> uart;
uart uart_;
typedef device::PORT<device::PORT1, device::bitpos::B0> SPI_SDA;
typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_SCL;
typedef device::spi_io<SPI_SCL, SPI_SDA, device::NULL_PORT> SPI;
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B1> SELECT;
chip::MAX7219<SPI, SELECT> max7219_(spi_);
}
extern "C" {
void sci_putch(char ch) {
uart_.putch(ch);
}
char sci_getch(void) {
return uart_.getch();
}
uint16_t sci_length() {
return uart_.length();
}
void sci_puts(const char* str) {
uart_.puts(str);
}
void TIMER_RB_intr(void) {
timer_b_.itask();
}
void UART0_TX_intr(void) {
uart_.isend();
}
void UART0_RX_intr(void) {
uart_.irecv();
}
}
// __attribute__ ((section (".exttext")))
int main(int argc, char *argv[])
{
using namespace device;
// クロック関係レジスタ・プロテクト解除
PRCR.PRC0 = 1;
// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事(Makefile内)
OCOCR.HOCOE = 1;
utils::delay::micro_second(1); // >=30us(125KHz)
SCKCR.HSCKSEL = 1;
CKSTPR.SCKSEL = 1;
// タイマーB初期化
{
uint8_t ir_level = 2;
timer_b_.start_timer(60, ir_level);
}
// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意!
{
utils::PORT_MAP(utils::port_map::P14::TXD0);
utils::PORT_MAP(utils::port_map::P15::RXD0);
uint8_t ir_level = 1;
uart_.start(57600, ir_level);
}
// SPI を開始
{
spi_.start(10);
}
// MAX7219 を開始
{
max7219_.start();
}
sci_puts("Start R8C MAX7219 sample\n");
// LED シグナル用ポートを出力
PD1.B0 = 1;
for(uint8_t i = 0; i < 8; ++i) {
max7219_.set_cha(i, '-');
}
uint8_t idx = 0;
while(1) {
timer_b_.sync();
max7219_.service();
max7219_.set_intensity(0);
if(sci_length()) {
if(idx > 7) {
max7219_.shift_top();
idx = 7;
}
char ch = sci_getch();
sci_putch(ch);
max7219_.set_cha(idx ^ 7, ch);
++idx;
}
}
}
<commit_msg>update: spi_io typedef<commit_after>//=====================================================================//
/*! @file
@brief R8C MAX7219 メイン @n
P1_0: DIN @n
P1_1: /CS @n
P1_2: CLK
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "common/vect.h"
#include "system.hpp"
#include "clock.hpp"
#include "port.hpp"
#include "intr.hpp"
#include "common/intr_utils.hpp"
#include "common/delay.hpp"
#include "common/port_map.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/format.hpp"
#include "common/trb_io.hpp"
#include "common/spi_io.hpp"
#include "chip/MAX7219.hpp"
namespace {
device::trb_io<utils::null_task, uint8_t> timer_b_;
typedef utils::fifo<uint8_t, 16> buffer;
typedef device::uart_io<device::UART0, buffer, buffer> uart;
uart uart_;
typedef device::PORT<device::PORT1, device::bitpos::B0> SPI_SDA;
typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_SCL;
typedef device::spi_io<device::NULL_PORT, SPI_SDA, SPI_SCL, device::soft_spi_mode::CK10> SPI;
SPI spi_;
typedef device::PORT<device::PORT1, device::bitpos::B1> SELECT;
chip::MAX7219<SPI, SELECT> max7219_(spi_);
}
extern "C" {
void sci_putch(char ch) {
uart_.putch(ch);
}
char sci_getch(void) {
return uart_.getch();
}
uint16_t sci_length() {
return uart_.length();
}
void sci_puts(const char* str) {
uart_.puts(str);
}
void TIMER_RB_intr(void) {
timer_b_.itask();
}
void UART0_TX_intr(void) {
uart_.isend();
}
void UART0_RX_intr(void) {
uart_.irecv();
}
}
// __attribute__ ((section (".exttext")))
int main(int argc, char *argv[])
{
using namespace device;
// クロック関係レジスタ・プロテクト解除
PRCR.PRC0 = 1;
// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事(Makefile内)
OCOCR.HOCOE = 1;
utils::delay::micro_second(1); // >=30us(125KHz)
SCKCR.HSCKSEL = 1;
CKSTPR.SCKSEL = 1;
// タイマーB初期化
{
uint8_t ir_level = 2;
timer_b_.start_timer(60, ir_level);
}
// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意!
{
utils::PORT_MAP(utils::port_map::P14::TXD0);
utils::PORT_MAP(utils::port_map::P15::RXD0);
uint8_t ir_level = 1;
uart_.start(57600, ir_level);
}
// SPI を開始
{
spi_.start(10);
}
// MAX7219 を開始
{
max7219_.start();
}
sci_puts("Start R8C MAX7219 sample\n");
// LED シグナル用ポートを出力
PD1.B0 = 1;
for(uint8_t i = 0; i < 8; ++i) {
max7219_.set_cha(i, '-');
}
uint8_t idx = 0;
while(1) {
timer_b_.sync();
max7219_.service();
max7219_.set_intensity(0);
if(sci_length()) {
if(idx > 7) {
max7219_.shift_top();
idx = 7;
}
char ch = sci_getch();
sci_putch(ch);
max7219_.set_cha(idx ^ 7, ch);
++idx;
}
}
}
<|endoftext|> |
<commit_before>#include "cpu_generic.h"
//////////////////////////////////////////////////////////////////////
// GENERIC: register access
//////////////////////////////////////////////////////////////////////
static Value **
ptr_r(cpu_t *cpu)
{
switch (cpu->reg_size) {
case 8:
return cpu->ptr_r8;
case 16:
return cpu->ptr_r16;
case 32:
return cpu->ptr_r32;
case 64:
return cpu->ptr_r64;
default:
return 0; /* can't happen */
}
}
static Value **
ptr_f(cpu_t *cpu)
{
switch (cpu->fp_reg_size) {
case 32:
return cpu->ptr_f32;
case 64:
return cpu->ptr_f64;
case 80:
return cpu->ptr_f80;
case 128:
return cpu->ptr_f128;
default:
return 0; /* can't happen */
}
}
// GET REGISTER
Value *
arch_get_reg(cpu_t *cpu, uint32_t index, uint32_t bits, BasicBlock *bb) {
Value *v;
/* R0 is always 0 (on certain RISCs) */
if (cpu->has_special_r0 && !index)
return CONSTs(bits? bits : cpu->reg_size, 0);
/* get the register */
v = new LoadInst(ptr_r(cpu)[index], "", false, bb);
/* optionally truncate it */
if (bits && cpu->reg_size != bits)
v = TRUNC(bits, v);
return v;
}
Value *
arch_get_fp_reg(cpu_t *cpu, uint32_t index, uint32_t bits, BasicBlock *bb) {
Value *v;
/* get the register */
return new LoadInst(ptr_f(cpu)[index], "", false, bb);
}
// PUT REGISTER
void
arch_put_reg(cpu_t *cpu, uint32_t index, Value *v, uint32_t bits, bool sext, BasicBlock *bb) {
/*
* if the caller cares about bit size and
* the size is not the register size, we'll zext or sext
*/
if (bits && cpu->reg_size != bits)
if (sext)
v = SEXT(cpu->reg_size, v);
else
v = ZEXT(cpu->reg_size, v);
/* store value, unless it's R0 (on certain RISCs) */
if (!cpu->has_special_r0 || index)
new StoreInst(v, ptr_r(cpu)[index], bb);
}
void
arch_put_fp_reg(cpu_t *cpu, uint32_t index, Value *v, uint32_t bits, BasicBlock *bb) {
/* store value, unless it's R0 (on certain RISCs) */
if (!cpu->has_special_fr0 || index)
new StoreInst(v, ptr_f(cpu)[index], bb);
}
//XXX TODO
// The guest CPU can be little endian or big endian, so we need both
// host mode access routines as well as IR generators that deal with
// both modes. In practice, we need two sets of functions, one that
// deals with host native endianness, and one that deals with the other
// endianness; and interface functions that dispatch calls to endianness
// functions depending on the host endianness.
// i.e. there should be RAM32NE() which reads a 32 bit address from RAM,
// using the "Native Endianness" of the host, and RAM32SW() which does
// a swapped read. RAM32BE() and RAM32LE() should choose either of
// RAM32NE() and RAM32SW() depending on the endianness of the host.
//
// Swapped endianness can be implemented in different ways: by swapping
// every non-byte memory read and write, or by keeping aligned words
// in the host's native endianness, not swapping aligned reads and
// writes, and correcting unaligned accesses. (This makes more sense
// on guest CPUs that only allow aligned memory access.)
// The client should be able to specify a specific strategy, but each
// CPU frontend should default to the typically best strategy. Functions
// like RAM32SW() will have to respect the setting, so that all memory
// access is consistent with the strategy.
//////////////////////////////////////////////////////////////////////
// GENERIC: host memory access
//////////////////////////////////////////////////////////////////////
uint32_t
RAM32BE(uint8_t *RAM, addr_t a) {
uint32_t v;
v = RAM[a+0] << 24;
v |= RAM[a+1] << 16;
v |= RAM[a+2] << 8;
v |= RAM[a+3] << 0;
return v;
}
//////////////////////////////////////////////////////////////////////
// GENERIC: memory access
//////////////////////////////////////////////////////////////////////
/* get a RAM pointer to a 32 bit value */
static Value *
arch_gep32(cpu_t *cpu, Value *a, BasicBlock *bb) {
a = GetElementPtrInst::Create(cpu->ptr_RAM, a, "", bb);
return new BitCastInst(a, PointerType::get(getType(Int32Ty), 0), "", bb);
}
/* load 32 bit ALIGNED value from RAM */
Value *
arch_load32_aligned(cpu_t *cpu, Value *a, BasicBlock *bb) {
a = arch_gep32(cpu, a, bb);
#ifdef __LITTLE_ENDIAN__
bool swap = !cpu->is_little_endian;
#else
bool swap = cpu->is_little_endian;
#endif
if(swap)
return SWAP32(new LoadInst(a, "", false, bb));
else
return new LoadInst(a, "", false, bb);
}
/* store 32 bit ALIGNED value to RAM */
void
arch_store32_aligned(cpu_t *cpu, Value *v, Value *a, BasicBlock *bb) {
a = arch_gep32(cpu, a, bb);
#ifdef __LITTLE_ENDIAN__
bool swap = !cpu->is_little_endian;
#else
bool swap = cpu->is_little_endian;
#endif
new StoreInst(swap ? SWAP32(v) : v, a, bb);
}
//////////////////////////////////////////////////////////////////////
// GENERIC: endianness
//////////////////////////////////////////////////////////////////////
static Value *
arch_get_shift8(cpu_t *cpu, Value *addr, BasicBlock *bb)
{
Value *shift = AND(addr,CONST(3));
if (!cpu->is_little_endian)
shift = XOR(shift, CONST(3));
return SHL(CONST(3), shift);
}
static Value *
arch_get_shift16(cpu_t *cpu, Value *addr, BasicBlock *bb)
{
Value *shift = AND(addr,CONST(1));
if (!cpu->is_little_endian)
shift = XOR(shift, CONST(1));
return SHL(CONST(4), shift);
}
Value *
arch_load8(cpu_t *cpu, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift8(cpu, addr, bb);
Value *val = arch_load32_aligned(cpu, AND(addr, CONST(~3ULL)), bb);
return TRUNC8(LSHR(val, shift));
}
Value *
arch_load16_aligned(cpu_t *cpu, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift16(cpu, addr, bb);
Value *val = arch_load32_aligned(cpu, AND(addr, CONST(~3ULL)), bb);
return TRUNC16(LSHR(val, shift));
}
void
arch_store8(cpu_t *cpu, Value *val, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift8(cpu, addr, bb);
addr = AND(addr, CONST(~3ULL));
Value *mask = XOR(SHL(CONST(255), shift),CONST(-1ULL));
Value *old = AND(arch_load32_aligned(cpu, addr, bb), mask);
val = OR(old, SHL(AND(val, CONST(255)), shift));
arch_store32_aligned(cpu, val, addr, bb);
}
void
arch_store16(cpu_t *cpu, Value *val, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift16(cpu, addr, bb);
addr = AND(addr, CONST(~3ULL));
Value *mask = XOR(SHL(CONST(65535), shift),CONST(-1ULL));
Value *old = AND(arch_load32_aligned(cpu, addr, bb), mask);
val = OR(old, SHL(AND(val, CONST(65535)), shift));
arch_store32_aligned(cpu, val, addr, bb);
}
//////////////////////////////////////////////////////////////////////
Value *
arch_bswap(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::bswap, &ty, 1), v, "", bb);
}
Value *
arch_ctlz(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::ctlz, &ty, 1), v, "", bb);
}
Value *
arch_cttz(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::cttz, &ty, 1), v, "", bb);
}
// branches
void
arch_branch(bool flag_state, BasicBlock *target1, BasicBlock *target2, Value *v, BasicBlock *bb) {
if (flag_state)
BranchInst::Create(target1, target2, v, bb);
else
BranchInst::Create(target2, target1, v, bb);
}
void
arch_jump(BasicBlock *bb, BasicBlock *bb_target) {
if (!bb_target) {
printf("error: unknown jump target!\n");
exit(1);
}
BranchInst::Create(bb_target, bb);
}
// decoding and encoding of bits in a bitfield (e.g. flags)
Value *
arch_encode_bit(Value *flags, Value *bit, int shift, int width, BasicBlock *bb)
{
Value *n = new LoadInst(bit, "", false, bb);
bit = new ZExtInst(n, getIntegerType(width), "", bb);
bit = BinaryOperator::Create(Instruction::Shl, bit, ConstantInt::get(getIntegerType(width), shift), "", bb);
return BinaryOperator::Create(Instruction::Or, flags, bit, "", bb);
}
void
arch_decode_bit(Value *flags, Value *bit, int shift, int width, BasicBlock *bb)
{
Value *n = BinaryOperator::Create(Instruction::LShr, flags, ConstantInt::get(getIntegerType(width), shift), "", bb);
n = new TruncInst(n, getIntegerType(1), "", bb);
new StoreInst(n, bit, bb);
}
// FP
Value *
arch_sqrt(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getFloatType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::sqrt, &ty, 1), v, "", bb);
}
<commit_msg>fix shifts.<commit_after>#include "cpu_generic.h"
//////////////////////////////////////////////////////////////////////
// GENERIC: register access
//////////////////////////////////////////////////////////////////////
static Value **
ptr_r(cpu_t *cpu)
{
switch (cpu->reg_size) {
case 8:
return cpu->ptr_r8;
case 16:
return cpu->ptr_r16;
case 32:
return cpu->ptr_r32;
case 64:
return cpu->ptr_r64;
default:
return 0; /* can't happen */
}
}
static Value **
ptr_f(cpu_t *cpu)
{
switch (cpu->fp_reg_size) {
case 32:
return cpu->ptr_f32;
case 64:
return cpu->ptr_f64;
case 80:
return cpu->ptr_f80;
case 128:
return cpu->ptr_f128;
default:
return 0; /* can't happen */
}
}
// GET REGISTER
Value *
arch_get_reg(cpu_t *cpu, uint32_t index, uint32_t bits, BasicBlock *bb) {
Value *v;
/* R0 is always 0 (on certain RISCs) */
if (cpu->has_special_r0 && !index)
return CONSTs(bits? bits : cpu->reg_size, 0);
/* get the register */
v = new LoadInst(ptr_r(cpu)[index], "", false, bb);
/* optionally truncate it */
if (bits && cpu->reg_size != bits)
v = TRUNC(bits, v);
return v;
}
Value *
arch_get_fp_reg(cpu_t *cpu, uint32_t index, uint32_t bits, BasicBlock *bb) {
Value *v;
/* get the register */
return new LoadInst(ptr_f(cpu)[index], "", false, bb);
}
// PUT REGISTER
void
arch_put_reg(cpu_t *cpu, uint32_t index, Value *v, uint32_t bits, bool sext, BasicBlock *bb) {
/*
* if the caller cares about bit size and
* the size is not the register size, we'll zext or sext
*/
if (bits && cpu->reg_size != bits)
if (sext)
v = SEXT(cpu->reg_size, v);
else
v = ZEXT(cpu->reg_size, v);
/* store value, unless it's R0 (on certain RISCs) */
if (!cpu->has_special_r0 || index)
new StoreInst(v, ptr_r(cpu)[index], bb);
}
void
arch_put_fp_reg(cpu_t *cpu, uint32_t index, Value *v, uint32_t bits, BasicBlock *bb) {
/* store value, unless it's R0 (on certain RISCs) */
if (!cpu->has_special_fr0 || index)
new StoreInst(v, ptr_f(cpu)[index], bb);
}
//XXX TODO
// The guest CPU can be little endian or big endian, so we need both
// host mode access routines as well as IR generators that deal with
// both modes. In practice, we need two sets of functions, one that
// deals with host native endianness, and one that deals with the other
// endianness; and interface functions that dispatch calls to endianness
// functions depending on the host endianness.
// i.e. there should be RAM32NE() which reads a 32 bit address from RAM,
// using the "Native Endianness" of the host, and RAM32SW() which does
// a swapped read. RAM32BE() and RAM32LE() should choose either of
// RAM32NE() and RAM32SW() depending on the endianness of the host.
//
// Swapped endianness can be implemented in different ways: by swapping
// every non-byte memory read and write, or by keeping aligned words
// in the host's native endianness, not swapping aligned reads and
// writes, and correcting unaligned accesses. (This makes more sense
// on guest CPUs that only allow aligned memory access.)
// The client should be able to specify a specific strategy, but each
// CPU frontend should default to the typically best strategy. Functions
// like RAM32SW() will have to respect the setting, so that all memory
// access is consistent with the strategy.
//////////////////////////////////////////////////////////////////////
// GENERIC: host memory access
//////////////////////////////////////////////////////////////////////
uint32_t
RAM32BE(uint8_t *RAM, addr_t a) {
uint32_t v;
v = RAM[a+0] << 24;
v |= RAM[a+1] << 16;
v |= RAM[a+2] << 8;
v |= RAM[a+3] << 0;
return v;
}
//////////////////////////////////////////////////////////////////////
// GENERIC: memory access
//////////////////////////////////////////////////////////////////////
/* get a RAM pointer to a 32 bit value */
static Value *
arch_gep32(cpu_t *cpu, Value *a, BasicBlock *bb) {
a = GetElementPtrInst::Create(cpu->ptr_RAM, a, "", bb);
return new BitCastInst(a, PointerType::get(getType(Int32Ty), 0), "", bb);
}
/* load 32 bit ALIGNED value from RAM */
Value *
arch_load32_aligned(cpu_t *cpu, Value *a, BasicBlock *bb) {
a = arch_gep32(cpu, a, bb);
#ifdef __LITTLE_ENDIAN__
bool swap = !cpu->is_little_endian;
#else
bool swap = cpu->is_little_endian;
#endif
if(swap)
return SWAP32(new LoadInst(a, "", false, bb));
else
return new LoadInst(a, "", false, bb);
}
/* store 32 bit ALIGNED value to RAM */
void
arch_store32_aligned(cpu_t *cpu, Value *v, Value *a, BasicBlock *bb) {
a = arch_gep32(cpu, a, bb);
#ifdef __LITTLE_ENDIAN__
bool swap = !cpu->is_little_endian;
#else
bool swap = cpu->is_little_endian;
#endif
new StoreInst(swap ? SWAP32(v) : v, a, bb);
}
//////////////////////////////////////////////////////////////////////
// GENERIC: endianness
//////////////////////////////////////////////////////////////////////
static Value *
arch_get_shift8(cpu_t *cpu, Value *addr, BasicBlock *bb)
{
Value *shift = AND(addr,CONST(3));
if (!cpu->is_little_endian)
shift = XOR(shift, CONST(3));
return SHL(shift, CONST(3));
}
static Value *
arch_get_shift16(cpu_t *cpu, Value *addr, BasicBlock *bb)
{
Value *shift = AND(addr,CONST(1));
if (!cpu->is_little_endian)
shift = XOR(shift, CONST(1));
return SHL(shift, CONST(4));
}
Value *
arch_load8(cpu_t *cpu, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift8(cpu, addr, bb);
Value *val = arch_load32_aligned(cpu, AND(addr, CONST(~3ULL)), bb);
return TRUNC8(LSHR(val, shift));
}
Value *
arch_load16_aligned(cpu_t *cpu, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift16(cpu, addr, bb);
Value *val = arch_load32_aligned(cpu, AND(addr, CONST(~3ULL)), bb);
return TRUNC16(LSHR(val, shift));
}
void
arch_store8(cpu_t *cpu, Value *val, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift8(cpu, addr, bb);
addr = AND(addr, CONST(~3ULL));
Value *mask = XOR(SHL(CONST(255), shift),CONST(-1ULL));
Value *old = AND(arch_load32_aligned(cpu, addr, bb), mask);
val = OR(old, SHL(AND(val, CONST(255)), shift));
arch_store32_aligned(cpu, val, addr, bb);
}
void
arch_store16(cpu_t *cpu, Value *val, Value *addr, BasicBlock *bb) {
Value *shift = arch_get_shift16(cpu, addr, bb);
addr = AND(addr, CONST(~3ULL));
Value *mask = XOR(SHL(CONST(65535), shift),CONST(-1ULL));
Value *old = AND(arch_load32_aligned(cpu, addr, bb), mask);
val = OR(old, SHL(AND(val, CONST(65535)), shift));
arch_store32_aligned(cpu, val, addr, bb);
}
//////////////////////////////////////////////////////////////////////
Value *
arch_bswap(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::bswap, &ty, 1), v, "", bb);
}
Value *
arch_ctlz(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::ctlz, &ty, 1), v, "", bb);
}
Value *
arch_cttz(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getIntegerType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::cttz, &ty, 1), v, "", bb);
}
// branches
void
arch_branch(bool flag_state, BasicBlock *target1, BasicBlock *target2, Value *v, BasicBlock *bb) {
if (flag_state)
BranchInst::Create(target1, target2, v, bb);
else
BranchInst::Create(target2, target1, v, bb);
}
void
arch_jump(BasicBlock *bb, BasicBlock *bb_target) {
if (!bb_target) {
printf("error: unknown jump target!\n");
exit(1);
}
BranchInst::Create(bb_target, bb);
}
// decoding and encoding of bits in a bitfield (e.g. flags)
Value *
arch_encode_bit(Value *flags, Value *bit, int shift, int width, BasicBlock *bb)
{
Value *n = new LoadInst(bit, "", false, bb);
bit = new ZExtInst(n, getIntegerType(width), "", bb);
bit = BinaryOperator::Create(Instruction::Shl, bit, ConstantInt::get(getIntegerType(width), shift), "", bb);
return BinaryOperator::Create(Instruction::Or, flags, bit, "", bb);
}
void
arch_decode_bit(Value *flags, Value *bit, int shift, int width, BasicBlock *bb)
{
Value *n = BinaryOperator::Create(Instruction::LShr, flags, ConstantInt::get(getIntegerType(width), shift), "", bb);
n = new TruncInst(n, getIntegerType(1), "", bb);
new StoreInst(n, bit, bb);
}
// FP
Value *
arch_sqrt(cpu_t *cpu, size_t width, Value *v, BasicBlock *bb) {
Type const *ty = getFloatType(width);
return CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::sqrt, &ty, 1), v, "", bb);
}
<|endoftext|> |
<commit_before>#include <netdb.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include "client.h"
#include "duckchat.h"
#include "raw.h"
// Client connects, logs in, and joins “Common”.
// Client reads lines from the user and parses commands.
// Client correctly sends Say message.
// Client uses select() to wait for input from the user and the server.
// Client correctly sends Join, Leave, Login, and Logout and TODO handles Switch.
// TODO Client correctly sends List and Who.
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
// Variables
struct sockaddr_in client_addr;
struct sockaddr_in server_addr;
int client_socket;
struct addrinfo *server_info;
char *current_channel;
std::vector<char *> channels;
// Prints an error message and exits the program.
void Error(const char *msg) {
std::cerr << msg << std::endl;
exit(1);
}
void PrintPrompt() {
std::cout << "> " << std::flush;
}
// Splits strings around spaces.
std::vector<std::string> StringSplit(std::string input) {
std::istringstream iss(input);
std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
return result;
}
// Splits strings around spaces.
std::vector<std::string> SplitString(char *input, char delimiter) {
std::vector<std::string> result;
std::string word = "";
size_t input_size = strlen(input);
for (size_t i = 0; i < input_size; i++) {
if (input[i] != delimiter) {
word += input[i];
} else {
result.push_back(word);
word = "";
}
}
result.push_back(word);
return result;
}
void StripChar(char *input, char c) {
size_t size = strlen(input);
for (size_t i = 0; i < size; i++) {
if (input[i] == c) {
input[i] = '\0';
}
}
}
// Gets the address info of the server at a the given port and creates the client's socket.
void CreateSocket(char *domain, const char *port) {
std::cout << "Connecting to " << domain << std::endl;
struct addrinfo hints;
struct addrinfo *server_info_tmp;
int status;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = 0;
if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {
std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl;
exit(1);
}
// getaddrinfo() returns a list of address structures into server_info_tmp.
// Tries each address until a successful connect().
// If socket() (or connect()) fails, closes the socket and tries the next address.
for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {
if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {
continue;
}
if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {
fcntl(client_socket, F_SETFL, O_NONBLOCK);
break; // Success
}
close(client_socket);
}
if (server_info == NULL) {
Error("client: all sockets failed to connect");
}
}
// Sends a message to all users in on the active channel.
int SendSay(const char *message) {
struct request_say say;
memset(&say, 0, sizeof(say));
say.req_type = REQ_SAY;
strncpy(say.req_text, message, SAY_MAX);
strncpy(say.req_channel, current_channel, CHANNEL_MAX);
if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to send message\n");
}
return 0;
}
// Sends login requests to the server.
int SendLogin(char *username) {
struct request_login login;
memset(&login, 0, sizeof(login));
login.req_type = REQ_LOGIN;
strncpy(login.req_username, username, USERNAME_MAX);
size_t message_size = sizeof(struct request_login);
if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request login\n");
}
return 0;
}
// Sends logout requests to the server.
int SendLogout() {
struct request_logout logout;
memset((char *) &logout, 0, sizeof(logout));
logout.req_type = REQ_LOGOUT;
size_t message_size = sizeof(struct request_logout);
if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request logout\n");
}
return 0;
}
// Sends join requests to the server.
int SendJoin(const char *channel) {
struct request_join join;
memset((char *) &join, 0, sizeof(join));
join.req_type = REQ_JOIN;
strncpy(join.req_channel, channel, CHANNEL_MAX);
size_t message_size = sizeof(struct request_join);
if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request join\n");
}
channels.push_back((char *) channel);
return 0;
}
// Switches to a channel the user has already joined.
int SwitchChannel(const char *channel) {
bool isSubscribed = false;
if (channels.size() > 0) {
for (auto c: channels) {
std::cout << "c: " << c << " channel: " << channel << std::endl;
if (channel == c) {
current_channel = (char *) channel;
isSubscribed = true;
}
}
}
if (!isSubscribed) {
std::cout << "You have not subscribed to channel " << channel << std::endl;
}
return 0;
}
// Handles TXT-SAY server messages.
void HandleTextSay(char *receive_buffer, char *output) {
struct text_say say;
memcpy(&say, receive_buffer, sizeof(struct text_say));
std::string backspaces = "";
for (int i = 0; i < SAY_MAX; i++) {
backspaces.append("\b");
}
std::cout << backspaces;
std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl;
PrintPrompt();
std::cout << output << std::flush;
}
// Processes the input string to decide what type of command it is.
bool ProcessInput(std::string input) {
std::vector<std::string> inputs = StringSplit(input);
if (inputs[0] == "/exit") {
SendLogout();
cooked_mode();
return false;
} else if (inputs[0] == "/list") {
} else if (inputs[0] == "/join" && inputs.size() > 1) {
SendJoin(inputs[1].c_str());
} else if (inputs[0] == "/leave") {
} else if (inputs[0] == "/who") {
} else if (inputs[0] == "/switch" && inputs.size() > 1) {
SwitchChannel(inputs[1].c_str());
} else {
std::cout << "*Unknown command" << std::endl;
}
PrintPrompt();
return true;
}
int main(int argc, char *argv[]) {
char *domain;
char *port_str;
int port_num;
char *username;
char *input;
char *output = (char *) "";
fd_set read_set;
int result;
char stdin_buffer[SAY_MAX + 1];
char *stdin_buffer_pointer = stdin_buffer;
char receive_buffer[kBufferSize];
memset(&receive_buffer, 0, kBufferSize);
if (argc < 4) {
Error("usage: client [server name] [port] [username]");
}
domain = argv[1];
port_str = argv[2];
port_num = atoi(argv[2]);
username = argv[3];
if (strlen(domain) > UNIX_PATH_MAX) {
Error("client: server name must be less than 108 characters");
}
if (port_num < 0 || port_num > 65535) {
Error("client: port number must be between 0 and 65535");
}
if (strlen(username) > USERNAME_MAX) {
Error("client: username must be less than 32 characters");
}
CreateSocket(domain, port_str);
SendLogin(username);
current_channel = (char *) "Common";
channels.push_back(current_channel);
SendJoin(current_channel);
if (raw_mode() != 0){
Error("client: error using raw mode");
}
PrintPrompt();
while (1) {
FD_ZERO(&read_set);
FD_SET(client_socket, &read_set);
FD_SET(STDIN_FILENO, &read_set);
if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {
Error("client: problem using select");
}
if (result > 0) {
if (FD_ISSET(STDIN_FILENO, &read_set)) {
// User entered a char.
char c = (char) getchar();
if (c == '\n') {
// Increments pointer and adds NULL char.
*stdin_buffer_pointer++ = '\0';
// Resets stdin_buffer_pointer to the start of stdin_buffer.
stdin_buffer_pointer = stdin_buffer;
std::cout << "\n" << std::flush;
// Prevents output from printing on the new prompt after a newline char.
output = (char *) "";
input = stdin_buffer;
if (input[0] == '/') {
if (!ProcessInput(input)) {
break;
}
} else {
// Sends chat messages.
SendSay(input);
}
} else if (stdin_buffer_pointer != stdin_buffer + SAY_MAX) {
// Increments pointer and adds char c.
*stdin_buffer_pointer++ = c;
std::cout << c << std::flush;
// Copies pointer into output.
output = stdin_buffer_pointer;
// Increments and sets NULL char.
*output++ = '\0';
// Copies stdin_buffer into part of output before NULL char.
output = stdin_buffer;
}
} else if (FD_ISSET(client_socket, &read_set)) {
// Socket has data.
ssize_t read_size = read(client_socket, receive_buffer, kBufferSize);
if (read_size != 0) {
struct text message;
memcpy(&message, receive_buffer, sizeof(struct text));
text_t text_type = message.txt_type;
switch (text_type) {
case TXT_SAY:
HandleTextSay(receive_buffer, output);
break;
default:
break;
}
}
memset(&receive_buffer, 0, SAY_MAX);
} // end of if client_socket
} // end of if result
} // end of while
return 0;
}<commit_msg>print testing in join<commit_after>#include <netdb.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include "client.h"
#include "duckchat.h"
#include "raw.h"
// Client connects, logs in, and joins “Common”.
// Client reads lines from the user and parses commands.
// Client correctly sends Say message.
// Client uses select() to wait for input from the user and the server.
// Client correctly sends Join, Leave, Login, and Logout and TODO handles Switch.
// TODO Client correctly sends List and Who.
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
// Variables
struct sockaddr_in client_addr;
struct sockaddr_in server_addr;
int client_socket;
struct addrinfo *server_info;
char *current_channel;
std::vector<char *> channels;
// Prints an error message and exits the program.
void Error(const char *msg) {
std::cerr << msg << std::endl;
exit(1);
}
void PrintPrompt() {
std::cout << "> " << std::flush;
}
// Splits strings around spaces.
std::vector<std::string> StringSplit(std::string input) {
std::istringstream iss(input);
std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
return result;
}
// Splits strings around spaces.
std::vector<std::string> SplitString(char *input, char delimiter) {
std::vector<std::string> result;
std::string word = "";
size_t input_size = strlen(input);
for (size_t i = 0; i < input_size; i++) {
if (input[i] != delimiter) {
word += input[i];
} else {
result.push_back(word);
word = "";
}
}
result.push_back(word);
return result;
}
void StripChar(char *input, char c) {
size_t size = strlen(input);
for (size_t i = 0; i < size; i++) {
if (input[i] == c) {
input[i] = '\0';
}
}
}
// Gets the address info of the server at a the given port and creates the client's socket.
void CreateSocket(char *domain, const char *port) {
std::cout << "Connecting to " << domain << std::endl;
struct addrinfo hints;
struct addrinfo *server_info_tmp;
int status;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = 0;
if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {
std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl;
exit(1);
}
// getaddrinfo() returns a list of address structures into server_info_tmp.
// Tries each address until a successful connect().
// If socket() (or connect()) fails, closes the socket and tries the next address.
for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {
if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {
continue;
}
if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {
fcntl(client_socket, F_SETFL, O_NONBLOCK);
break; // Success
}
close(client_socket);
}
if (server_info == NULL) {
Error("client: all sockets failed to connect");
}
}
// Sends a message to all users in on the active channel.
int SendSay(const char *message) {
struct request_say say;
memset(&say, 0, sizeof(say));
say.req_type = REQ_SAY;
strncpy(say.req_text, message, SAY_MAX);
strncpy(say.req_channel, current_channel, CHANNEL_MAX);
if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to send message\n");
}
return 0;
}
// Sends login requests to the server.
int SendLogin(char *username) {
struct request_login login;
memset(&login, 0, sizeof(login));
login.req_type = REQ_LOGIN;
strncpy(login.req_username, username, USERNAME_MAX);
size_t message_size = sizeof(struct request_login);
if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request login\n");
}
return 0;
}
// Sends logout requests to the server.
int SendLogout() {
struct request_logout logout;
memset((char *) &logout, 0, sizeof(logout));
logout.req_type = REQ_LOGOUT;
size_t message_size = sizeof(struct request_logout);
if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request logout\n");
}
return 0;
}
// Sends join requests to the server.
int SendJoin(const char *channel) {
std::cout << "join channel: " << channel << std::endl;
struct request_join join;
memset((char *) &join, 0, sizeof(join));
join.req_type = REQ_JOIN;
strncpy(join.req_channel, channel, CHANNEL_MAX);
size_t message_size = sizeof(struct request_join);
if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {
Error("client: failed to request join\n");
}
channels.push_back((char *) channel);
for (auto c : channels) {
std::cout << "channel in channels: " << c << std::endl;
}
return 0;
}
// Switches to a channel the user has already joined.
int SwitchChannel(const char *channel) {
bool isSubscribed = false;
if (channels.size() > 0) {
for (auto c: channels) {
std::cout << "c: " << c << " channel: " << channel << std::endl;
if (channel == c) {
current_channel = (char *) channel;
isSubscribed = true;
}
}
}
if (!isSubscribed) {
std::cout << "You have not subscribed to channel " << channel << std::endl;
}
return 0;
}
// Handles TXT-SAY server messages.
void HandleTextSay(char *receive_buffer, char *output) {
struct text_say say;
memcpy(&say, receive_buffer, sizeof(struct text_say));
std::string backspaces = "";
for (int i = 0; i < SAY_MAX; i++) {
backspaces.append("\b");
}
std::cout << backspaces;
std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl;
PrintPrompt();
std::cout << output << std::flush;
}
// Processes the input string to decide what type of command it is.
bool ProcessInput(std::string input) {
std::vector<std::string> inputs = StringSplit(input);
if (inputs[0] == "/exit") {
SendLogout();
cooked_mode();
return false;
} else if (inputs[0] == "/list") {
} else if (inputs[0] == "/join" && inputs.size() > 1) {
SendJoin(inputs[1].c_str());
} else if (inputs[0] == "/leave") {
} else if (inputs[0] == "/who") {
} else if (inputs[0] == "/switch" && inputs.size() > 1) {
SwitchChannel(inputs[1].c_str());
} else {
std::cout << "*Unknown command" << std::endl;
}
PrintPrompt();
return true;
}
int main(int argc, char *argv[]) {
char *domain;
char *port_str;
int port_num;
char *username;
char *input;
char *output = (char *) "";
fd_set read_set;
int result;
char stdin_buffer[SAY_MAX + 1];
char *stdin_buffer_pointer = stdin_buffer;
char receive_buffer[kBufferSize];
memset(&receive_buffer, 0, kBufferSize);
if (argc < 4) {
Error("usage: client [server name] [port] [username]");
}
domain = argv[1];
port_str = argv[2];
port_num = atoi(argv[2]);
username = argv[3];
if (strlen(domain) > UNIX_PATH_MAX) {
Error("client: server name must be less than 108 characters");
}
if (port_num < 0 || port_num > 65535) {
Error("client: port number must be between 0 and 65535");
}
if (strlen(username) > USERNAME_MAX) {
Error("client: username must be less than 32 characters");
}
CreateSocket(domain, port_str);
SendLogin(username);
current_channel = (char *) "Common";
channels.push_back(current_channel);
SendJoin(current_channel);
if (raw_mode() != 0){
Error("client: error using raw mode");
}
PrintPrompt();
while (1) {
FD_ZERO(&read_set);
FD_SET(client_socket, &read_set);
FD_SET(STDIN_FILENO, &read_set);
if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {
Error("client: problem using select");
}
if (result > 0) {
if (FD_ISSET(STDIN_FILENO, &read_set)) {
// User entered a char.
char c = (char) getchar();
if (c == '\n') {
// Increments pointer and adds NULL char.
*stdin_buffer_pointer++ = '\0';
// Resets stdin_buffer_pointer to the start of stdin_buffer.
stdin_buffer_pointer = stdin_buffer;
std::cout << "\n" << std::flush;
// Prevents output from printing on the new prompt after a newline char.
output = (char *) "";
input = stdin_buffer;
if (input[0] == '/') {
if (!ProcessInput(input)) {
break;
}
} else {
// Sends chat messages.
SendSay(input);
}
} else if (stdin_buffer_pointer != stdin_buffer + SAY_MAX) {
// Increments pointer and adds char c.
*stdin_buffer_pointer++ = c;
std::cout << c << std::flush;
// Copies pointer into output.
output = stdin_buffer_pointer;
// Increments and sets NULL char.
*output++ = '\0';
// Copies stdin_buffer into part of output before NULL char.
output = stdin_buffer;
}
} else if (FD_ISSET(client_socket, &read_set)) {
// Socket has data.
ssize_t read_size = read(client_socket, receive_buffer, kBufferSize);
if (read_size != 0) {
struct text message;
memcpy(&message, receive_buffer, sizeof(struct text));
text_t text_type = message.txt_type;
switch (text_type) {
case TXT_SAY:
HandleTextSay(receive_buffer, output);
break;
default:
break;
}
}
memset(&receive_buffer, 0, SAY_MAX);
} // end of if client_socket
} // end of if result
} // end of while
return 0;
}<|endoftext|> |
<commit_before><commit_msg>This change is patched from http://codereview.chromium.org/276071 by [email protected]<commit_after><|endoftext|> |
<commit_before>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
#define WIN_SIZE 16
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int base; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
base = 0; //initialize base
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[3];
memcpy(sns, &p[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &p[2], 6);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[8], 122);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
cout << "cs: " << cs << endl;
cout << "pk.generateCheckSum(): " << pk.generateCheckSum() << endl;
if(!(sn >= base && sn < base + WIN_SIZE)) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - base;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * sns = new char[3];
memcpy(sns, &packet[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &packet[2], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
int x = boost::lexical_cast<int>(sns);
cout << "sns: " << sns << endl;
cout << "x (sns as int): " << x << endl;
if(x == base) base++; //increment base of window //FIXME
file << dataPull;
file.flush();
}
cout << "Sent response: ";
cout << "ACK " << base << endl;
if(packet[6] == '1') usleep(delayT*1000);
string wbs = to_string((long long)base);
const char * ackval = wbs.c_str();
if(sendto(s, ackval, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<commit_msg>Possibly fix checksum verification<commit_after>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
#define WIN_SIZE 16
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int base; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
base = 0; //initialize base
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[3];
memcpy(sns, &p[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &p[2], 5);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[8], 122);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
cout << "cs: " << cs << endl;
cout << "pk.generateCheckSum(): " << pk.generateCheckSum() << endl;
if(!(sn >= base && sn < base + WIN_SIZE)) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - base;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * sns = new char[3];
memcpy(sns, &packet[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &packet[2], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
int x = boost::lexical_cast<int>(sns);
cout << "sns: " << sns << endl;
cout << "x (sns as int): " << x << endl;
if(x == base) base++; //increment base of window //FIXME
file << dataPull;
file.flush();
}
cout << "Sent response: ";
cout << "ACK " << base << endl;
if(packet[6] == '1') usleep(delayT*1000);
string wbs = to_string((long long)base);
const char * ackval = wbs.c_str();
if(sendto(s, ackval, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<|endoftext|> |
<commit_before><commit_msg>Fix a leak in newly added sync channel unit tests.<commit_after><|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Libmemcached library
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* Copyright (C) 2006-2009 Brian Aker All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <libmemcached/common.h>
inline static memcached_return_t _string_check(memcached_string_st *string, size_t need)
{
if (need && need > (size_t)(string->current_size - (size_t)(string->end - string->string)))
{
size_t current_offset= (size_t) (string->end - string->string);
/* This is the block multiplier. To keep it larger and surive division errors we must round it up */
size_t adjust= (need - (size_t)(string->current_size - (size_t)(string->end - string->string))) / MEMCACHED_BLOCK_SIZE;
adjust++;
size_t new_size= sizeof(char) * (size_t)((adjust * MEMCACHED_BLOCK_SIZE) + string->current_size);
/* Test for overflow */
if (new_size < need)
{
char error_message[1024];
int error_message_length= snprintf(error_message, sizeof(error_message),"Needed %ld, got %ld", (long)need, (long)new_size);
return memcached_set_error(*string->root, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT, error_message, error_message_length);
}
char *new_value= libmemcached_xrealloc(string->root, string->string, new_size, char);
if (new_value == NULL)
{
return memcached_set_error(*string->root, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
}
string->string= new_value;
string->end= string->string + current_offset;
string->current_size+= (MEMCACHED_BLOCK_SIZE * adjust);
}
return MEMCACHED_SUCCESS;
}
static inline void _init_string(memcached_string_st *self)
{
self->current_size= 0;
self->end= self->string= NULL;
}
memcached_string_st *memcached_string_create(Memcached *memc, memcached_string_st *self, size_t initial_size)
{
WATCHPOINT_ASSERT(memc);
/* Saving malloc calls :) */
if (self)
{
WATCHPOINT_ASSERT(self->options.is_initialized == false);
memcached_set_allocated(self, false);
}
else
{
self= libmemcached_xmalloc(memc, memcached_string_st);
if (self == NULL)
{
return NULL;
}
memcached_set_allocated(self, true);
}
self->root= memc;
_init_string(self);
if (memcached_failed(_string_check(self, initial_size)))
{
if (memcached_is_allocated(self))
{
libmemcached_free(memc, self);
}
return NULL;
}
memcached_set_initialized(self, true);
WATCHPOINT_ASSERT(self->string == self->end);
return self;
}
static memcached_return_t memcached_string_append_null(memcached_string_st& string)
{
if (memcached_failed(_string_check(&string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string.end= 0;
return MEMCACHED_SUCCESS;
}
static memcached_return_t memcached_string_append_null(memcached_string_st *string)
{
if (memcached_failed(_string_check(string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string->end= 0;
return MEMCACHED_SUCCESS;
}
memcached_return_t memcached_string_append_character(memcached_string_st *string,
char character)
{
if (memcached_failed(_string_check(string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string->end= character;
string->end++;
return MEMCACHED_SUCCESS;
}
memcached_return_t memcached_string_append(memcached_string_st *string,
const char *value, size_t length)
{
if (memcached_failed(_string_check(string, length)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
WATCHPOINT_ASSERT(length <= string->current_size);
WATCHPOINT_ASSERT(string->string);
WATCHPOINT_ASSERT(string->end >= string->string);
memcpy(string->end, value, length);
string->end+= length;
return MEMCACHED_SUCCESS;
}
char *memcached_string_c_copy(memcached_string_st *string)
{
if (memcached_string_length(string) == 0)
{
return NULL;
}
char *c_ptr= static_cast<char *>(libmemcached_malloc(string->root, (memcached_string_length(string)+1) * sizeof(char)));
if (c_ptr == NULL)
{
return NULL;
}
memcpy(c_ptr, memcached_string_value(string), memcached_string_length(string));
c_ptr[memcached_string_length(string)]= 0;
return c_ptr;
}
bool memcached_string_set(memcached_string_st& string, const char* value, size_t length)
{
memcached_string_reset(&string);
if (memcached_success(memcached_string_append(&string, value, length)))
{
memcached_string_append_null(string);
return true;
}
return false;
}
void memcached_string_reset(memcached_string_st *string)
{
string->end= string->string;
}
void memcached_string_free(memcached_string_st& ptr)
{
memcached_string_free(&ptr);
}
void memcached_string_free(memcached_string_st *ptr)
{
if (ptr == NULL)
{
return;
}
if (ptr->string)
{
libmemcached_free(ptr->root, ptr->string);
}
if (memcached_is_allocated(ptr))
{
libmemcached_free(ptr->root, ptr);
}
else
{
ptr->options.is_initialized= false;
}
}
memcached_return_t memcached_string_check(memcached_string_st *string, size_t need)
{
return _string_check(string, need);
}
bool memcached_string_resize(memcached_string_st& string, const size_t need)
{
return memcached_success(_string_check(&string, need));
}
size_t memcached_string_length(const memcached_string_st *self)
{
return size_t(self->end -self->string);
}
size_t memcached_string_length(const memcached_string_st& self)
{
return size_t(self.end -self.string);
}
size_t memcached_string_size(const memcached_string_st *self)
{
return self->current_size;
}
const char *memcached_string_value(const memcached_string_st *self)
{
return self->string;
}
const char *memcached_string_value(const memcached_string_st& self)
{
return self.string;
}
char *memcached_string_take_value(memcached_string_st *self)
{
char* value= NULL;
if (memcached_string_length(self))
{
assert_msg(self, "Invalid memcached_string_st");
// If we fail at adding the null, we copy and move on
if (memcached_success(memcached_string_append_null(self)))
{
return memcached_string_c_copy(self);
}
value= self->string;
_init_string(self);
}
return value;
}
char *memcached_string_value_mutable(const memcached_string_st *self)
{
return self->string;
}
char *memcached_string_c_str(memcached_string_st& self)
{
return self.string;
}
void memcached_string_set_length(memcached_string_st *self, size_t length)
{
self->end= self->string +length;
}
void memcached_string_set_length(memcached_string_st& self, const size_t length)
{
assert(self.current_size >= length);
size_t set_length= length;
if (self.current_size > length)
{
if (memcached_failed(_string_check(&self, length)))
{
set_length= self.current_size;
}
}
self.end= self.string +set_length;
}
<commit_msg>Fix bad if path<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Libmemcached library
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* Copyright (C) 2006-2009 Brian Aker All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <libmemcached/common.h>
inline static memcached_return_t _string_check(memcached_string_st *string, size_t need)
{
if (need && need > (size_t)(string->current_size - (size_t)(string->end - string->string)))
{
size_t current_offset= (size_t) (string->end - string->string);
/* This is the block multiplier. To keep it larger and surive division errors we must round it up */
size_t adjust= (need - (size_t)(string->current_size - (size_t)(string->end - string->string))) / MEMCACHED_BLOCK_SIZE;
adjust++;
size_t new_size= sizeof(char) * (size_t)((adjust * MEMCACHED_BLOCK_SIZE) + string->current_size);
/* Test for overflow */
if (new_size < need)
{
char error_message[1024];
int error_message_length= snprintf(error_message, sizeof(error_message),"Needed %ld, got %ld", (long)need, (long)new_size);
return memcached_set_error(*string->root, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT, error_message, error_message_length);
}
char *new_value= libmemcached_xrealloc(string->root, string->string, new_size, char);
if (new_value == NULL)
{
return memcached_set_error(*string->root, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
}
string->string= new_value;
string->end= string->string + current_offset;
string->current_size+= (MEMCACHED_BLOCK_SIZE * adjust);
}
return MEMCACHED_SUCCESS;
}
static inline void _init_string(memcached_string_st *self)
{
self->current_size= 0;
self->end= self->string= NULL;
}
memcached_string_st *memcached_string_create(Memcached *memc, memcached_string_st *self, size_t initial_size)
{
WATCHPOINT_ASSERT(memc);
/* Saving malloc calls :) */
if (self)
{
WATCHPOINT_ASSERT(self->options.is_initialized == false);
memcached_set_allocated(self, false);
}
else
{
self= libmemcached_xmalloc(memc, memcached_string_st);
if (self == NULL)
{
return NULL;
}
memcached_set_allocated(self, true);
}
self->root= memc;
_init_string(self);
if (memcached_failed(_string_check(self, initial_size)))
{
if (memcached_is_allocated(self))
{
libmemcached_free(memc, self);
}
return NULL;
}
memcached_set_initialized(self, true);
WATCHPOINT_ASSERT(self->string == self->end);
return self;
}
static memcached_return_t memcached_string_append_null(memcached_string_st& string)
{
if (memcached_failed(_string_check(&string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string.end= 0;
return MEMCACHED_SUCCESS;
}
static memcached_return_t memcached_string_append_null(memcached_string_st *string)
{
if (memcached_failed(_string_check(string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string->end= 0;
return MEMCACHED_SUCCESS;
}
memcached_return_t memcached_string_append_character(memcached_string_st *string,
char character)
{
if (memcached_failed(_string_check(string, 1)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
*string->end= character;
string->end++;
return MEMCACHED_SUCCESS;
}
memcached_return_t memcached_string_append(memcached_string_st *string,
const char *value, size_t length)
{
if (memcached_failed(_string_check(string, length)))
{
return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
}
WATCHPOINT_ASSERT(length <= string->current_size);
WATCHPOINT_ASSERT(string->string);
WATCHPOINT_ASSERT(string->end >= string->string);
memcpy(string->end, value, length);
string->end+= length;
return MEMCACHED_SUCCESS;
}
char *memcached_string_c_copy(memcached_string_st *string)
{
if (memcached_string_length(string) == 0)
{
return NULL;
}
char *c_ptr= static_cast<char *>(libmemcached_malloc(string->root, (memcached_string_length(string)+1) * sizeof(char)));
if (c_ptr == NULL)
{
return NULL;
}
memcpy(c_ptr, memcached_string_value(string), memcached_string_length(string));
c_ptr[memcached_string_length(string)]= 0;
return c_ptr;
}
bool memcached_string_set(memcached_string_st& string, const char* value, size_t length)
{
memcached_string_reset(&string);
if (memcached_success(memcached_string_append(&string, value, length)))
{
memcached_string_append_null(string);
return true;
}
return false;
}
void memcached_string_reset(memcached_string_st *string)
{
string->end= string->string;
}
void memcached_string_free(memcached_string_st& ptr)
{
memcached_string_free(&ptr);
}
void memcached_string_free(memcached_string_st *ptr)
{
if (ptr == NULL)
{
return;
}
if (ptr->string)
{
libmemcached_free(ptr->root, ptr->string);
}
if (memcached_is_allocated(ptr))
{
libmemcached_free(ptr->root, ptr);
}
else
{
ptr->options.is_initialized= false;
}
}
memcached_return_t memcached_string_check(memcached_string_st *string, size_t need)
{
return _string_check(string, need);
}
bool memcached_string_resize(memcached_string_st& string, const size_t need)
{
return memcached_success(_string_check(&string, need));
}
size_t memcached_string_length(const memcached_string_st *self)
{
return size_t(self->end -self->string);
}
size_t memcached_string_length(const memcached_string_st& self)
{
return size_t(self.end -self.string);
}
size_t memcached_string_size(const memcached_string_st *self)
{
return self->current_size;
}
const char *memcached_string_value(const memcached_string_st *self)
{
return self->string;
}
const char *memcached_string_value(const memcached_string_st& self)
{
return self.string;
}
char *memcached_string_take_value(memcached_string_st *self)
{
char* value= NULL;
assert_msg(self, "Invalid memcached_string_st");
if (self)
{
if (memcached_string_length(self))
{
// If we fail at adding the null, we copy and move on
if (memcached_failed(memcached_string_append_null(self)))
{
return NULL;
}
value= self->string;
_init_string(self);
}
}
return value;
}
char *memcached_string_value_mutable(const memcached_string_st *self)
{
return self->string;
}
char *memcached_string_c_str(memcached_string_st& self)
{
return self.string;
}
void memcached_string_set_length(memcached_string_st *self, size_t length)
{
self->end= self->string +length;
}
void memcached_string_set_length(memcached_string_st& self, const size_t length)
{
assert(self.current_size >= length);
size_t set_length= length;
if (self.current_size > length)
{
if (memcached_failed(_string_check(&self, length)))
{
set_length= self.current_size;
}
}
self.end= self.string +set_length;
}
<|endoftext|> |
<commit_before>#include "CppUnitTest.h"
#include <algorithm>
#include <sstream>
#include <cctype>
#include <string>
#include <vector>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace algo
{
struct token
{
enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };
toktype type;
string name;
};
bool operator==(const token& lhs, const token& rhs)
{
return lhs.type == rhs.type
&& lhs.name == rhs.name;
}
struct ascii_tree
{
static vector<token> tokenize(const string& s)
{
vector<token> tokens;
enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;
size_t marker = 0, marked_length = 0;
for (size_t i = 0; i < s.size(); ++i)
{
auto ch = s[i];
if (ch == '[')
{
prev = open_square_brace;
}
else if (ch == ']')
{
if (prev == asterisk)
{
tokens.emplace_back(token { token::root_node, "" });
}
else
{
tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });
}
prev = close_square_brace;
}
else if (ch == '*')
{
prev = asterisk;
}
else if (ch == '-')
{
if (prev == name_char)
{
tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });
}
prev = dash;
}
else if (ch == '/')
{
tokens.emplace_back(token { token::ascending_edge_part, "" });
}
else if (ch == '\\')
{
tokens.emplace_back(token { token::descending_edge_part, "" });
}
else if (ch == '|')
{
tokens.emplace_back(token { token::vertical_edge_part, "" });
}
else if (isalnum(ch) || ch == '_')
{
if (prev != name_char)
{
marker = i;
marked_length = 0;
}
prev = name_char;
++marked_length;
}
}
if (prev == name_char)
{
tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });
}
return tokens;
}
};
}
namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework
{
template<>
wstring ToString<algo::token::toktype>(const algo::token::toktype& type)
{
switch (type)
{
case algo::token::root_node:
return L"root_node";
case algo::token::named_node:
return L"named_node";
case algo::token::edge_name:
return L"edge_name";
case algo::token::horizontal_edge:
return L"horizontal_edge";
case algo::token::ascending_edge_part:
return L"ascending_edge_part";
case algo::token::descending_edge_part:
return L"descending_edge_part";
case algo::token::vertical_edge_part:
return L"vertical_edge_part";
default:
return L"unknown token";
}
}
}}}
namespace algo { namespace spec
{
TEST_CLASS(can_recognize_ascii_tree_tokens)
{
void TokensShouldMatch_(std::initializer_list<token> expected, vector<token>& actual)
{
auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());
if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())
{
wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());
wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());
wstring message = L"Expected: " + ToString(mismatch_pair.first->type) + L" \"" + expectedName + L"\" "
+ L"Actual: " + ToString(mismatch_pair.second->type) + L" \"" + actualName + L"\"";
Assert::Fail(message.c_str());
}
}
public:
TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)
{
auto tokens = ascii_tree::tokenize("");
Assert::IsTrue(tokens.empty());
}
TEST_METHOD(should_recognize_a_root_node)
{
auto tokens = ascii_tree::tokenize("[*]");
Assert::AreEqual(token::root_node, tokens.front().type);
}
TEST_METHOD(should_recognize_a_root_node_with_spaces)
{
auto tokens = ascii_tree::tokenize(" [ * ]");
Assert::AreEqual(token::root_node, tokens.front().type);
}
TEST_METHOD(should_recognize_a_named_node)
{
const string all_chars = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
auto tokens = ascii_tree::tokenize("[" + all_chars + "]");
Assert::AreEqual(token::named_node, tokens.front().type);
Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_named_node_with_spaces)
{
auto tokens = ascii_tree::tokenize(" [ a ]");
Assert::AreEqual(token::named_node, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_edge_name)
{
auto tokens = ascii_tree::tokenize("a");
Assert::AreEqual(token::edge_name, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_edge_name_with_spaces)
{
auto tokens = ascii_tree::tokenize(" a ");
Assert::AreEqual(token::edge_name, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_ascending_edge_part)
{
auto tokens = ascii_tree::tokenize("/");
Assert::AreEqual(token::ascending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" / ");
Assert::AreEqual(token::ascending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_descending_edge_part)
{
auto tokens = ascii_tree::tokenize("\\");
Assert::AreEqual(token::descending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" \\ ");
Assert::AreEqual(token::descending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_vertical_edge_part)
{
auto tokens = ascii_tree::tokenize("|");
Assert::AreEqual(token::vertical_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" | ");
Assert::AreEqual(token::vertical_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_horizontal_edge)
{
auto tokens = ascii_tree::tokenize("-a-");
Assert::AreEqual(token::horizontal_edge, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)
{
auto tokens = ascii_tree::tokenize(" - a - ");
Assert::AreEqual(token::horizontal_edge, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)
{
auto expected_tokens =
{
token { token::root_node, "" },
token { token::named_node, "a" }
};
auto tokens = ascii_tree::tokenize("[*][a]");
TokensShouldMatch_(expected_tokens, tokens);
}
TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)
{
auto expected_tokens =
{
token { token::root_node, "" },
token { token::horizontal_edge, "a" }
};
auto tokens = ascii_tree::tokenize("[*]-a-");
TokensShouldMatch_(expected_tokens, tokens);
}
TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)
{
auto expected_tokens =
{
token { token::horizontal_edge, "a" },
token { token::named_node, "b" }
};
auto tokens = ascii_tree::tokenize("-a-[b]");
TokensShouldMatch_(expected_tokens, tokens);
}
};
}}
<commit_msg>simplify tests<commit_after>#include "CppUnitTest.h"
#include <algorithm>
#include <sstream>
#include <cctype>
#include <string>
#include <vector>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace algo
{
struct token
{
enum toktype { root_node, named_node, edge_name, horizontal_edge, ascending_edge_part, descending_edge_part, vertical_edge_part };
toktype type;
string name;
};
bool operator==(const token& lhs, const token& rhs)
{
return lhs.type == rhs.type
&& lhs.name == rhs.name;
}
struct ascii_tree
{
static vector<token> tokenize(const string& s)
{
vector<token> tokens;
enum { none, open_square_brace, close_square_brace, asterisk, dash, name_char } prev = none;
size_t marker = 0, marked_length = 0;
for (size_t i = 0; i < s.size(); ++i)
{
auto ch = s[i];
if (ch == '[')
{
prev = open_square_brace;
}
else if (ch == ']')
{
if (prev == asterisk)
{
tokens.emplace_back(token { token::root_node, "" });
}
else
{
tokens.emplace_back(token { token::named_node, s.substr(marker, marked_length) });
}
prev = close_square_brace;
}
else if (ch == '*')
{
prev = asterisk;
}
else if (ch == '-')
{
if (prev == name_char)
{
tokens.emplace_back(token { token::horizontal_edge, s.substr(marker, marked_length) });
}
prev = dash;
}
else if (ch == '/')
{
tokens.emplace_back(token { token::ascending_edge_part, "" });
}
else if (ch == '\\')
{
tokens.emplace_back(token { token::descending_edge_part, "" });
}
else if (ch == '|')
{
tokens.emplace_back(token { token::vertical_edge_part, "" });
}
else if (isalnum(ch) || ch == '_')
{
if (prev != name_char)
{
marker = i;
marked_length = 0;
}
prev = name_char;
++marked_length;
}
}
if (prev == name_char)
{
tokens.emplace_back(token { token::edge_name, s.substr(marker, marked_length) });
}
return tokens;
}
};
}
namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework
{
template<>
wstring ToString<algo::token::toktype>(const algo::token::toktype& type)
{
switch (type)
{
case algo::token::root_node:
return L"root_node";
case algo::token::named_node:
return L"named_node";
case algo::token::edge_name:
return L"edge_name";
case algo::token::horizontal_edge:
return L"horizontal_edge";
case algo::token::ascending_edge_part:
return L"ascending_edge_part";
case algo::token::descending_edge_part:
return L"descending_edge_part";
case algo::token::vertical_edge_part:
return L"vertical_edge_part";
default:
return L"unknown token";
}
}
}}}
namespace algo { namespace spec
{
TEST_CLASS(can_recognize_ascii_tree_tokens)
{
void tokens_should_match_(std::initializer_list<token> expected, vector<token>& actual)
{
auto mismatch_pair = std::mismatch(expected.begin(), expected.end(), actual.begin());
if (mismatch_pair.first != expected.end() || mismatch_pair.second != actual.end())
{
wstring expectedName(mismatch_pair.first->name.begin(), mismatch_pair.first->name.end());
wstring actualName(mismatch_pair.second->name.begin(), mismatch_pair.second->name.end());
wstring message = L"Expected: " + ToString(mismatch_pair.first->type) + L" \"" + expectedName + L"\" "
+ L"Actual: " + ToString(mismatch_pair.second->type) + L" \"" + actualName + L"\"";
Assert::Fail(message.c_str());
}
}
public:
TEST_METHOD(should_not_recognize_any_tokens_in_an_empty_string)
{
auto tokens = ascii_tree::tokenize("");
Assert::IsTrue(tokens.empty());
}
TEST_METHOD(should_recognize_a_root_node)
{
auto tokens = ascii_tree::tokenize("[*]");
Assert::AreEqual(token::root_node, tokens.front().type);
}
TEST_METHOD(should_recognize_a_root_node_with_spaces)
{
auto tokens = ascii_tree::tokenize(" [ * ]");
Assert::AreEqual(token::root_node, tokens.front().type);
}
TEST_METHOD(should_recognize_a_named_node)
{
const string all_chars = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
auto tokens = ascii_tree::tokenize("[" + all_chars + "]");
Assert::AreEqual(token::named_node, tokens.front().type);
Assert::AreEqual(all_chars.c_str(), tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_named_node_with_spaces)
{
auto tokens = ascii_tree::tokenize(" [ a ]");
Assert::AreEqual(token::named_node, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_edge_name)
{
auto tokens = ascii_tree::tokenize("a");
Assert::AreEqual(token::edge_name, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_edge_name_with_spaces)
{
auto tokens = ascii_tree::tokenize(" a ");
Assert::AreEqual(token::edge_name, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_an_ascending_edge_part)
{
auto tokens = ascii_tree::tokenize("/");
Assert::AreEqual(token::ascending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_an_ascending_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" / ");
Assert::AreEqual(token::ascending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_descending_edge_part)
{
auto tokens = ascii_tree::tokenize("\\");
Assert::AreEqual(token::descending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_descending_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" \\ ");
Assert::AreEqual(token::descending_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_vertical_edge_part)
{
auto tokens = ascii_tree::tokenize("|");
Assert::AreEqual(token::vertical_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_vertical_edge_part_with_spaces)
{
auto tokens = ascii_tree::tokenize(" | ");
Assert::AreEqual(token::vertical_edge_part, tokens.front().type);
}
TEST_METHOD(should_recognize_a_horizontal_edge)
{
auto tokens = ascii_tree::tokenize("-a-");
Assert::AreEqual(token::horizontal_edge, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_horizontal_edge_with_spaces)
{
auto tokens = ascii_tree::tokenize(" - a - ");
Assert::AreEqual(token::horizontal_edge, tokens.front().type);
Assert::AreEqual("a", tokens.front().name.c_str());
}
TEST_METHOD(should_recognize_a_root_node_next_to_a_named_node)
{
auto tokens = ascii_tree::tokenize("[*][a]");
tokens_should_match_({ { token::root_node, "" }, { token::named_node, "a" } }, tokens);
}
TEST_METHOD(should_recognize_a_root_node_next_to_a_horizontal_edge)
{
auto tokens = ascii_tree::tokenize("[*]-a-");
tokens_should_match_({ { token::root_node, "" }, { token::horizontal_edge, "a" } }, tokens);
}
TEST_METHOD(should_recognize_a_horizontal_edge_next_to_a_named_node)
{
auto tokens = ascii_tree::tokenize("-a-[b]");
tokens_should_match_({ { token::horizontal_edge, "a" }, { token::named_node, "b" } }, tokens);
}
};
}}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2012, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <new>
#include <cstdint>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_gpio.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "hardware.hxx"
#include "TivaDev.hxx"
#include "TivaEEPROMEmulation.hxx"
#include "TivaEEPROMBitSet.hxx"
#include "TivaGPIO.hxx"
#include "DummyGPIO.hxx"
#include "bootloader_hal.h"
struct Debug
{
typedef DummyPin DccPacketDelay;
typedef DummyPin DccDecodeInterrupts;
typedef DummyPin CapTimerOverflow;
};
#include "TivaDCCDecoder.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));
/** UART 0 serial driver instance */
static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
const unsigned TivaEEPROMEmulation::FAMILY = TM4C123;
const size_t EEPROMEmulation::SECTOR_SIZE = (4*1024);
static TivaEEPROMEmulation eeprom("/dev/eeprom", 1500);
extern StoredBitSet* g_gpio_stored_bit_set;
StoredBitSet* g_gpio_stored_bit_set = nullptr;
constexpr unsigned EEPROM_BIT_COUNT = 84;
constexpr unsigned EEPROM_BITS_PER_CELL = 28;
extern "C" {
void hw_set_to_safe(void);
void enter_bootloader()
{
extern void (* const __interrupt_vector[])(void);
if (__interrupt_vector[1] == __interrupt_vector[13] ||
__interrupt_vector[13] == nullptr) {
// No bootloader detected.
return;
}
hw_set_to_safe();
__bootloader_magic_ptr = REQUEST_BOOTLOADER;
/* Globally disables interrupts. */
asm("cpsid i\n");
extern char __flash_start;
asm volatile(" mov r3, %[flash_addr] \n"
:
: [flash_addr] "r"(&__flash_start));
/* Loads SP and jumps to the reset vector. */
asm volatile(
" ldr r0, [r3]\n"
" mov sp, r0\n"
" ldr r0, [r3, #4]\n"
" bx r0\n");
}
}
struct DCCDecode
{
static const auto TIMER_BASE = TIMER2_BASE;
static const auto TIMER_PERIPH = SYSCTL_PERIPH_TIMER2;
static const auto TIMER_INTERRUPT = INT_TIMER2B;
static const auto TIMER = TIMER_B;
static const auto CFG_TIM_CAPTURE =
TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_CAP_TIME;
static const auto CFG_RCOM_TIMER =
TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_PERIODIC;
// Interrupt bits.
static const auto TIMER_CAP_EVENT = TIMER_CAPB_EVENT;
static const auto TIMER_RCOM_MATCH = TIMER_TIMA_MATCH;
// Sets the match register of TIMER to update immediately.
static void clr_tim_mrsu() {
HWREG(TIMER_BASE + TIMER_O_TAMR) &= ~(TIMER_TAMR_TAMRSU);
HWREG(TIMER_BASE + TIMER_O_TAMR) |= (TIMER_TAMR_TAMIE);
}
static void cap_event_hook() {}
static const auto RCOM_TIMER = TIMER_A;
static const auto SAMPLE_PERIOD_CLOCKS = 60000;
//static const auto SAMPLE_TIMER_TIMEOUT = TIMER_TIMA_TIMEOUT;
static const auto RCOM_INTERRUPT = INT_TIMER2A;
static const auto OS_INTERRUPT = INT_WTIMER2A;
typedef DCC_IN_Pin NRZ_Pin;
// 16-bit timer max + use 7 bits of prescaler.
static const uint32_t TIMER_MAX_VALUE = 0x800000UL;
static const uint32_t PS_MAX = 0x80;
static_assert(SAMPLE_PERIOD_CLOCKS < TIMER_MAX_VALUE, "Cannot sample less often than the timer period");
static const int Q_SIZE = 32;
// after 5 overcurrent samples we get one occupancy sample
static const uint32_t OCCUPANCY_SAMPLE_RATIO = 5;
static inline void dcc_before_cutout_hook() {}
static inline void dcc_packet_finished_hook() {}
static inline void after_feedback_hook() {}
};
// Dummy implementation because we are not a railcom detector.
NoRailcomDriver railcom_driver;
/** The input pin for detecting the DCC signal. */
static TivaDccDecoder<DCCDecode> dcc_decoder0("/dev/dcc_decoder0", &railcom_driver);
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static volatile uint32_t rest_pattern = 0;
void hw_set_to_safe(void)
{
GpioInit::hw_set_to_safe();
}
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
static uint32_t nsec_per_clock = 0;
/// Calculate partial timing information from the tick counter.
long long hw_get_partial_tick_time_nsec(void)
{
volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018;
long long tick_val = *tick_current_reg;
tick_val *= nsec_per_clock;
long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val;
if (elapsed < 0) elapsed = 0;
return elapsed;
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
BLINKER_RAW_Pin::set((rest_pattern & 1));
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
void timer2b_interrupt_handler(void)
{
dcc_decoder0.interrupt_handler();
}
void timer2a_interrupt_handler(void)
{
dcc_decoder0.rcom_interrupt_handler();
}
void wide_timer2a_interrupt_handler(void)
{
dcc_decoder0.os_interrupt_handler();
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
nsec_per_clock = 1000000000 / cm3_cpu_clock_hz;
//
// Unlock PF0 so we can change it to a GPIO input
// Once we have enabled (unlocked) the commit register then re-lock it
// to prevent further changes. PF0 is muxed with NMI thus a special case.
//
MAP_SysCtlPeripheralEnable(SW2_Pin::GPIO_PERIPH);
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_CR) |= 0x01;
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_LOCK) = 0;
// Initializes all GPIO and hardware pins.
GpioInit::hw_init();
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* USB interrupt priority */
MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority
/* Checks the SW1 pin at boot time in case we want to allow for a debugger
* to connect. */
asm volatile ("cpsie i\n");
do {
if (!SW2_Pin::get()) {
blinker_pattern = 0xAAAA;
} else {
blinker_pattern = 0;
}
} while (blinker_pattern || rest_pattern);
asm volatile ("cpsid i\n");
g_gpio_stored_bit_set = new EEPROMStoredBitSet<TivaEEPROMHwDefs<EEPROM_BIT_COUNT, EEPROM_BITS_PER_CELL>>(2, 2);
}
} // extern "C"
<commit_msg>fix compilation error.<commit_after>/** \copyright
* Copyright (c) 2012, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* \file HwInit.cxx
* This file represents the hardware initialization for the TI Tiva MCU.
*
* @author Stuart W. Baker
* @date 5 January 2013
*/
#include <new>
#include <cstdint>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_gpio.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "hardware.hxx"
#include "TivaDev.hxx"
#include "TivaEEPROMEmulation.hxx"
#include "TivaEEPROMBitSet.hxx"
#include "TivaGPIO.hxx"
#include "DummyGPIO.hxx"
#include "bootloader_hal.h"
struct Debug
{
typedef DummyPin DccPacketDelay;
typedef DummyPin DccDecodeInterrupts;
typedef DummyPin DccPacketFinishedHook;
typedef DummyPin CapTimerOverflow;
};
#include "TivaDCCDecoder.hxx"
/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";
/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";
/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";
/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));
/** UART 0 serial driver instance */
static TivaUart uart0("/dev/ser0", UART0_BASE, INT_RESOLVE(INT_UART0_, 0));
/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));
const unsigned TivaEEPROMEmulation::FAMILY = TM4C123;
const size_t EEPROMEmulation::SECTOR_SIZE = (4*1024);
static TivaEEPROMEmulation eeprom("/dev/eeprom", 1500);
extern StoredBitSet* g_gpio_stored_bit_set;
StoredBitSet* g_gpio_stored_bit_set = nullptr;
constexpr unsigned EEPROM_BIT_COUNT = 84;
constexpr unsigned EEPROM_BITS_PER_CELL = 28;
extern "C" {
void hw_set_to_safe(void);
void enter_bootloader()
{
extern void (* const __interrupt_vector[])(void);
if (__interrupt_vector[1] == __interrupt_vector[13] ||
__interrupt_vector[13] == nullptr) {
// No bootloader detected.
return;
}
hw_set_to_safe();
__bootloader_magic_ptr = REQUEST_BOOTLOADER;
/* Globally disables interrupts. */
asm("cpsid i\n");
extern char __flash_start;
asm volatile(" mov r3, %[flash_addr] \n"
:
: [flash_addr] "r"(&__flash_start));
/* Loads SP and jumps to the reset vector. */
asm volatile(
" ldr r0, [r3]\n"
" mov sp, r0\n"
" ldr r0, [r3, #4]\n"
" bx r0\n");
}
}
struct DCCDecode
{
static const auto TIMER_BASE = TIMER2_BASE;
static const auto TIMER_PERIPH = SYSCTL_PERIPH_TIMER2;
static const auto TIMER_INTERRUPT = INT_TIMER2B;
static const auto TIMER = TIMER_B;
static const auto CFG_TIM_CAPTURE =
TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_CAP_TIME;
static const auto CFG_RCOM_TIMER =
TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_PERIODIC;
// Interrupt bits.
static const auto TIMER_CAP_EVENT = TIMER_CAPB_EVENT;
static const auto TIMER_RCOM_MATCH = TIMER_TIMA_MATCH;
// Sets the match register of TIMER to update immediately.
static void clr_tim_mrsu() {
HWREG(TIMER_BASE + TIMER_O_TAMR) &= ~(TIMER_TAMR_TAMRSU);
HWREG(TIMER_BASE + TIMER_O_TAMR) |= (TIMER_TAMR_TAMIE);
}
static void cap_event_hook() {}
static const auto RCOM_TIMER = TIMER_A;
static const auto SAMPLE_PERIOD_CLOCKS = 60000;
//static const auto SAMPLE_TIMER_TIMEOUT = TIMER_TIMA_TIMEOUT;
static const auto RCOM_INTERRUPT = INT_TIMER2A;
static const auto OS_INTERRUPT = INT_WTIMER2A;
typedef DCC_IN_Pin NRZ_Pin;
// 16-bit timer max + use 7 bits of prescaler.
static const uint32_t TIMER_MAX_VALUE = 0x800000UL;
static const uint32_t PS_MAX = 0x80;
static_assert(SAMPLE_PERIOD_CLOCKS < TIMER_MAX_VALUE, "Cannot sample less often than the timer period");
static const int Q_SIZE = 32;
// after 5 overcurrent samples we get one occupancy sample
static const uint32_t OCCUPANCY_SAMPLE_RATIO = 5;
static inline void dcc_before_cutout_hook() {}
static inline void dcc_packet_finished_hook() {}
static inline void after_feedback_hook() {}
};
// Dummy implementation because we are not a railcom detector.
NoRailcomDriver railcom_driver;
/** The input pin for detecting the DCC signal. */
static TivaDccDecoder<DCCDecode> dcc_decoder0("/dev/dcc_decoder0", &railcom_driver);
extern "C" {
/** Blink LED */
uint32_t blinker_pattern = 0;
static volatile uint32_t rest_pattern = 0;
void hw_set_to_safe(void)
{
GpioInit::hw_set_to_safe();
}
void resetblink(uint32_t pattern)
{
blinker_pattern = pattern;
/* make a timer event trigger immediately */
}
void setblink(uint32_t pattern)
{
resetblink(pattern);
}
static uint32_t nsec_per_clock = 0;
/// Calculate partial timing information from the tick counter.
long long hw_get_partial_tick_time_nsec(void)
{
volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018;
long long tick_val = *tick_current_reg;
tick_val *= nsec_per_clock;
long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val;
if (elapsed < 0) elapsed = 0;
return elapsed;
}
void timer5a_interrupt_handler(void)
{
//
// Clear the timer interrupt.
//
MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
// Set output LED.
BLINKER_RAW_Pin::set((rest_pattern & 1));
// Shift and maybe reset pattern.
rest_pattern >>= 1;
if (!rest_pattern)
rest_pattern = blinker_pattern;
}
void diewith(uint32_t pattern)
{
vPortClearInterruptMask(0x20);
asm("cpsie i\n");
resetblink(pattern);
while (1)
;
}
void timer2b_interrupt_handler(void)
{
dcc_decoder0.interrupt_handler();
}
void timer2a_interrupt_handler(void)
{
dcc_decoder0.rcom_interrupt_handler();
}
void wide_timer2a_interrupt_handler(void)
{
dcc_decoder0.os_interrupt_handler();
}
/** Initialize the processor hardware.
*/
void hw_preinit(void)
{
/* Globally disables interrupts until the FreeRTOS scheduler is up. */
asm("cpsid i\n");
nsec_per_clock = 1000000000 / cm3_cpu_clock_hz;
//
// Unlock PF0 so we can change it to a GPIO input
// Once we have enabled (unlocked) the commit register then re-lock it
// to prevent further changes. PF0 is muxed with NMI thus a special case.
//
MAP_SysCtlPeripheralEnable(SW2_Pin::GPIO_PERIPH);
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_CR) |= 0x01;
HWREG(SW2_Pin::GPIO_BASE + GPIO_O_LOCK) = 0;
// Initializes all GPIO and hardware pins.
GpioInit::hw_init();
/* Setup the system clock. */
MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
/* Blinker timer initialization. */
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, MAP_SysCtlClockGet() / 8);
MAP_IntEnable(INT_TIMER5A);
/* This interrupt should hit even during kernel operations. */
MAP_IntPrioritySet(INT_TIMER5A, 0);
MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
MAP_TimerEnable(TIMER5_BASE, TIMER_A);
/* USB interrupt priority */
MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority
/* Checks the SW1 pin at boot time in case we want to allow for a debugger
* to connect. */
asm volatile ("cpsie i\n");
do {
if (!SW2_Pin::get()) {
blinker_pattern = 0xAAAA;
} else {
blinker_pattern = 0;
}
} while (blinker_pattern || rest_pattern);
asm volatile ("cpsid i\n");
g_gpio_stored_bit_set = new EEPROMStoredBitSet<TivaEEPROMHwDefs<EEPROM_BIT_COUNT, EEPROM_BITS_PER_CELL>>(2, 2);
}
} // extern "C"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: pluby $ $Date: 2000-11-14 00:18:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = 0;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = NULL;
maFrameData.mnInputLang = 0;
maFrameData.mnInputCodePage = 0;
maFrameData.mbGraphics = FALSE;
maFrameData.mbCaption = FALSE;
maFrameData.mbBorder = FALSE;
maFrameData.mbSizeBorder = FALSE;
maFrameData.mbFullScreen = FALSE;
maFrameData.mbPresentation = FALSE;
maFrameData.mbInShow = FALSE;
maFrameData.mbRestoreMaximize = FALSE;
maFrameData.mbInMoveMsg = FALSE;
maFrameData.mbInSizeMsg = FALSE;
maFrameData.mbFullScreenToolWin = FALSE;
maFrameData.mbDefPos = TRUE;
maFrameData.mbOverwriteState = TRUE;
maFrameData.mbIME = FALSE;
maFrameData.mbHandleIME = FALSE;
maFrameData.mbSpezIME = FALSE;
maFrameData.mbAtCursorIME = FALSE;
maFrameData.mbCompositionMode = FALSE;
maFrameData.mbCandidateMode = FALSE;
memset( &maFrameData.maState, 0, sizeof( SalFrameState ) );
maFrameData.maSysData.nSize = sizeof( SystemEnvData );
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
if ( hView )
{
SalData* pSalData = GetSalData();
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mhWnd = maFrameData.mhWnd;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
maFrameData.mbGraphics = TRUE;
}
}
else
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics* )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void* pData )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char *)aByteTitle.GetBuffer();
VCLWindow_setTitle(maFrameData.mhWnd, pTitle);
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
VCLWindow_makeKeyAndOrderFront( maFrameData.mhWnd );
else
VCLWindow_close( maFrameData.mhWnd );
// This is temporary code for testing only and should be removed when
// development of the SalObject class is complete. This code allows
// us to test our SalGraphics drawing methods.
// Get this window's cached handle to its native content view
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
// Draw a line on the native content view
VCLGraphics_drawLine( hView, 0L, 0L, 1000L, 1000L );
}
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
void SalFrame::UpdateExtTextInputArea()
{
}
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
}
<commit_msg>Added #if statement for SRC612 build<commit_after>/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: pluby $ $Date: 2000-11-14 00:34:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = 0;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = NULL;
maFrameData.mnInputLang = 0;
maFrameData.mnInputCodePage = 0;
maFrameData.mbGraphics = FALSE;
maFrameData.mbCaption = FALSE;
maFrameData.mbBorder = FALSE;
maFrameData.mbSizeBorder = FALSE;
maFrameData.mbFullScreen = FALSE;
maFrameData.mbPresentation = FALSE;
maFrameData.mbInShow = FALSE;
maFrameData.mbRestoreMaximize = FALSE;
maFrameData.mbInMoveMsg = FALSE;
maFrameData.mbInSizeMsg = FALSE;
maFrameData.mbFullScreenToolWin = FALSE;
maFrameData.mbDefPos = TRUE;
maFrameData.mbOverwriteState = TRUE;
maFrameData.mbIME = FALSE;
maFrameData.mbHandleIME = FALSE;
maFrameData.mbSpezIME = FALSE;
maFrameData.mbAtCursorIME = FALSE;
maFrameData.mbCompositionMode = FALSE;
maFrameData.mbCandidateMode = FALSE;
memset( &maFrameData.maState, 0, sizeof( SalFrameState ) );
maFrameData.maSysData.nSize = sizeof( SystemEnvData );
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
if ( hView )
{
SalData* pSalData = GetSalData();
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mhWnd = maFrameData.mhWnd;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
maFrameData.mbGraphics = TRUE;
}
}
else
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics* )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void* pData )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char *)aByteTitle.GetBuffer();
VCLWindow_setTitle(maFrameData.mhWnd, pTitle);
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
VCLWindow_makeKeyAndOrderFront( maFrameData.mhWnd );
else
VCLWindow_close( maFrameData.mhWnd );
// This is temporary code for testing only and should be removed when
// development of the SalObject class is complete. This code allows
// us to test our SalGraphics drawing methods.
// Get this window's cached handle to its native content view
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
// Draw a line on the native content view
VCLGraphics_drawLine( hView, 0L, 0L, 1000L, 1000L );
}
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
#if SUPD < 612
void SalFrame::UpdateExtTextInputArea()
{
}
#endif
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
}
<|endoftext|> |
<commit_before>// Copyright 2014 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 "config.h"
#include "bindings/core/v8/ScriptStreamer.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8ScriptRunner.h"
#include "core/dom/PendingScript.h"
#include "core/frame/Settings.h"
#include "platform/Task.h"
#include "public/platform/Platform.h"
#include <gtest/gtest.h>
#include <v8.h>
namespace blink {
namespace {
class ScriptStreamingTest : public testing::Test {
public:
ScriptStreamingTest()
: m_scope(v8::Isolate::GetCurrent())
, m_settings(Settings::create())
, m_resourceRequest("http://www.streaming-test.com/")
, m_resource(new ScriptResource(m_resourceRequest, "text/utf-8"))
, m_pendingScript(0, m_resource) // Takes ownership of m_resource.
{
m_settings->setV8ScriptStreamingEnabled(true);
m_resource->setLoading(true);
}
ScriptState* scriptState() const { return m_scope.scriptState(); }
v8::Isolate* isolate() const { return m_scope.isolate(); }
void trace(Visitor* visitor)
{
visitor->trace(m_pendingScript);
}
protected:
void appendData(const char* data)
{
m_resource->appendData(data, strlen(data));
// Yield control to the background thread, so that V8 gets a change to
// process the data before the main thread adds more. Note that we
// cannot fully control in what kind of chunks the data is passed to V8
// (if the V8 is not requesting more data between two appendData calls,
// V8 will get both chunks together).
WTF::yield();
}
void appendPadding()
{
for (int i = 0; i < 10; ++i) {
appendData(" /* this is padding to make the script long enough, so "
"that V8's buffer gets filled and it starts processing "
"the data */ ");
}
}
void finish()
{
m_resource->finish();
m_resource->setLoading(false);
}
void processTasksUntilStreamingComplete()
{
while (ScriptStreamerThread::shared()->isRunningTask()) {
WebThread* currentThread = blink::Platform::current()->currentThread();
currentThread->postTask(new Task(WTF::bind(&WebThread::exitRunLoop, currentThread)));
currentThread->enterRunLoop();
}
}
V8TestingScope m_scope;
OwnPtr<Settings> m_settings;
// The Resource and PendingScript where we stream from. These don't really
// fetch any data outside the test; the test controls the data by calling
// ScriptResource::appendData.
ResourceRequest m_resourceRequest;
ScriptResource* m_resource;
PendingScript m_pendingScript;
};
class TestScriptResourceClient : public ScriptResourceClient {
public:
TestScriptResourceClient()
: m_finished(false) { }
virtual void notifyFinished(Resource*) OVERRIDE { m_finished = true; }
bool finished() const { return m_finished; }
private:
bool m_finished;
};
TEST_F(ScriptStreamingTest, CompilingStreamedScript)
{
// Test that we can successfully compile a streamed script.
bool started = ScriptStreamer::startStreaming(m_pendingScript, m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
m_pendingScript.watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendPadding();
appendData("return 5; }");
appendPadding();
appendData("foo();");
EXPECT_FALSE(client.finished());
finish();
// Process tasks on the main thread until the streaming background thread
// has completed its tasks.
processTasksUntilStreamingComplete();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = m_pendingScript.getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
EXPECT_TRUE(sourceCode.streamer());
v8::TryCatch tryCatch;
v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(sourceCode, isolate());
EXPECT_FALSE(script.IsEmpty());
EXPECT_FALSE(tryCatch.HasCaught());
}
TEST_F(ScriptStreamingTest, CompilingStreamedScriptWithParseError)
{
// Test that scripts with parse errors are handled properly. In those cases,
// the V8 side typically finished before loading finishes: make sure we
// handle it gracefully.
bool started = ScriptStreamer::startStreaming(m_pendingScript, m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
m_pendingScript.watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendData("this is the part which will be a parse error");
// V8 won't realize the parse error until it actually starts parsing the
// script, and this happens only when its buffer is filled.
appendPadding();
EXPECT_FALSE(client.finished());
// Force the V8 side to finish before the loading.
processTasksUntilStreamingComplete();
EXPECT_FALSE(client.finished());
finish();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = m_pendingScript.getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
EXPECT_TRUE(sourceCode.streamer());
v8::TryCatch tryCatch;
v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(sourceCode, isolate());
EXPECT_TRUE(script.IsEmpty());
EXPECT_TRUE(tryCatch.HasCaught());
}
TEST_F(ScriptStreamingTest, CancellingStreaming)
{
// Test that the upper layers (PendingScript and up) can be ramped down
// while streaming is ongoing, and ScriptStreamer handles it gracefully.
bool started = ScriptStreamer::startStreaming(m_pendingScript, m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
m_pendingScript.watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
// In general, we cannot control what the background thread is doing
// (whether it's parsing or waiting for more data). In this test, we have
// given it so little data that it's surely waiting for more.
// Simulate cancelling the network load (e.g., because the user navigated
// away).
EXPECT_FALSE(client.finished());
m_pendingScript.stopWatchingForLoad(&client);
m_pendingScript = PendingScript(); // This will destroy m_resource.
m_resource = 0;
// The V8 side will complete too. This should not crash. We don't receive
// any results from the streaming and the client doesn't get notified.
processTasksUntilStreamingComplete();
EXPECT_FALSE(client.finished());
}
TEST_F(ScriptStreamingTest, SuppressingStreaming)
{
// If we notice during streaming that there is a code cache, streaming
// is suppressed (V8 doesn't parse while the script is loading), and the
// upper layer (ScriptResourceClient) should get a notification when the
// script is loaded.
bool started = ScriptStreamer::startStreaming(m_pendingScript, m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
m_pendingScript.watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendPadding();
m_resource->setCachedMetadata(V8ScriptRunner::tagForCodeCache(), "X", 1, Resource::CacheLocally);
appendPadding();
finish();
processTasksUntilStreamingComplete();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = m_pendingScript.getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
// ScriptSourceCode doesn't refer to the streamer, since we have suppressed
// the streaming and resumed the non-streaming code path for script
// compilation.
EXPECT_FALSE(sourceCode.streamer());
}
} // namespace
} // namespace blink
<commit_msg>Oilpan: have ScriptStreamingTest correctly trace its PendingScript.<commit_after>// Copyright 2014 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 "config.h"
#include "bindings/core/v8/ScriptStreamer.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8ScriptRunner.h"
#include "core/dom/PendingScript.h"
#include "core/frame/Settings.h"
#include "platform/Task.h"
#include "platform/heap/Handle.h"
#include "public/platform/Platform.h"
#include <gtest/gtest.h>
#include <v8.h>
namespace blink {
namespace {
// For the benefit of Oilpan, put the part object PendingScript inside
// a wrapper that's on the Oilpan heap and hold a reference to that wrapper
// from ScriptStreamingTest.
class PendingScriptWrapper : public NoBaseWillBeGarbageCollectedFinalized<PendingScriptWrapper> {
public:
static PassOwnPtrWillBeRawPtr<PendingScriptWrapper> create()
{
return adoptPtrWillBeNoop(new PendingScriptWrapper());
}
static PassOwnPtrWillBeRawPtr<PendingScriptWrapper> create(Element* element, ScriptResource* resource)
{
return adoptPtrWillBeNoop(new PendingScriptWrapper(element, resource));
}
PendingScript& get() { return m_pendingScript; }
void trace(Visitor* visitor)
{
visitor->trace(m_pendingScript);
}
private:
PendingScriptWrapper()
{
}
PendingScriptWrapper(Element* element, ScriptResource* resource)
: m_pendingScript(PendingScript(element, resource))
{
}
PendingScript m_pendingScript;
};
class ScriptStreamingTest : public testing::Test {
public:
ScriptStreamingTest()
: m_scope(v8::Isolate::GetCurrent())
, m_settings(Settings::create())
, m_resourceRequest("http://www.streaming-test.com/")
, m_resource(new ScriptResource(m_resourceRequest, "text/utf-8"))
, m_pendingScript(PendingScriptWrapper::create(0, m_resource)) // Takes ownership of m_resource.
{
m_settings->setV8ScriptStreamingEnabled(true);
m_resource->setLoading(true);
}
ScriptState* scriptState() const { return m_scope.scriptState(); }
v8::Isolate* isolate() const { return m_scope.isolate(); }
PendingScript& pendingScript() const { return m_pendingScript->get(); }
protected:
void appendData(const char* data)
{
m_resource->appendData(data, strlen(data));
// Yield control to the background thread, so that V8 gets a change to
// process the data before the main thread adds more. Note that we
// cannot fully control in what kind of chunks the data is passed to V8
// (if the V8 is not requesting more data between two appendData calls,
// V8 will get both chunks together).
WTF::yield();
}
void appendPadding()
{
for (int i = 0; i < 10; ++i) {
appendData(" /* this is padding to make the script long enough, so "
"that V8's buffer gets filled and it starts processing "
"the data */ ");
}
}
void finish()
{
m_resource->finish();
m_resource->setLoading(false);
}
void processTasksUntilStreamingComplete()
{
while (ScriptStreamerThread::shared()->isRunningTask()) {
WebThread* currentThread = blink::Platform::current()->currentThread();
currentThread->postTask(new Task(WTF::bind(&WebThread::exitRunLoop, currentThread)));
currentThread->enterRunLoop();
}
}
V8TestingScope m_scope;
OwnPtr<Settings> m_settings;
// The Resource and PendingScript where we stream from. These don't really
// fetch any data outside the test; the test controls the data by calling
// ScriptResource::appendData.
ResourceRequest m_resourceRequest;
ScriptResource* m_resource;
OwnPtrWillBePersistent<PendingScriptWrapper> m_pendingScript;
};
class TestScriptResourceClient : public ScriptResourceClient {
public:
TestScriptResourceClient()
: m_finished(false) { }
virtual void notifyFinished(Resource*) OVERRIDE { m_finished = true; }
bool finished() const { return m_finished; }
private:
bool m_finished;
};
TEST_F(ScriptStreamingTest, CompilingStreamedScript)
{
// Test that we can successfully compile a streamed script.
bool started = ScriptStreamer::startStreaming(pendingScript(), m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
pendingScript().watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendPadding();
appendData("return 5; }");
appendPadding();
appendData("foo();");
EXPECT_FALSE(client.finished());
finish();
// Process tasks on the main thread until the streaming background thread
// has completed its tasks.
processTasksUntilStreamingComplete();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = pendingScript().getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
EXPECT_TRUE(sourceCode.streamer());
v8::TryCatch tryCatch;
v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(sourceCode, isolate());
EXPECT_FALSE(script.IsEmpty());
EXPECT_FALSE(tryCatch.HasCaught());
}
TEST_F(ScriptStreamingTest, CompilingStreamedScriptWithParseError)
{
// Test that scripts with parse errors are handled properly. In those cases,
// the V8 side typically finished before loading finishes: make sure we
// handle it gracefully.
bool started = ScriptStreamer::startStreaming(pendingScript(), m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
pendingScript().watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendData("this is the part which will be a parse error");
// V8 won't realize the parse error until it actually starts parsing the
// script, and this happens only when its buffer is filled.
appendPadding();
EXPECT_FALSE(client.finished());
// Force the V8 side to finish before the loading.
processTasksUntilStreamingComplete();
EXPECT_FALSE(client.finished());
finish();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = pendingScript().getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
EXPECT_TRUE(sourceCode.streamer());
v8::TryCatch tryCatch;
v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(sourceCode, isolate());
EXPECT_TRUE(script.IsEmpty());
EXPECT_TRUE(tryCatch.HasCaught());
}
TEST_F(ScriptStreamingTest, CancellingStreaming)
{
// Test that the upper layers (PendingScript and up) can be ramped down
// while streaming is ongoing, and ScriptStreamer handles it gracefully.
bool started = ScriptStreamer::startStreaming(pendingScript(), m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
pendingScript().watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
// In general, we cannot control what the background thread is doing
// (whether it's parsing or waiting for more data). In this test, we have
// given it so little data that it's surely waiting for more.
// Simulate cancelling the network load (e.g., because the user navigated
// away).
EXPECT_FALSE(client.finished());
pendingScript().stopWatchingForLoad(&client);
m_pendingScript = PendingScriptWrapper::create(); // This will destroy m_resource.
m_resource = 0;
// The V8 side will complete too. This should not crash. We don't receive
// any results from the streaming and the client doesn't get notified.
processTasksUntilStreamingComplete();
EXPECT_FALSE(client.finished());
}
TEST_F(ScriptStreamingTest, SuppressingStreaming)
{
// If we notice during streaming that there is a code cache, streaming
// is suppressed (V8 doesn't parse while the script is loading), and the
// upper layer (ScriptResourceClient) should get a notification when the
// script is loaded.
bool started = ScriptStreamer::startStreaming(pendingScript(), m_settings.get(), m_scope.scriptState());
TestScriptResourceClient client;
pendingScript().watchForLoad(&client);
EXPECT_TRUE(started);
appendData("function foo() {");
appendPadding();
m_resource->setCachedMetadata(V8ScriptRunner::tagForCodeCache(), "X", 1, Resource::CacheLocally);
appendPadding();
finish();
processTasksUntilStreamingComplete();
EXPECT_TRUE(client.finished());
bool errorOccurred = false;
ScriptSourceCode sourceCode = pendingScript().getSource(KURL(), errorOccurred);
EXPECT_FALSE(errorOccurred);
// ScriptSourceCode doesn't refer to the streamer, since we have suppressed
// the streaming and resumed the non-streaming code path for script
// compilation.
EXPECT_FALSE(sourceCode.streamer());
}
} // namespace
} // namespace blink
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/sstream.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/constants.h"
#include "library/normalize.h"
#include "library/aux_recursors.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"
namespace lean {
static expr * g_neutral_expr = nullptr;
static expr * g_unreachable_expr = nullptr;
class erase_irrelevant_fn : public compiler_step_visitor {
virtual expr visit_constant(expr const & e) override {
/* Erase universe level information */
return mk_constant(const_name(e));
}
/* We keep only the major and minor premises in cases_on applications. */
expr visit_cases_on(expr const & fn, buffer<expr> & args) {
name const & rec_name = const_name(fn);
name const & I_name = rec_name.get_prefix();
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nminors = *inductive::get_num_minor_premises(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
unsigned arity = nparams + 1 /* typeformer/motive */ + nindices + 1 /* major premise */ + nminors;
lean_assert(args.size() >= arity);
for (unsigned i = nparams + 1 + nindices; i < args.size(); i++) {
args[i] = visit(args[i]);
}
expr new_fn = visit(fn);
return mk_app(new_fn, args.size() - nparams - 1 - nindices, args.data() + nparams + 1 + nindices);
}
/* We keep only the major and minor premises in rec applications.
This method also converts the rec into cases_on */
expr visit_rec(expr const & fn, buffer<expr> & args) {
name const & rec_name = const_name(fn);
name const & I_name = rec_name.get_prefix();
/* This preprocessing step assumes that recursive recursors have already been eliminated */
lean_assert(!is_recursive_datatype(env(), I_name));
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nminors = *inductive::get_num_minor_premises(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
unsigned arity = nparams + 1 /* typeformer/motive */ + nminors + nindices + 1 /* major premise */;
lean_assert(args.size() >= arity);
buffer<expr> new_args;
expr new_fn = mk_constant(name(I_name, "cases_on"));
/* add major */
new_args.push_back(visit(args[nparams + 1 + nminors + nindices]));
/* add minors */
for (unsigned i = 0; i < nminors; i++)
new_args.push_back(visit(args[nparams + 1 + i]));
return add_args(mk_app(new_fn, new_args), arity, args);
}
expr add_args(expr e, unsigned start_idx, buffer<expr> const & args) {
for (unsigned i = start_idx; i < args.size(); i++)
e = mk_app(e, args[i]);
return beta_reduce(e);
}
/* Remove eq.rec applications since they are just "type-casting" operations. */
expr visit_eq_rec(buffer<expr> & args) {
lean_assert(args.size() >= 6);
expr major = visit(args[3]);
return add_args(major, 6, args);
}
expr consume_lambdas(type_context::tmp_locals & locals, expr e) {
while (true) {
if (is_lambda(e)) {
expr local = locals.push_local_from_binding(e);
e = instantiate(binding_body(e), local);
} else {
return beta_reduce(e);
}
}
}
/* We can eliminate no_confusion applications, they do not add any relevant information to the environment */
expr visit_no_confusion(expr const & fn, buffer<expr> const & args) {
lean_assert(is_constant(fn));
name const & no_confusion_name = const_name(fn);
name const & I_name = no_confusion_name.get_prefix();
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
unsigned basic_arity = nparams + nindices + 1 /* motive */ + 2 /* lhs/rhs */ + 1 /* equality */;
lean_assert(args.size() >= basic_arity);
expr lhs = ctx().whnf(args[nparams + nindices + 1]);
expr rhs = ctx().whnf(args[nparams + nindices + 2]);
optional<name> lhs_constructor = is_constructor_app(env(), lhs);
optional<name> rhs_constructor = is_constructor_app(env(), rhs);
if (!lhs_constructor || !rhs_constructor)
throw exception(sstream() << "code generation failed, unsupported occurrence of '" << no_confusion_name << "', constructors expected");
if (lhs_constructor != rhs_constructor)
return *g_unreachable_expr;
lean_assert(args.size() >= basic_arity + 1);
expr major = args[nparams + nindices + 4];
type_context::tmp_locals locals(ctx());
major = consume_lambdas(locals, major);
major = visit(major);
major = locals.mk_lambda(major);
expr r = major;
unsigned c_data_sz = get_constructor_arity(env(), *lhs_constructor) - nparams;
for (unsigned i = 0; i < c_data_sz; i++)
r = mk_app(r, *g_neutral_expr); // add dummy proofs
/* add remaining arguments */
return add_args(r, nparams + nindices + 5, args);
}
/* Treat subtype.tag as the identity function */
virtual expr visit_subtype_tag(buffer<expr> const & args) {
lean_assert(args.size() >= 4);
expr r = visit(args[2]);
return add_args(r, 4, args);
}
/* Eliminate subtype.rec */
virtual expr visit_subtype_rec(buffer<expr> const & args) {
lean_assert(args.size() >= 5);
expr minor = visit(args[3]);
expr major = visit(args[4]);
expr r = mk_app(minor, major, *g_neutral_expr);
return add_args(r, 5, args);
}
/* subtype.elt_of is also compiled as the identity function */
virtual expr visit_subtype_elt_of(buffer<expr> const & args) {
lean_assert(args.size() >= 3);
expr r = visit(args[2]);
return add_args(r, 3, args);
}
virtual expr visit_app(expr const & e) override {
buffer<expr> args;
expr const & fn = get_app_args(e, args);
if (is_lambda(fn)) {
return visit(beta_reduce(e));
} else if (is_constant(fn)) {
name const & n = const_name(fn);
if (n == get_eq_rec_name()) {
return visit_eq_rec(args);
} else if (n == get_subtype_rec_name()) {
return visit_subtype_rec(args);
} else if (is_cases_on_recursor(env(), n)) {
return visit_cases_on(fn, args);
} else if (inductive::is_elim_rule(env(), n)) {
return visit_rec(fn, args);
} else if (is_no_confusion(env(), n)) {
return visit_no_confusion(fn, args);
} else if (n == get_subtype_tag_name()) {
return visit_subtype_tag(args);
} else if (n == get_subtype_elt_of_name()) {
return visit_subtype_elt_of(args);
}
}
return compiler_step_visitor::visit_app(e);
}
public:
erase_irrelevant_fn(environment const & env):compiler_step_visitor(env) {}
};
expr erase_irrelevant(environment const & env, expr const & e) {
return erase_irrelevant_fn(env)(e);
}
bool is_neutral_expr(expr const & e) {
return e == *g_neutral_expr;
}
bool is_unreachable_expr(expr const & e) {
return e == *g_unreachable_expr;
}
void initialize_erase_irrelevant() {
g_neutral_expr = new expr(mk_constant("_neutral_"));
g_unreachable_expr = new expr(mk_constant("_unreachable_"));
}
void finalize_erase_irrelevant() {
delete g_neutral_expr;
delete g_unreachable_expr;
}
}
<commit_msg>chore(compiler/erase_irrelevant): compilation warnings<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/sstream.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/constants.h"
#include "library/normalize.h"
#include "library/aux_recursors.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"
namespace lean {
static expr * g_neutral_expr = nullptr;
static expr * g_unreachable_expr = nullptr;
class erase_irrelevant_fn : public compiler_step_visitor {
virtual expr visit_constant(expr const & e) override {
/* Erase universe level information */
return mk_constant(const_name(e));
}
/* We keep only the major and minor premises in cases_on applications. */
expr visit_cases_on(expr const & fn, buffer<expr> & args) {
name const & rec_name = const_name(fn);
name const & I_name = rec_name.get_prefix();
unsigned nparams = *inductive::get_num_params(env(), I_name);
DEBUG_CODE(unsigned nminors = *inductive::get_num_minor_premises(env(), I_name););
unsigned nindices = *inductive::get_num_indices(env(), I_name);
DEBUG_CODE(unsigned arity = nparams + 1 /* typeformer/motive */ + nindices + 1 /* major premise */ + nminors;);
lean_assert(args.size() >= arity);
for (unsigned i = nparams + 1 + nindices; i < args.size(); i++) {
args[i] = visit(args[i]);
}
expr new_fn = visit(fn);
return mk_app(new_fn, args.size() - nparams - 1 - nindices, args.data() + nparams + 1 + nindices);
}
/* We keep only the major and minor premises in rec applications.
This method also converts the rec into cases_on */
expr visit_rec(expr const & fn, buffer<expr> & args) {
name const & rec_name = const_name(fn);
name const & I_name = rec_name.get_prefix();
/* This preprocessing step assumes that recursive recursors have already been eliminated */
lean_assert(!is_recursive_datatype(env(), I_name));
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nminors = *inductive::get_num_minor_premises(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
unsigned arity = nparams + 1 /* typeformer/motive */ + nminors + nindices + 1 /* major premise */;
lean_assert(args.size() >= arity);
buffer<expr> new_args;
expr new_fn = mk_constant(name(I_name, "cases_on"));
/* add major */
new_args.push_back(visit(args[nparams + 1 + nminors + nindices]));
/* add minors */
for (unsigned i = 0; i < nminors; i++)
new_args.push_back(visit(args[nparams + 1 + i]));
return add_args(mk_app(new_fn, new_args), arity, args);
}
expr add_args(expr e, unsigned start_idx, buffer<expr> const & args) {
for (unsigned i = start_idx; i < args.size(); i++)
e = mk_app(e, args[i]);
return beta_reduce(e);
}
/* Remove eq.rec applications since they are just "type-casting" operations. */
expr visit_eq_rec(buffer<expr> & args) {
lean_assert(args.size() >= 6);
expr major = visit(args[3]);
return add_args(major, 6, args);
}
expr consume_lambdas(type_context::tmp_locals & locals, expr e) {
while (true) {
if (is_lambda(e)) {
expr local = locals.push_local_from_binding(e);
e = instantiate(binding_body(e), local);
} else {
return beta_reduce(e);
}
}
}
/* We can eliminate no_confusion applications, they do not add any relevant information to the environment */
expr visit_no_confusion(expr const & fn, buffer<expr> const & args) {
lean_assert(is_constant(fn));
name const & no_confusion_name = const_name(fn);
name const & I_name = no_confusion_name.get_prefix();
unsigned nparams = *inductive::get_num_params(env(), I_name);
unsigned nindices = *inductive::get_num_indices(env(), I_name);
DEBUG_CODE(unsigned basic_arity = nparams + nindices + 1 /* motive */ + 2 /* lhs/rhs */ + 1 /* equality */;);
lean_assert(args.size() >= basic_arity);
expr lhs = ctx().whnf(args[nparams + nindices + 1]);
expr rhs = ctx().whnf(args[nparams + nindices + 2]);
optional<name> lhs_constructor = is_constructor_app(env(), lhs);
optional<name> rhs_constructor = is_constructor_app(env(), rhs);
if (!lhs_constructor || !rhs_constructor)
throw exception(sstream() << "code generation failed, unsupported occurrence of '" << no_confusion_name << "', constructors expected");
if (lhs_constructor != rhs_constructor)
return *g_unreachable_expr;
lean_assert(args.size() >= basic_arity + 1);
expr major = args[nparams + nindices + 4];
type_context::tmp_locals locals(ctx());
major = consume_lambdas(locals, major);
major = visit(major);
major = locals.mk_lambda(major);
expr r = major;
unsigned c_data_sz = get_constructor_arity(env(), *lhs_constructor) - nparams;
for (unsigned i = 0; i < c_data_sz; i++)
r = mk_app(r, *g_neutral_expr); // add dummy proofs
/* add remaining arguments */
return add_args(r, nparams + nindices + 5, args);
}
/* Treat subtype.tag as the identity function */
virtual expr visit_subtype_tag(buffer<expr> const & args) {
lean_assert(args.size() >= 4);
expr r = visit(args[2]);
return add_args(r, 4, args);
}
/* Eliminate subtype.rec */
virtual expr visit_subtype_rec(buffer<expr> const & args) {
lean_assert(args.size() >= 5);
expr minor = visit(args[3]);
expr major = visit(args[4]);
expr r = mk_app(minor, major, *g_neutral_expr);
return add_args(r, 5, args);
}
/* subtype.elt_of is also compiled as the identity function */
virtual expr visit_subtype_elt_of(buffer<expr> const & args) {
lean_assert(args.size() >= 3);
expr r = visit(args[2]);
return add_args(r, 3, args);
}
virtual expr visit_app(expr const & e) override {
buffer<expr> args;
expr const & fn = get_app_args(e, args);
if (is_lambda(fn)) {
return visit(beta_reduce(e));
} else if (is_constant(fn)) {
name const & n = const_name(fn);
if (n == get_eq_rec_name()) {
return visit_eq_rec(args);
} else if (n == get_subtype_rec_name()) {
return visit_subtype_rec(args);
} else if (is_cases_on_recursor(env(), n)) {
return visit_cases_on(fn, args);
} else if (inductive::is_elim_rule(env(), n)) {
return visit_rec(fn, args);
} else if (is_no_confusion(env(), n)) {
return visit_no_confusion(fn, args);
} else if (n == get_subtype_tag_name()) {
return visit_subtype_tag(args);
} else if (n == get_subtype_elt_of_name()) {
return visit_subtype_elt_of(args);
}
}
return compiler_step_visitor::visit_app(e);
}
public:
erase_irrelevant_fn(environment const & env):compiler_step_visitor(env) {}
};
expr erase_irrelevant(environment const & env, expr const & e) {
return erase_irrelevant_fn(env)(e);
}
bool is_neutral_expr(expr const & e) {
return e == *g_neutral_expr;
}
bool is_unreachable_expr(expr const & e) {
return e == *g_unreachable_expr;
}
void initialize_erase_irrelevant() {
g_neutral_expr = new expr(mk_constant("_neutral_"));
g_unreachable_expr = new expr(mk_constant("_unreachable_"));
}
void finalize_erase_irrelevant() {
delete g_neutral_expr;
delete g_unreachable_expr;
}
}
<|endoftext|> |
<commit_before>
#include <gmock/gmock.h>
#include <fiblib/Fibonacci.h>
class fibonacci_test: public testing::Test
{
public:
};
TEST_F(fibonacci_test, CheckSomeResults)
{
fiblib::Fibonacci fib;
EXPECT_EQ( 0, fib( 0));
EXPECT_EQ( 1, fib( 1));
EXPECT_EQ( 1, fib( 2));
EXPECT_EQ(21, fib( 8));
// ...
}
<commit_msg>Fix signed-unsigned-warning in test<commit_after>
#include <gmock/gmock.h>
#include <fiblib/Fibonacci.h>
class fibonacci_test: public testing::Test
{
public:
};
TEST_F(fibonacci_test, CheckSomeResults)
{
fiblib::Fibonacci fib;
EXPECT_EQ((unsigned int) 0, fib(0));
EXPECT_EQ((unsigned int) 1, fib(1));
EXPECT_EQ((unsigned int) 1, fib(2));
EXPECT_EQ((unsigned int)21, fib(8));
// ...
}
<|endoftext|> |
<commit_before>/*!
\file named_condition_variable.cpp
\brief Named condition variable synchronization primitive implementation
\author Ivan Shynkarenka
\date 04.10.2016
\copyright MIT License
*/
#include "threads/named_condition_variable.h"
#include "errors/exceptions.h"
#include "errors/fatal.h"
#include <algorithm>
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif
namespace CppCommon {
//! @cond INTERNALS
class NamedConditionVariable::Impl
{
public:
Impl(const std::string& name) : _name(name)
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
, _shared(name)
#elif defined(_WIN32) || defined(_WIN64)
, _shared(name)
#endif
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
// Only the owner should initializate a named condition variable
if (_shared.owner())
{
pthread_mutexattr_t mutex_attribute;
int result = pthread_mutexattr_init(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
result = pthread_mutexattr_destroy(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);
pthread_condattr_t cond_attribute;
result = pthread_condattr_init(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
result = pthread_cond_init(&_shared->cond, &cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
result = pthread_condattr_destroy(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
}
#elif defined(_WIN32) || defined(_WIN64)
// Owner of the condition variable should initialize its value
if (_shared.owner())
*_shared = 0;
_mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
if (_mutex == nullptr)
throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
_semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
if (_semaphore == nullptr)
throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
}
~Impl()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
// Only the owner should destroy a named condition variable
if (_shared.owner())
{
int result = pthread_mutex_destroy(&_shared->mutex);
if (result != 0)
fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
result = pthread_cond_destroy(&_shared->cond);
if (result != 0)
fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
}
#elif defined(_WIN32) || defined(_WIN64)
if (!CloseHandle(_mutex))
fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
if (!CloseHandle(_semaphore))
fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
}
const std::string& name() const
{
return _name;
}
void NotifyOne()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_cond_signal(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Decrement shared waiters count
--(*_shared);
// Signal one waiter
if (!ReleaseSemaphore(_semaphore, 1, nullptr))
throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void NotifyAll()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_cond_broadcast(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Signal all waiters
if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
// Clear all shared waiters
*_shared = 0;
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void Wait()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
if (result != 0)
throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to wait a named condition variable!");
#endif
}
bool TryWaitFor(const Timespan& timespan)
{
if (timespan < 0)
return false;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
struct timespec timeout;
timeout.tv_sec = timespan.seconds();
timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
if ((result != 0) && (result != ETIMEDOUT))
throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
return (result == 0);
#elif defined(_WIN32) || defined(_WIN64)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, (DWORD)std::max(0ll, timespan.milliseconds()));
if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
return (result == WAIT_OBJECT_0);
#endif
}
private:
std::string _name;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
// Shared condition variable structure
struct CondVar
{
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// Shared condition variable structure wrapper
SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64)
HANDLE _mutex;
HANDLE _semaphore;
SharedType<LONG> _shared;
#endif
};
//! @endcond
NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}
NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}
NamedConditionVariable::~NamedConditionVariable()
{
}
NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
_pimpl = std::move(cv._pimpl);
return *this;
}
const std::string& NamedConditionVariable::name() const
{
return _pimpl->name();
}
void NamedConditionVariable::NotifyOne()
{
_pimpl->NotifyOne();
}
void NamedConditionVariable::NotifyAll()
{
_pimpl->NotifyAll();
}
void NamedConditionVariable::Wait()
{
_pimpl->Wait();
}
bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
return _pimpl->TryWaitFor(timespan);
}
} // namespace CppCommon
<commit_msg>Fix Cygwin build<commit_after>/*!
\file named_condition_variable.cpp
\brief Named condition variable synchronization primitive implementation
\author Ivan Shynkarenka
\date 04.10.2016
\copyright MIT License
*/
#include "threads/named_condition_variable.h"
#include "errors/exceptions.h"
#include "errors/fatal.h"
#include <algorithm>
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif
namespace CppCommon {
//! @cond INTERNALS
class NamedConditionVariable::Impl
{
public:
Impl(const std::string& name) : _name(name)
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
, _shared(name)
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
, _shared(name)
#endif
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should initializate a named condition variable
if (_shared.owner())
{
pthread_mutexattr_t mutex_attribute;
int result = pthread_mutexattr_init(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
result = pthread_mutexattr_destroy(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);
pthread_condattr_t cond_attribute;
result = pthread_condattr_init(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
result = pthread_cond_init(&_shared->cond, &cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
result = pthread_condattr_destroy(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Owner of the condition variable should initialize its value
if (_shared.owner())
*_shared = 0;
_mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
if (_mutex == nullptr)
throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
_semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
if (_semaphore == nullptr)
throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
}
~Impl()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should destroy a named condition variable
if (_shared.owner())
{
int result = pthread_mutex_destroy(&_shared->mutex);
if (result != 0)
fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
result = pthread_cond_destroy(&_shared->cond);
if (result != 0)
fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
if (!CloseHandle(_mutex))
fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
if (!CloseHandle(_semaphore))
fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
}
const std::string& name() const
{
return _name;
}
void NotifyOne()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_signal(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Decrement shared waiters count
--(*_shared);
// Signal one waiter
if (!ReleaseSemaphore(_semaphore, 1, nullptr))
throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void NotifyAll()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_broadcast(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Signal all waiters
if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
// Clear all shared waiters
*_shared = 0;
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void Wait()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
if (result != 0)
throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to wait a named condition variable!");
#endif
}
bool TryWaitFor(const Timespan& timespan)
{
if (timespan < 0)
return false;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
struct timespec timeout;
timeout.tv_sec = timespan.seconds();
timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
if ((result != 0) && (result != ETIMEDOUT))
throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
return (result == 0);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, (DWORD)std::max(0ll, timespan.milliseconds()));
if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
return (result == WAIT_OBJECT_0);
#endif
}
private:
std::string _name;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Shared condition variable structure
struct CondVar
{
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// Shared condition variable structure wrapper
SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
HANDLE _mutex;
HANDLE _semaphore;
SharedType<LONG> _shared;
#endif
};
//! @endcond
NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}
NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}
NamedConditionVariable::~NamedConditionVariable()
{
}
NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
_pimpl = std::move(cv._pimpl);
return *this;
}
const std::string& NamedConditionVariable::name() const
{
return _pimpl->name();
}
void NamedConditionVariable::NotifyOne()
{
_pimpl->NotifyOne();
}
void NamedConditionVariable::NotifyAll()
{
_pimpl->NotifyAll();
}
void NamedConditionVariable::Wait()
{
_pimpl->Wait();
}
bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
return _pimpl->TryWaitFor(timespan);
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBrains2MaskImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
//#include "itkFlipImageFilter.h"
#include "itkSpatialOrientationAdapter.h"
#include "vnl/vnl_sample.h"
int itkBrains2MaskTest(int ac, char *av[])
{
typedef itk::Image<unsigned int,3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef itk::ImageFileWriter<ImageType> ImageWriterType;
//
// create a random image to write out.
const ImageType::SizeType imageSize = {{4,4,4}};
const ImageType::IndexType imageIndex = {{0,0,0}};
ImageType::RegionType region;
region.SetSize(imageSize);
region.SetIndex(imageIndex);
ImageType::Pointer img = ImageType::New();
img->SetLargestPossibleRegion(region);
img->SetBufferedRegion(region);
img->SetRequestedRegion(region);
img->Allocate();
itk::SpatialOrientationAdapter<3>::DirectionType CORdir=itk::SpatialOrientationAdapter<3>().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP);
img->SetDirection(CORdir);
vnl_sample_reseed(8775070);
itk::ImageRegionIterator<ImageType> ri(img,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd())
{
unsigned int val
= static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
val = val > 8192 ? 255 : 0;
if(counter && counter % 8 == 0)
std::cerr << val << std::endl;
else
std::cerr << val << " ";
counter++;
ri.Set(val);
++ri;
}
std::cerr << std::endl << std::endl;
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
itk::ImageIOBase::Pointer io;
io = itk::Brains2MaskImageIO::New();
if(ac < 2)
{
std::cout << "Must specify directory containing Brains2Test.mask"
<< std::endl;
return EXIT_FAILURE;
}
std::string fileName(av[1]);
fileName = fileName + "/Brains2Test.mask";
ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetImageIO(io);
imageWriter->SetFileName(fileName.c_str());
imageWriter->SetInput(img);
try
{
imageWriter->Write();
}
catch (itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return EXIT_FAILURE;
}
ImageType::Pointer readImage;
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetImageIO(io);
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch (itk::ExceptionObject& ex)
{
std::string message;
message = "Problem found while reading image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return EXIT_FAILURE;
}
ri.GoToBegin();
itk::ImageRegionIterator<ImageType> ri2(readImage,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd() && !ri2.IsAtEnd())
{
unsigned int x = ri.Get();
unsigned int y = ri2.Get();
if(counter && counter % 8 == 0)
std::cerr << y << std::endl;
else
std::cerr << y << " ";
if(x != y)
{
std::cerr <<
"Error comparing Input Image and File Image of Brains2 Mask" <<
std::endl;
return EXIT_FAILURE;
}
counter++;
++ri;
++ri2;
}
if(!ri.IsAtEnd() || !ri2.IsAtEnd())
{
std::cerr << "Error, inconsistent image sizes " << std::endl;
return EXIT_FAILURE;
}
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
//
// test the factory interface. This ImageIO class doesn't get
// added to the list of Builtin factories, so add it explicitly, and
// then try and open the mask file.
itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: SpatialOrientationAdapter is not a templated class anymore.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBrains2MaskImageIOTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
//#include "itkFlipImageFilter.h"
#include "itkSpatialOrientationAdapter.h"
#include "vnl/vnl_sample.h"
int itkBrains2MaskTest(int ac, char *av[])
{
typedef itk::Image<unsigned int,3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
typedef itk::ImageFileWriter<ImageType> ImageWriterType;
//
// create a random image to write out.
const ImageType::SizeType imageSize = {{4,4,4}};
const ImageType::IndexType imageIndex = {{0,0,0}};
ImageType::RegionType region;
region.SetSize(imageSize);
region.SetIndex(imageIndex);
ImageType::Pointer img = ImageType::New();
img->SetLargestPossibleRegion(region);
img->SetBufferedRegion(region);
img->SetRequestedRegion(region);
img->Allocate();
itk::SpatialOrientationAdapter::DirectionType CORdir=itk::SpatialOrientationAdapter().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP);
img->SetDirection(CORdir);
vnl_sample_reseed(8775070);
itk::ImageRegionIterator<ImageType> ri(img,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd())
{
unsigned int val
= static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
val = val > 8192 ? 255 : 0;
if(counter && counter % 8 == 0)
std::cerr << val << std::endl;
else
std::cerr << val << " ";
counter++;
ri.Set(val);
++ri;
}
std::cerr << std::endl << std::endl;
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
itk::ImageIOBase::Pointer io;
io = itk::Brains2MaskImageIO::New();
if(ac < 2)
{
std::cout << "Must specify directory containing Brains2Test.mask"
<< std::endl;
return EXIT_FAILURE;
}
std::string fileName(av[1]);
fileName = fileName + "/Brains2Test.mask";
ImageWriterType::Pointer imageWriter = ImageWriterType::New();
imageWriter->SetImageIO(io);
imageWriter->SetFileName(fileName.c_str());
imageWriter->SetInput(img);
try
{
imageWriter->Write();
}
catch (itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return EXIT_FAILURE;
}
ImageType::Pointer readImage;
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetImageIO(io);
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch (itk::ExceptionObject& ex)
{
std::string message;
message = "Problem found while reading image ";
message += fileName;
message += "\n";
message += ex.GetLocation();
message += "\n";
message += ex.GetDescription();
std::cerr << message << std::endl;
itksys::SystemTools::RemoveFile(fileName.c_str());
return EXIT_FAILURE;
}
ri.GoToBegin();
itk::ImageRegionIterator<ImageType> ri2(readImage,region);
try
{
unsigned int counter = 0;
while(!ri.IsAtEnd() && !ri2.IsAtEnd())
{
unsigned int x = ri.Get();
unsigned int y = ri2.Get();
if(counter && counter % 8 == 0)
std::cerr << y << std::endl;
else
std::cerr << y << " ";
if(x != y)
{
std::cerr <<
"Error comparing Input Image and File Image of Brains2 Mask" <<
std::endl;
return EXIT_FAILURE;
}
counter++;
++ri;
++ri2;
}
if(!ri.IsAtEnd() || !ri2.IsAtEnd())
{
std::cerr << "Error, inconsistent image sizes " << std::endl;
return EXIT_FAILURE;
}
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
//
// test the factory interface. This ImageIO class doesn't get
// added to the list of Builtin factories, so add it explicitly, and
// then try and open the mask file.
itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
try
{
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(fileName.c_str());
imageReader->Update();
readImage = imageReader->GetOutput();
}
catch(itk::ExceptionObject & ex)
{
ex.Print(std::cerr);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include <algorithm>
#include "core/Setup.h"
#include "Audio.hpp"
#include "AudioDevice.hpp"
#include "Listener.hpp"
#include "alsa/ALSAAudioDevice.hpp"
#include "core/Engine.hpp"
#include "coreaudio/CAAudioDevice.hpp"
#include "dsound/DSAudioDevice.hpp"
#include "empty/EmptyAudioDevice.hpp"
#include "openal/OALAudioDevice.hpp"
#include "opensl/OSLAudioDevice.hpp"
#include "xaudio2/XA2AudioDevice.hpp"
#include "wasapi/WASAPIAudioDevice.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace audio
{
Driver Audio::getDriver(const std::string& driver)
{
if (driver.empty() || driver == "default")
{
auto availableDrivers = Audio::getAvailableAudioDrivers();
if (availableDrivers.find(Driver::WASAPI) != availableDrivers.end())
return Driver::WASAPI;
else if (availableDrivers.find(Driver::COREAUDIO) != availableDrivers.end())
return Driver::COREAUDIO;
else if (availableDrivers.find(Driver::ALSA) != availableDrivers.end())
return Driver::ALSA;
else if (availableDrivers.find(Driver::OPENAL) != availableDrivers.end())
return Driver::OPENAL;
else if (availableDrivers.find(Driver::XAUDIO2) != availableDrivers.end())
return Driver::XAUDIO2;
else if (availableDrivers.find(Driver::DIRECTSOUND) != availableDrivers.end())
return Driver::DIRECTSOUND;
else if (availableDrivers.find(Driver::OPENSL) != availableDrivers.end())
return Driver::OPENSL;
else
return Driver::EMPTY;
}
else if (driver == "empty")
return Driver::EMPTY;
else if (driver == "openal")
return Driver::OPENAL;
else if (driver == "directsound")
return Driver::DIRECTSOUND;
else if (driver == "xaudio2")
return Driver::XAUDIO2;
else if (driver == "opensl")
return Driver::OPENSL;
else if (driver == "coreaudio")
return Driver::COREAUDIO;
else if (driver == "alsa")
return Driver::ALSA;
else if (driver == "wasapi")
return Driver::WASAPI;
else
throw std::runtime_error("Invalid audio driver");
}
std::set<Driver> Audio::getAvailableAudioDrivers()
{
static std::set<Driver> availableDrivers;
if (availableDrivers.empty())
{
availableDrivers.insert(Driver::EMPTY);
#if OUZEL_COMPILE_OPENAL
availableDrivers.insert(Driver::OPENAL);
#endif
#if OUZEL_COMPILE_DIRECTSOUND
availableDrivers.insert(Driver::DIRECTSOUND);
#endif
#if OUZEL_COMPILE_XAUDIO2
availableDrivers.insert(Driver::XAUDIO2);
#endif
#if OUZEL_COMPILE_OPENSL
availableDrivers.insert(Driver::OPENSL);
#endif
#if OUZEL_COMPILE_COREAUDIO
availableDrivers.insert(Driver::COREAUDIO);
#endif
#if OUZEL_COMPILE_ALSA
availableDrivers.insert(Driver::ALSA);
#endif
#if OUZEL_COMPILE_WASAPI
availableDrivers.insert(Driver::WASAPI);
#endif
}
return availableDrivers;
}
static std::unique_ptr<AudioDevice> createAudioDevice(Driver driver,
const std::function<void(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)>& dataGetter,
bool debugAudio, Window* window)
{
switch (driver)
{
#if OUZEL_COMPILE_OPENAL
case Driver::OPENAL:
engine->log(Log::Level::INFO) << "Using OpenAL audio driver";
return std::unique_ptr<AudioDevice>(new OALAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_DIRECTSOUND
case Driver::DIRECTSOUND:
engine->log(Log::Level::INFO) << "Using DirectSound audio driver";
return std::unique_ptr<AudioDevice>(new DSAudioDevice(512, 44100, 0, dataGetter, window));
#endif
#if OUZEL_COMPILE_XAUDIO2
case Driver::XAUDIO2:
engine->log(Log::Level::INFO) << "Using XAudio 2 audio driver";
return std::unique_ptr<AudioDevice>(new XA2AudioDevice(512, 44100, 0, dataGetter, debugAudio));
#endif
#if OUZEL_COMPILE_OPENSL
case Driver::OPENSL:
engine->log(Log::Level::INFO) << "Using OpenSL ES audio driver";
return std::unique_ptr<AudioDevice>(new OSLAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_COREAUDIO
case Driver::COREAUDIO:
engine->log(Log::Level::INFO) << "Using CoreAudio audio driver";
return std::unique_ptr<AudioDevice>(new CAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_ALSA
case Driver::ALSA:
engine->log(Log::Level::INFO) << "Using ALSA audio driver";
return std::unique_ptr<AudioDevice>(new ALSAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_WASAPI
case Driver::WASAPI:
engine->log(Log::Level::INFO) << "Using WASAPI audio driver";
return std::unique_ptr<AudioDevice>(new WASAPIAudioDevice(512, 44100, 0, dataGetter));
#endif
default:
engine->log(Log::Level::INFO) << "Not using audio driver";
(void)debugAudio;
(void)window;
return std::unique_ptr<AudioDevice>(new EmptyAudioDevice(512, 44100, 0, dataGetter));
}
}
Audio::Audio(Driver driver, bool debugAudio, Window* window):
device(createAudioDevice(driver,
std::bind(&Audio::getData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4),
debugAudio, window)),
mixer(device->getBufferSize(), device->getChannels(),
std::bind(&Audio::eventCallback, this, std::placeholders::_1)),
masterMix(*this)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::SetMasterBusCommand(masterMix.getBusId())));
device->start();
}
Audio::~Audio()
{
}
void Audio::update()
{
// TODO: handle events from the audio device
mixer.submitCommandBuffer(std::move(commandBuffer));
commandBuffer = mixer::CommandBuffer();
}
void Audio::deleteObject(uintptr_t objectId)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::DeleteObjectCommand(objectId)));
}
uintptr_t Audio::initBus()
{
uintptr_t busId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitBusCommand(busId)));
return busId;
}
uintptr_t Audio::initStream(uintptr_t sourceId)
{
uintptr_t streamId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitStreamCommand(streamId, sourceId)));
return streamId;
}
uintptr_t Audio::initData(const std::function<std::unique_ptr<mixer::Data>()>& initFunction)
{
uintptr_t dataId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitDataCommand(dataId,
initFunction)));
return dataId;
}
uintptr_t Audio::initProcessor(std::unique_ptr<mixer::Processor>&& processor)
{
uintptr_t processorId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitProcessorCommand(processorId,
std::forward<std::unique_ptr<mixer::Processor>>(processor))));
return processorId;
}
void Audio::updateProcessor(uintptr_t processorId, const std::function<void(mixer::Processor*)>& updateFunction)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::UpdateProcessorCommand(processorId,
updateFunction)));
}
void Audio::getData(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)
{
mixer.getSamples(frames, channels, sampleRate, samples);
}
void Audio::eventCallback(const mixer::Mixer::Event& event)
{
}
} // namespace audio
} // namespace ouzel
<commit_msg>Rename the remaining getData methods to getSamples<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include <algorithm>
#include "core/Setup.h"
#include "Audio.hpp"
#include "AudioDevice.hpp"
#include "Listener.hpp"
#include "alsa/ALSAAudioDevice.hpp"
#include "core/Engine.hpp"
#include "coreaudio/CAAudioDevice.hpp"
#include "dsound/DSAudioDevice.hpp"
#include "empty/EmptyAudioDevice.hpp"
#include "openal/OALAudioDevice.hpp"
#include "opensl/OSLAudioDevice.hpp"
#include "xaudio2/XA2AudioDevice.hpp"
#include "wasapi/WASAPIAudioDevice.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace audio
{
Driver Audio::getDriver(const std::string& driver)
{
if (driver.empty() || driver == "default")
{
auto availableDrivers = Audio::getAvailableAudioDrivers();
if (availableDrivers.find(Driver::WASAPI) != availableDrivers.end())
return Driver::WASAPI;
else if (availableDrivers.find(Driver::COREAUDIO) != availableDrivers.end())
return Driver::COREAUDIO;
else if (availableDrivers.find(Driver::ALSA) != availableDrivers.end())
return Driver::ALSA;
else if (availableDrivers.find(Driver::OPENAL) != availableDrivers.end())
return Driver::OPENAL;
else if (availableDrivers.find(Driver::XAUDIO2) != availableDrivers.end())
return Driver::XAUDIO2;
else if (availableDrivers.find(Driver::DIRECTSOUND) != availableDrivers.end())
return Driver::DIRECTSOUND;
else if (availableDrivers.find(Driver::OPENSL) != availableDrivers.end())
return Driver::OPENSL;
else
return Driver::EMPTY;
}
else if (driver == "empty")
return Driver::EMPTY;
else if (driver == "openal")
return Driver::OPENAL;
else if (driver == "directsound")
return Driver::DIRECTSOUND;
else if (driver == "xaudio2")
return Driver::XAUDIO2;
else if (driver == "opensl")
return Driver::OPENSL;
else if (driver == "coreaudio")
return Driver::COREAUDIO;
else if (driver == "alsa")
return Driver::ALSA;
else if (driver == "wasapi")
return Driver::WASAPI;
else
throw std::runtime_error("Invalid audio driver");
}
std::set<Driver> Audio::getAvailableAudioDrivers()
{
static std::set<Driver> availableDrivers;
if (availableDrivers.empty())
{
availableDrivers.insert(Driver::EMPTY);
#if OUZEL_COMPILE_OPENAL
availableDrivers.insert(Driver::OPENAL);
#endif
#if OUZEL_COMPILE_DIRECTSOUND
availableDrivers.insert(Driver::DIRECTSOUND);
#endif
#if OUZEL_COMPILE_XAUDIO2
availableDrivers.insert(Driver::XAUDIO2);
#endif
#if OUZEL_COMPILE_OPENSL
availableDrivers.insert(Driver::OPENSL);
#endif
#if OUZEL_COMPILE_COREAUDIO
availableDrivers.insert(Driver::COREAUDIO);
#endif
#if OUZEL_COMPILE_ALSA
availableDrivers.insert(Driver::ALSA);
#endif
#if OUZEL_COMPILE_WASAPI
availableDrivers.insert(Driver::WASAPI);
#endif
}
return availableDrivers;
}
static std::unique_ptr<AudioDevice> createAudioDevice(Driver driver,
const std::function<void(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)>& dataGetter,
bool debugAudio, Window* window)
{
switch (driver)
{
#if OUZEL_COMPILE_OPENAL
case Driver::OPENAL:
engine->log(Log::Level::INFO) << "Using OpenAL audio driver";
return std::unique_ptr<AudioDevice>(new OALAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_DIRECTSOUND
case Driver::DIRECTSOUND:
engine->log(Log::Level::INFO) << "Using DirectSound audio driver";
return std::unique_ptr<AudioDevice>(new DSAudioDevice(512, 44100, 0, dataGetter, window));
#endif
#if OUZEL_COMPILE_XAUDIO2
case Driver::XAUDIO2:
engine->log(Log::Level::INFO) << "Using XAudio 2 audio driver";
return std::unique_ptr<AudioDevice>(new XA2AudioDevice(512, 44100, 0, dataGetter, debugAudio));
#endif
#if OUZEL_COMPILE_OPENSL
case Driver::OPENSL:
engine->log(Log::Level::INFO) << "Using OpenSL ES audio driver";
return std::unique_ptr<AudioDevice>(new OSLAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_COREAUDIO
case Driver::COREAUDIO:
engine->log(Log::Level::INFO) << "Using CoreAudio audio driver";
return std::unique_ptr<AudioDevice>(new CAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_ALSA
case Driver::ALSA:
engine->log(Log::Level::INFO) << "Using ALSA audio driver";
return std::unique_ptr<AudioDevice>(new ALSAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_WASAPI
case Driver::WASAPI:
engine->log(Log::Level::INFO) << "Using WASAPI audio driver";
return std::unique_ptr<AudioDevice>(new WASAPIAudioDevice(512, 44100, 0, dataGetter));
#endif
default:
engine->log(Log::Level::INFO) << "Not using audio driver";
(void)debugAudio;
(void)window;
return std::unique_ptr<AudioDevice>(new EmptyAudioDevice(512, 44100, 0, dataGetter));
}
}
Audio::Audio(Driver driver, bool debugAudio, Window* window):
device(createAudioDevice(driver,
std::bind(&Audio::getSamples, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4),
debugAudio, window)),
mixer(device->getBufferSize(), device->getChannels(),
std::bind(&Audio::eventCallback, this, std::placeholders::_1)),
masterMix(*this)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::SetMasterBusCommand(masterMix.getBusId())));
device->start();
}
Audio::~Audio()
{
}
void Audio::update()
{
// TODO: handle events from the audio device
mixer.submitCommandBuffer(std::move(commandBuffer));
commandBuffer = mixer::CommandBuffer();
}
void Audio::deleteObject(uintptr_t objectId)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::DeleteObjectCommand(objectId)));
}
uintptr_t Audio::initBus()
{
uintptr_t busId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitBusCommand(busId)));
return busId;
}
uintptr_t Audio::initStream(uintptr_t sourceId)
{
uintptr_t streamId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitStreamCommand(streamId, sourceId)));
return streamId;
}
uintptr_t Audio::initData(const std::function<std::unique_ptr<mixer::Data>()>& initFunction)
{
uintptr_t dataId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitDataCommand(dataId,
initFunction)));
return dataId;
}
uintptr_t Audio::initProcessor(std::unique_ptr<mixer::Processor>&& processor)
{
uintptr_t processorId = mixer.getObjectId();
addCommand(std::unique_ptr<mixer::Command>(new mixer::InitProcessorCommand(processorId,
std::forward<std::unique_ptr<mixer::Processor>>(processor))));
return processorId;
}
void Audio::updateProcessor(uintptr_t processorId, const std::function<void(mixer::Processor*)>& updateFunction)
{
addCommand(std::unique_ptr<mixer::Command>(new mixer::UpdateProcessorCommand(processorId,
updateFunction)));
}
void Audio::getSamples(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)
{
mixer.getSamples(frames, channels, sampleRate, samples);
}
void Audio::eventCallback(const mixer::Mixer::Event& event)
{
}
} // namespace audio
} // namespace ouzel
<|endoftext|> |
<commit_before>// Copyright (c) 2018 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "scanner.h"
static bool had_error{};
static void report(
int line, const std::string& where, const std::string& message) {
std::cerr
<< "[line " << line << "] ERROR " << where << ": "
<< message << std::endl;
had_error = true;
}
static void error(int line, const std::string& message) {
report(line, "", message);
}
static void print_tokens(const std::string& source) {
Scanner s(source);
auto tokens = s.scan_tokens();
for (auto& t : tokens)
std::cout << t.repr() << std::endl;
}
static void repl(void) {
std::string line;
for (;;) {
std::cout << ">>> ";
if (!std::getline(std::cin, line) || line == "exit") {
std::cout << std::endl;
break;
}
// interpret(line);
print_tokens(line);
had_error = false;
}
}
static std::string read_file(const std::string& path) {
std::ifstream fp(path);
if (fp.is_open()) {
std::stringstream ss;
ss << fp.rdbuf();
return ss.str();
}
return "";
}
static void run(const std::string& source) {
}
static void run_file(const std::string& path) {
auto bytes = read_file(path);
// run(bytes);
print_tokens(bytes);
if (had_error)
std::exit(1);
}
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
if (argc < 2) {
repl();
}
else if (argc == 2) {
run_file(argv[1]);
}
else {
std::cerr << "USAGE: loxpp {script}" << std::endl;
std::exit(1);
}
return 0;
}
<commit_msg>:construction: chore(lox): updated the lox starting<commit_after>// Copyright (c) 2018 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include "error_reporter.h"
#include "scanner.h"
#include "parser.h"
#include "ast_printer.h"
#include "interpreter.h"
static ErrorReporter err_reporter;
static std::shared_ptr<Interpreter> interp = std::make_shared<Interpreter>(err_reporter);
static void run(const std::string& source) {
Scanner s(source);
auto tokens = s.scan_tokens();
// for (auto& t : tokens)
// std::cout << t.repr() << std::endl;
// Parser p(tokens);
// auto expr = p.parse();
// std::cout << std::make_shared<AstPrinter>()->as_string(expr) << std::endl;
// auto interp = std::make_shared<Interpreter>(err_reporter);
// interp->interpret(expr);
Parser p(tokens);
auto stmts = p.parse_stmt();
// auto interp = std::make_shared<Interpreter>(err_reporter);
interp->interpret(stmts);
if (err_reporter.had_error())
std::abort();
}
static void repl(void) {
std::string line;
for (;;) {
std::cout << ">>> ";
if (!std::getline(std::cin, line) || line == "exit") {
std::cout << std::endl;
break;
}
run(line);
}
}
static std::string read_file(const std::string& path) {
std::ifstream fp(path);
if (fp.is_open()) {
std::stringstream ss;
ss << fp.rdbuf();
return ss.str();
}
return "";
}
static void run_file(const std::string& path) {
auto bytes = read_file(path);
run(bytes);
}
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
if (argc < 2) {
repl();
}
else if (argc == 2) {
run_file(argv[1]);
}
else {
std::cerr << "USAGE: loxpp {script}" << std::endl;
std::exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>/* **********************************************************************************************
Homework: #7
Author: Dak Washbrook
Due: Sun. March 20, 2016
Title: Complex Number
Assignment: Create a class called Complex for performing arithmetic with complex numbers. Write a
program to test your class.
Complex numbers have the form:
realPart + imaginaryPart * i
Use double variables to represent the private data of the class. Provide a constructor that
enables an object of this class to be initialized when it is declared. The constructor should
contain default values in case no initializers are provided. Provide public member functions that
perform the following tasks:
a) Adding two complex numbers: The real parts added together and the imaginary parts are
added together.
b) Subtracting two complex numbers: The real parts subtracted together and the imaginary
parts are subtracted together.
c) Printing Complex numbers in the form (a , b), where a is the real part and b is the
imaginary part.
(Do not use operator overloading for this assignment.)
********************************************************************************************** */
#include <iostream>
using namespace std;
class Complex {
private:
// Declare the Real Number
double real;
// Declare the Imaginary Number
double imaginary;
public:
/**
* Complex constructor.
*
* @param double real Initializer for the Real Number
* @param double imaginary Initializer for the Imaginary Number
*/
Complex(double real = 0.0, double imaginary = 0.0) {
// Store the Real Number
this->real = real;
// Store the Imaginary Number
this->imaginary = imaginary;
}
/**
* Add this Complex to with another Complex and return the newComplex.
*
* @param Complex num2 Complex to be added to this Complex
* @return Complex newComplex returns the newComplex number after adding.
*/
Complex add(Complex num2) {
double newReal = this->real + num2.getReal();
double newImaginary = this->imaginary + num2.getImaginary();
Complex newComplex(newReal, newImaginary);
return newComplex;
}
/**
* Subtract another Complex from this Complex and return the new Complex.
*
* @param Complex num2 Complex to be subtracted from this Complex
* @return Complex newComplex returns the newComplex number after subtracting.
*/
Complex subtract(Complex num2) {
double newReal = this->real - num2.getReal();
double newImaginary = this->imaginary - num2.getImaginary();
Complex newComplex(newReal, newImaginary);
return newComplex;
}
/**
* Print this Complex Number as (a, b). Where a is the real number and b is the imaginary part.
*/
void print() {
cout << "(" << this->real << ", " << this->imaginary << ")" << endl;
}
/**
* Accessor function for this real number.
*
* @return double real
*/
double getReal() {
return this->real;
}
/**
* Accessor function for this real number.
*
* @return double imaginary
*/
double getImaginary() {
return this->imaginary;
}
};
int main() {
while (true) {
/**
* Declare the real and imaginary doubles for the first and second complex numbers.
*/
double firstReal, firstImaginary;
double secondReal, secondImaginary;
/**
* Declare the choice integer for the action the user want's to make.
*/
int choice;
do {
// Request the first real number.
cout << "Enter the first real number: ";
cin >> firstReal;
// Request the first imaginary number.
cout << "Enter the first imaginary number: ";
cin >> firstImaginary;
// Request the second real number.
cout << "Enter the second real number: ";
cin >> secondReal;
// Request the second imaginary number.
cout << "Enter the second imaginary number: ";
cin >> secondImaginary;
/**
* Create the Complex objects for the first and second complex numbers.
*/
Complex first(firstReal, firstImaginary);
Complex second(secondReal, secondImaginary);
cout << "Complex Numbers are now stored." << endl << endl;
/**
* Do while loop for the choices of how to manipulate the Complex numbers.
*/
do {
cout << "Select an option to manipulate the Complex Numbers: " << endl;
cout << "1. Add" << endl;
cout << "2. Subtract" << endl;
cout << "3. New Numbers" << endl;
cout << "4. End Program." << endl;
cin >> choice;
// If the choice is out of range, continue.
if (choice < 1 || choice > 4) {
cout << "INVALID CHOICE" << endl;
continue;
}
// Declare what will be the new Complex number.
Complex newComplex;
// Switch statement to run the action that the user chooses.
switch (choice) {
case 1:
newComplex = first.add(second);
newComplex.print();
break;
case 2:
newComplex = first.subtract(second);
newComplex.print();
break;
case 3:
goto store;
break;
default:
goto stop;
break;
}
} while (true);
store:
continue;
} while (true);
stop:
break;
}
cout << endl;
return 0;
}
<commit_msg>Update Homework-7.cpp<commit_after>/* **********************************************************************************************
Homework: #7
Author: Dak Washbrook
Due: Sun. March 20, 2016
Title: Complex Number
Assignment: Create a class called Complex for performing arithmetic with complex numbers. Write a
program to test your class.
Complex numbers have the form:
realPart + imaginaryPart * i
Use double variables to represent the private data of the class. Provide a constructor that
enables an object of this class to be initialized when it is declared. The constructor should
contain default values in case no initializers are provided. Provide public member functions that
perform the following tasks:
a) Adding two complex numbers: The real parts added together and the imaginary parts are
added together.
b) Subtracting two complex numbers: The real parts subtracted together and the imaginary
parts are subtracted together.
c) Printing Complex numbers in the form (a , b), where a is the real part and b is the
imaginary part.
(Do not use operator overloading for this assignment.)
********************************************************************************************** */
#include <iostream>
using namespace std;
class Complex {
private:
// Declare the Real Number
double real;
// Declare the Imaginary Number
double imaginary;
public:
/**
* Complex constructor.
*
* @param double real Initializer for the Real Number
* @param double imaginary Initializer for the Imaginary Number
*/
Complex(double real = 0.0, double imaginary = 0.0) {
// Store the Real Number
this->real = real;
// Store the Imaginary Number
this->imaginary = imaginary;
}
/**
* Add this Complex to with another Complex and return the newComplex.
*
* @param Complex num2 Complex to be added to this Complex
* @return Complex newComplex returns the newComplex number after adding.
*/
Complex add(Complex num2) {
double newReal = this->real + num2.getReal();
double newImaginary = this->imaginary + num2.getImaginary();
Complex newComplex(newReal, newImaginary);
return newComplex;
}
/**
* Subtract another Complex from this Complex and return the new Complex.
*
* @param Complex num2 Complex to be subtracted from this Complex
* @return Complex newComplex returns the newComplex number after subtracting.
*/
Complex subtract(Complex num2) {
double newReal = this->real - num2.getReal();
double newImaginary = this->imaginary - num2.getImaginary();
Complex newComplex(newReal, newImaginary);
return newComplex;
}
/**
* Print this Complex Number as (a, b). Where a is the real number and b is the imaginary part.
*/
void print() {
cout << endl << "The new imaginary number is: (" << this->real << ", " << this->imaginary << ")" << endl << endl;
}
/**
* Accessor function for this real number.
*
* @return double real
*/
double getReal() {
return this->real;
}
/**
* Accessor function for this real number.
*
* @return double imaginary
*/
double getImaginary() {
return this->imaginary;
}
};
int main() {
while (true) {
/**
* Declare the real and imaginary doubles for the first and second complex numbers.
*/
double firstReal, firstImaginary;
double secondReal, secondImaginary;
/**
* Declare the choice integer for the action the user want's to make.
*/
int choice;
do {
// Request the first real number.
cout << "Enter the first real number: ";
cin >> firstReal;
// Request the first imaginary number.
cout << "Enter the first imaginary number: ";
cin >> firstImaginary;
// Request the second real number.
cout << "Enter the second real number: ";
cin >> secondReal;
// Request the second imaginary number.
cout << "Enter the second imaginary number: ";
cin >> secondImaginary;
/**
* Create the Complex objects for the first and second complex numbers.
*/
Complex first(firstReal, firstImaginary);
Complex second(secondReal, secondImaginary);
cout << "Complex Numbers are now stored." << endl << endl;
/**
* Do while loop for the choices of how to manipulate the Complex numbers.
*/
do {
cout << "Select an option to manipulate the Complex Numbers: " << endl;
cout << "1. Add" << endl;
cout << "2. Subtract" << endl;
cout << "3. New Numbers" << endl;
cout << "4. End Program." << endl;
cin >> choice;
// If the choice is out of range, continue.
if (choice < 1 || choice > 4) {
cout << "INVALID CHOICE" << endl;
continue;
}
// Declare what will be the new Complex number.
Complex newComplex;
// Switch statement to run the action that the user chooses.
switch (choice) {
case 1:
newComplex = first.add(second);
newComplex.print();
break;
case 2:
newComplex = first.subtract(second);
newComplex.print();
break;
case 3:
goto store;
break;
default:
goto stop;
break;
}
} while (true);
store:
continue;
} while (true);
stop:
break;
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implementationentry.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 10:33:53 $
*
* 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 _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
namespace cppu {
sal_Bool component_writeInfoHelper(
void *, void *pRegistryKey , const struct ImplementationEntry entries[] )
{
sal_Bool bRet = sal_False;
try
{
if( pRegistryKey )
{
for( sal_Int32 i = 0; entries[i].create ; i ++ )
{
OUStringBuffer buf( 124 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("/") );
buf.append( entries[i].getImplementationName() );
buf.appendAscii(RTL_CONSTASCII_STRINGPARAM( "/UNO/SERVICES" ) );
Reference< XRegistryKey > xNewKey(
reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( buf.makeStringAndClear() ) );
Sequence< OUString > seq = entries[i].getSupportedServiceNames();
const OUString *pArray = seq.getConstArray();
for ( sal_Int32 nPos = 0 ; nPos < seq.getLength(); nPos ++ )
xNewKey->createKey( pArray[nPos] );
}
bRet = sal_True;
}
}
catch ( InvalidRegistryException & )
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
return bRet;
}
void * component_getFactoryHelper(
const sal_Char * pImplName, void *, void *,
const struct ImplementationEntry entries[] )
{
void * pRet = 0;
Reference< XSingleComponentFactory > xFactory;
for( sal_Int32 i = 0 ; entries[i].create ; i ++ )
{
OUString implName = entries[i].getImplementationName();
if( 0 == implName.compareToAscii( pImplName ) )
{
xFactory = entries[i].createFactory(
entries[i].create,
implName,
entries[i].getSupportedServiceNames(),
entries[i].moduleCounter );
}
}
if( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.14); FILE MERGED 2006/09/01 17:23:17 kaib 1.3.14.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implementationentry.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:41:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppuhelper.hxx"
#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
namespace cppu {
sal_Bool component_writeInfoHelper(
void *, void *pRegistryKey , const struct ImplementationEntry entries[] )
{
sal_Bool bRet = sal_False;
try
{
if( pRegistryKey )
{
for( sal_Int32 i = 0; entries[i].create ; i ++ )
{
OUStringBuffer buf( 124 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("/") );
buf.append( entries[i].getImplementationName() );
buf.appendAscii(RTL_CONSTASCII_STRINGPARAM( "/UNO/SERVICES" ) );
Reference< XRegistryKey > xNewKey(
reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( buf.makeStringAndClear() ) );
Sequence< OUString > seq = entries[i].getSupportedServiceNames();
const OUString *pArray = seq.getConstArray();
for ( sal_Int32 nPos = 0 ; nPos < seq.getLength(); nPos ++ )
xNewKey->createKey( pArray[nPos] );
}
bRet = sal_True;
}
}
catch ( InvalidRegistryException & )
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
return bRet;
}
void * component_getFactoryHelper(
const sal_Char * pImplName, void *, void *,
const struct ImplementationEntry entries[] )
{
void * pRet = 0;
Reference< XSingleComponentFactory > xFactory;
for( sal_Int32 i = 0 ; entries[i].create ; i ++ )
{
OUString implName = entries[i].getImplementationName();
if( 0 == implName.compareToAscii( pImplName ) )
{
xFactory = entries[i].createFactory(
entries[i].create,
implName,
entries[i].getSupportedServiceNames(),
entries[i].moduleCounter );
}
}
if( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
}
<|endoftext|> |
<commit_before>/*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/statements/schema_altering_statement.hh"
#include "cql3/statements/cf_prop_defs.hh"
#include "cql3/statements/cf_statement.hh"
#include "cql3/cql3_type.hh"
#include "service/migration_manager.hh"
#include "schema.hh"
#include "core/shared_ptr.hh"
#include <unordered_map>
#include <utility>
#include <vector>
#include <set>
namespace cql3 {
namespace statements {
/** A <code>CREATE TABLE</code> parsed from a CQL query statement. */
class create_table_statement : public schema_altering_statement {
#if 0
private AbstractType<?> defaultValidator;
#endif
std::vector<data_type> _partition_key_types;
std::vector<data_type> _clustering_key_types;
std::vector<bytes> _key_aliases;
std::vector<bytes> _column_aliases;
#if 0
private ByteBuffer valueAlias;
private boolean isDense;
#endif
using column_map_type =
std::unordered_map<::shared_ptr<column_identifier>,
data_type,
shared_ptr_value_hash<column_identifier>,
shared_ptr_equal_by_value<column_identifier>>;
using column_set_type =
std::unordered_set<::shared_ptr<column_identifier>,
shared_ptr_value_hash<column_identifier>,
shared_ptr_equal_by_value<column_identifier>>;
column_map_type _columns;
column_set_type _static_columns;
const ::shared_ptr<cf_prop_defs> _properties;
const bool _if_not_exists;
public:
create_table_statement(::shared_ptr<cf_name> name,
::shared_ptr<cf_prop_defs> properties,
bool if_not_exists,
column_set_type static_columns);
virtual void check_access(const service::client_state& state) override;
virtual void validate(distributed<service::storage_proxy>&, const service::client_state& state) override;
virtual future<bool> announce_migration(distributed<service::storage_proxy>& proxy, bool is_local_only) override;
virtual shared_ptr<transport::event::schema_change> change_event() override;
schema_ptr get_cf_meta_data();
class raw_statement;
friend raw_statement;
private:
std::vector<column_definition> get_columns();
void apply_properties_to(schema_builder& builder);
void add_column_metadata_from_aliases(schema_builder& builder, std::vector<bytes> aliases, const std::vector<data_type>& types, column_kind kind);
};
class create_table_statement::raw_statement : public cf_statement {
private:
std::unordered_map<::shared_ptr<column_identifier>, ::shared_ptr<cql3_type::raw>> _definitions;
public:
const ::shared_ptr<cf_prop_defs> properties = ::make_shared<cf_prop_defs>();
private:
std::vector<std::vector<::shared_ptr<column_identifier>>> _key_aliases;
std::vector<::shared_ptr<column_identifier>> _column_aliases;
std::vector<std::pair<::shared_ptr<column_identifier>, bool>> defined_ordering; // Insertion ordering is important
create_table_statement::column_set_type _static_columns;
bool _use_compact_storage = false;
std::multiset<::shared_ptr<column_identifier>> _defined_names;
bool _if_not_exists;
public:
raw_statement(::shared_ptr<cf_name> name, bool if_not_exists);
virtual ::shared_ptr<prepared> prepare(database& db) override;
data_type get_type_and_remove(column_map_type& columns, ::shared_ptr<column_identifier> t);
void add_definition(::shared_ptr<column_identifier> def, ::shared_ptr<cql3_type::raw> type, bool is_static);
void add_key_aliases(const std::vector<::shared_ptr<column_identifier>> aliases);
void add_column_alias(::shared_ptr<column_identifier> alias);
void set_ordering(::shared_ptr<column_identifier> alias, bool reversed);
void set_compact_storage();
};
}
}
<commit_msg>cql3: Fix create_table_statement::raw_statement definition lookup<commit_after>/*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/statements/schema_altering_statement.hh"
#include "cql3/statements/cf_prop_defs.hh"
#include "cql3/statements/cf_statement.hh"
#include "cql3/cql3_type.hh"
#include "service/migration_manager.hh"
#include "schema.hh"
#include "core/shared_ptr.hh"
#include <unordered_map>
#include <utility>
#include <vector>
#include <set>
namespace cql3 {
namespace statements {
/** A <code>CREATE TABLE</code> parsed from a CQL query statement. */
class create_table_statement : public schema_altering_statement {
#if 0
private AbstractType<?> defaultValidator;
#endif
std::vector<data_type> _partition_key_types;
std::vector<data_type> _clustering_key_types;
std::vector<bytes> _key_aliases;
std::vector<bytes> _column_aliases;
#if 0
private ByteBuffer valueAlias;
private boolean isDense;
#endif
using column_map_type =
std::unordered_map<::shared_ptr<column_identifier>,
data_type,
shared_ptr_value_hash<column_identifier>,
shared_ptr_equal_by_value<column_identifier>>;
using column_set_type =
std::unordered_set<::shared_ptr<column_identifier>,
shared_ptr_value_hash<column_identifier>,
shared_ptr_equal_by_value<column_identifier>>;
column_map_type _columns;
column_set_type _static_columns;
const ::shared_ptr<cf_prop_defs> _properties;
const bool _if_not_exists;
public:
create_table_statement(::shared_ptr<cf_name> name,
::shared_ptr<cf_prop_defs> properties,
bool if_not_exists,
column_set_type static_columns);
virtual void check_access(const service::client_state& state) override;
virtual void validate(distributed<service::storage_proxy>&, const service::client_state& state) override;
virtual future<bool> announce_migration(distributed<service::storage_proxy>& proxy, bool is_local_only) override;
virtual shared_ptr<transport::event::schema_change> change_event() override;
schema_ptr get_cf_meta_data();
class raw_statement;
friend raw_statement;
private:
std::vector<column_definition> get_columns();
void apply_properties_to(schema_builder& builder);
void add_column_metadata_from_aliases(schema_builder& builder, std::vector<bytes> aliases, const std::vector<data_type>& types, column_kind kind);
};
class create_table_statement::raw_statement : public cf_statement {
private:
using defs_type = std::unordered_map<::shared_ptr<column_identifier>,
::shared_ptr<cql3_type::raw>,
shared_ptr_value_hash<column_identifier>,
shared_ptr_equal_by_value<column_identifier>>;
defs_type _definitions;
public:
const ::shared_ptr<cf_prop_defs> properties = ::make_shared<cf_prop_defs>();
private:
std::vector<std::vector<::shared_ptr<column_identifier>>> _key_aliases;
std::vector<::shared_ptr<column_identifier>> _column_aliases;
std::vector<std::pair<::shared_ptr<column_identifier>, bool>> defined_ordering; // Insertion ordering is important
create_table_statement::column_set_type _static_columns;
bool _use_compact_storage = false;
std::multiset<::shared_ptr<column_identifier>> _defined_names;
bool _if_not_exists;
public:
raw_statement(::shared_ptr<cf_name> name, bool if_not_exists);
virtual ::shared_ptr<prepared> prepare(database& db) override;
data_type get_type_and_remove(column_map_type& columns, ::shared_ptr<column_identifier> t);
void add_definition(::shared_ptr<column_identifier> def, ::shared_ptr<cql3_type::raw> type, bool is_static);
void add_key_aliases(const std::vector<::shared_ptr<column_identifier>> aliases);
void add_column_alias(::shared_ptr<column_identifier> alias);
void set_ordering(::shared_ptr<column_identifier> alias, bool reversed);
void set_compact_storage();
};
}
}
<|endoftext|> |
<commit_before>/** \brief A MARC-21 filter utility that can remove characters from a set of subfields.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2016 Universitätsbiblothek Tübingen. 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 <iostream>
#include <memory>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "FileUtil.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
void Usage() {
std::cerr << "usage: " << progname << " marc_input marc_output subfield_spec1:subfield_spec2:...:subfield_specN "
<< " characters_to_delete\n"
<< " where \"subfieldspec\" must be a MARC tag followed by a single-character\n"
<< " subfield code and \"characters_to_delete\" is list of characters that will be removed\n"
<< " from the contents of the specified subfields.\n\n";
std::exit(EXIT_FAILURE);
}
std::string GetSubfieldCodes(const std::string &tag, const std::vector<std::string> &subfield_specs) {
std::string subfield_codes;
for (const auto &subfield_spec : subfield_specs) {
if (subfield_spec.substr(0, DirectoryEntry::TAG_LENGTH) == tag)
subfield_codes += subfield_spec[DirectoryEntry::TAG_LENGTH];
}
return subfield_codes;
}
void Filter(File * const input, File * const output, const std::vector<std::string> &subfield_specs,
const std::string &filter_chars)
{
MarcXmlWriter xml_writer(output);
unsigned total_count(0), modified_record_count(0), modified_field_count(0);
while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) {
++total_count;
record.setRecordWillBeWrittenAsXml(true);
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
for (std::vector<DirectoryEntry>::const_iterator dir_entry(dir_entries.cbegin());
dir_entry != dir_entries.cend(); ++dir_entry)
{
const std::string subfield_codes(GetSubfieldCodes(dir_entry->getTag(), subfield_specs));
if (subfield_codes.empty()) {
record.write(&xml_writer);
continue;
}
bool modified_at_least_one(false);
const auto field_index(dir_entry - dir_entries.cbegin());
Subfields subfields(fields[field_index]);
for (const auto subfield_code : subfield_codes) {
const auto begin_end(subfields.getIterators(subfield_code));
for (auto subfield(begin_end.first); subfield != begin_end.second; ++subfield) {
const auto old_length(subfield->second.length());
StringUtil::RemoveChars(filter_chars, &(subfield->second));
if (subfield->second.length() != old_length) {
++modified_field_count;
modified_at_least_one = true;
}
}
}
if (modified_at_least_one) {
record.replaceField(field_index, subfields.toString());
++modified_record_count;
}
record.write(&xml_writer);
}
}
std::cerr << "Mofified " << modified_record_count << " (" << modified_field_count << " fields) of "
<< total_count << " record(s).\n";
}
// Sanity check.
bool ArePlausibleSubfieldSpecs(const std::vector<std::string> &subfield_specs) {
if (subfield_specs.empty())
return false;
for (const auto &subfield_spec : subfield_specs) {
if (subfield_spec.length() != (DirectoryEntry::TAG_LENGTH + 1))
return false;
}
return true;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 5)
Usage();
std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[1]));
std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2]));
std::vector<std::string> subfield_specs;
StringUtil::Split(argv[3], ':', &subfield_specs);
if (not ArePlausibleSubfieldSpecs(subfield_specs))
Error("bad subfield specifications!");
const std::string filter_chars(argv[4]);
if (filter_chars.empty())
Error("");
try {
Filter(input.get(), output.get(), subfield_specs, filter_chars);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Added a missing error message.<commit_after>/** \brief A MARC-21 filter utility that can remove characters from a set of subfields.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2016 Universitätsbiblothek Tübingen. 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 <iostream>
#include <memory>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "FileUtil.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
void Usage() {
std::cerr << "usage: " << progname << " marc_input marc_output subfield_spec1:subfield_spec2:...:subfield_specN "
<< " characters_to_delete\n"
<< " where \"subfieldspec\" must be a MARC tag followed by a single-character\n"
<< " subfield code and \"characters_to_delete\" is list of characters that will be removed\n"
<< " from the contents of the specified subfields.\n\n";
std::exit(EXIT_FAILURE);
}
std::string GetSubfieldCodes(const std::string &tag, const std::vector<std::string> &subfield_specs) {
std::string subfield_codes;
for (const auto &subfield_spec : subfield_specs) {
if (subfield_spec.substr(0, DirectoryEntry::TAG_LENGTH) == tag)
subfield_codes += subfield_spec[DirectoryEntry::TAG_LENGTH];
}
return subfield_codes;
}
void Filter(File * const input, File * const output, const std::vector<std::string> &subfield_specs,
const std::string &filter_chars)
{
MarcXmlWriter xml_writer(output);
unsigned total_count(0), modified_record_count(0), modified_field_count(0);
while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) {
++total_count;
record.setRecordWillBeWrittenAsXml(true);
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
for (std::vector<DirectoryEntry>::const_iterator dir_entry(dir_entries.cbegin());
dir_entry != dir_entries.cend(); ++dir_entry)
{
const std::string subfield_codes(GetSubfieldCodes(dir_entry->getTag(), subfield_specs));
if (subfield_codes.empty()) {
record.write(&xml_writer);
continue;
}
bool modified_at_least_one(false);
const auto field_index(dir_entry - dir_entries.cbegin());
Subfields subfields(fields[field_index]);
for (const auto subfield_code : subfield_codes) {
const auto begin_end(subfields.getIterators(subfield_code));
for (auto subfield(begin_end.first); subfield != begin_end.second; ++subfield) {
const auto old_length(subfield->second.length());
StringUtil::RemoveChars(filter_chars, &(subfield->second));
if (subfield->second.length() != old_length) {
++modified_field_count;
modified_at_least_one = true;
}
}
}
if (modified_at_least_one) {
record.replaceField(field_index, subfields.toString());
++modified_record_count;
}
record.write(&xml_writer);
}
}
std::cerr << "Mofified " << modified_record_count << " (" << modified_field_count << " fields) of "
<< total_count << " record(s).\n";
}
// Sanity check.
bool ArePlausibleSubfieldSpecs(const std::vector<std::string> &subfield_specs) {
if (subfield_specs.empty())
return false;
for (const auto &subfield_spec : subfield_specs) {
if (subfield_spec.length() != (DirectoryEntry::TAG_LENGTH + 1))
return false;
}
return true;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 5)
Usage();
std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[1]));
std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2]));
std::vector<std::string> subfield_specs;
StringUtil::Split(argv[3], ':', &subfield_specs);
if (not ArePlausibleSubfieldSpecs(subfield_specs))
Error("bad subfield specifications!");
const std::string filter_chars(argv[4]);
if (filter_chars.empty())
Error("missing characters to be filtered!");
try {
Filter(input.get(), output.get(), subfield_specs, filter_chars);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <ctime>
#include <cstdio>
#include <boost/filesystem.hpp>
#include "gflags/gflags.h"
#include "jsoncons/json.hpp"
#include "utils/protocol.h"
#include "utils/connection.h"
#include "bots/bot_interface.h"
#include "bots/raw_bot.h"
#include "bots/basic/bot.h"
#include "bots/tomek/bot.h"
#include "bots/piotr/bot.h"
#include "bots/greedy/bot.h"
#include "bots/stepping/bot.h"
#include "bots/constant/bot.h"
#include "bots/kamikaze/bot.h"
#include "bots/wojtek/bot.h"
#include "game/simulator.h"
DECLARE_string(race_id);
std::string random_race_id() {
char buffer[80];
sprintf (buffer, "%d", rand());
return std::string(buffer);
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
srand (time(NULL));
if (FLAGS_race_id.empty()) {
FLAGS_race_id = random_race_id();
}
boost::filesystem::create_directories("bin/" + FLAGS_race_id);
std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::wojtek::Bot()));
std::unique_ptr<game::Simulator> simulator(new game::Simulator());
auto result = simulator->Run(bot.get());
std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl;
if (result.crashed) {
std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl;
}
return 0;
}
<commit_msg>Print best lap as last line<commit_after>#include <iostream>
#include <string>
#include <ctime>
#include <cstdio>
#include <boost/filesystem.hpp>
#include "gflags/gflags.h"
#include "jsoncons/json.hpp"
#include "utils/protocol.h"
#include "utils/connection.h"
#include "bots/bot_interface.h"
#include "bots/raw_bot.h"
#include "bots/basic/bot.h"
#include "bots/tomek/bot.h"
#include "bots/piotr/bot.h"
#include "bots/greedy/bot.h"
#include "bots/stepping/bot.h"
#include "bots/constant/bot.h"
#include "bots/kamikaze/bot.h"
#include "bots/wojtek/bot.h"
#include "game/simulator.h"
DECLARE_string(race_id);
std::string random_race_id() {
char buffer[80];
sprintf (buffer, "%d", rand());
return std::string(buffer);
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
srand (time(NULL));
if (FLAGS_race_id.empty()) {
FLAGS_race_id = random_race_id();
}
boost::filesystem::create_directories("bin/" + FLAGS_race_id);
game::Simulator::Result result;
{
std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::wojtek::Bot()));
std::unique_ptr<game::Simulator> simulator(new game::Simulator());
result = simulator->Run(bot.get());
}
std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl;
if (result.crashed) {
std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#pragma GCC diagnostic push
#include "acmacs-base/boost-diagnostics.hh"
#include "boost/program_options.hpp"
#include <boost/filesystem.hpp>
#pragma GCC diagnostic pop
#include "acmacs-chart/ace.hh"
namespace fs = boost::filesystem;
// ----------------------------------------------------------------------
void scan(const fs::path& source_dir, std::vector<fs::path>& ace_files);
// ----------------------------------------------------------------------
class Options
{
public:
std::string source_dir;
};
static int get_args(int argc, const char *argv[], Options& aOptions);
int main(int argc, const char *argv[])
{
Options options;
int exit_code = get_args(argc, argv, options);
if (exit_code == 0) {
try {
std::vector<fs::path> ace_files;
scan(fs::path(options.source_dir), ace_files);
std::cout << ace_files.size() << std::endl;
for (const auto& p: ace_files)
std::cout << p << std::endl;
}
catch (std::exception& err) {
std::cerr << err.what() << std::endl;
exit_code = 1;
}
}
return exit_code;
}
static int get_args(int argc, const char *argv[], Options& aOptions)
{
using namespace boost::program_options;
options_description desc("Options");
desc.add_options()
("help", "Print help messages")
("source,s", value<std::string>(&aOptions.source_dir)->required(), "directory to scan for ace files (recursively)")
;
positional_options_description pos_opt;
pos_opt.add("source", 1);
variables_map vm;
try {
store(command_line_parser(argc, argv).options(desc).positional(pos_opt).run(), vm);
if (vm.count("help")) {
std::cerr << desc << std::endl;
return 1;
}
notify(vm);
return 0;
}
catch(required_option& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << desc << std::endl;
// std::cerr << "Usage: " << argv[0] << " <tree.json> <output.pdf>" << std::endl;
return 2;
}
catch(error& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << desc << std::endl;
return 3;
}
} // get_args
// ----------------------------------------------------------------------
void scan(const fs::path& source_dir, std::vector<fs::path>& ace_files)
{
if (!fs::is_directory(source_dir))
throw std::runtime_error(source_dir.string() + " is not a directory");
for (fs::directory_entry& dirent: fs::directory_iterator(source_dir)) {
if (fs::is_directory(dirent.status()))
scan(dirent.path(), ace_files);
else if (is_regular_file(dirent.status()) && dirent.path().extension().string() == ".ace")
ace_files.push_back(dirent.path());
}
} // scan
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>whocc-scan-titers<commit_after>#include <string>
#pragma GCC diagnostic push
#include "acmacs-base/boost-diagnostics.hh"
#include "boost/program_options.hpp"
#include <boost/filesystem.hpp>
#pragma GCC diagnostic pop
#include "acmacs-chart/ace.hh"
namespace fs = boost::filesystem;
// ----------------------------------------------------------------------
void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files);
void scan_titers(const fs::path& filename, std::set<Titer>& titers);
// ----------------------------------------------------------------------
class Options
{
public:
std::string source_dir;
};
static int get_args(int argc, const char *argv[], Options& aOptions);
int main(int argc, const char *argv[])
{
Options options;
int exit_code = get_args(argc, argv, options);
if (exit_code == 0) {
try {
std::vector<fs::path> ace_files;
find_ace_files(fs::path(options.source_dir), ace_files);
std::cout << "Total .ace files found: " << ace_files.size() << std::endl;
std::set<Titer> titers;
for (const auto& filename: ace_files)
scan_titers(filename, titers);
std::cout << titers << std::endl;
}
catch (std::exception& err) {
std::cerr << err.what() << std::endl;
exit_code = 1;
}
}
return exit_code;
}
static int get_args(int argc, const char *argv[], Options& aOptions)
{
using namespace boost::program_options;
options_description desc("Options");
desc.add_options()
("help", "Print help messages")
("source,s", value<std::string>(&aOptions.source_dir)->required(), "directory to scan for ace files (recursively)")
;
positional_options_description pos_opt;
pos_opt.add("source", 1);
variables_map vm;
try {
store(command_line_parser(argc, argv).options(desc).positional(pos_opt).run(), vm);
if (vm.count("help")) {
std::cerr << desc << std::endl;
return 1;
}
notify(vm);
return 0;
}
catch(required_option& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << desc << std::endl;
// std::cerr << "Usage: " << argv[0] << " <tree.json> <output.pdf>" << std::endl;
return 2;
}
catch(error& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << desc << std::endl;
return 3;
}
} // get_args
// ----------------------------------------------------------------------
void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files)
{
if (!fs::is_directory(source_dir))
throw std::runtime_error(source_dir.string() + " is not a directory");
for (fs::directory_entry& dirent: fs::directory_iterator(source_dir)) {
if (fs::is_directory(dirent.status()))
find_ace_files(dirent.path(), ace_files);
else if (is_regular_file(dirent.status()) && dirent.path().extension().string() == ".ace")
ace_files.push_back(dirent.path());
}
} // find_ace_files
// ----------------------------------------------------------------------
void scan_titers(const fs::path& filename, std::set<Titer>& titers)
{
std::unique_ptr<Chart> chart{import_chart(filename.string())};
for (size_t antigen_no = 0; antigen_no < chart->antigens().size(); ++antigen_no) {
for (size_t serum_no = 0; serum_no < chart->sera().size(); ++serum_no) {
titers.insert(chart->titers().get(antigen_no, serum_no));
}
}
} // scan_titers
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "app.hpp"
#include "config.h"
#include <windows.h>
#include <iostream>
#include <stdexcept>
#include <memory>
#include <getopt.h>
#include "cmd/register.hpp"
#include "cmd/exec.hpp"
#include "cmd/list.hpp"
#include "util/winerror.hpp"
#include "util/elevated.hpp"
#include "util/strconv.hpp"
#include "util/message.hpp"
namespace cygregext {
/* type of native WinApi GetCommandLineW */
typedef LPWSTR (__stdcall* native_GetCommandLineW)(void);
App::App(const int argc, char* const argv[]) :
_argc(argc),
_argv(argv),
_cmd(Command::NONE),
_regType(RegisterType::USER),
_extension(".sh"),
_iconPath(std::string()),
_force(false) {
static const char *opts = "ruaflhV";
static const struct option longopts[] = {
{ "register", no_argument, NULL, 'r' },
{ "unregister", no_argument, NULL, 'u' },
{ "ext", required_argument, NULL, 'e' },
{ "icon", required_argument, NULL, 'i' },
{ "all", no_argument, NULL, 'a' },
{ "force", no_argument, NULL, 'f' },
{ "list", no_argument, NULL, 'l' },
{ "exec", no_argument, NULL, 'E' },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{ 0, 0, 0, 0 }
};
while (1) {
int opt_index = 0;
int c = 0;
c = getopt_long(argc, argv, opts, longopts, &opt_index);
if (-1 == c) {
break;
}
switch (c) {
/* --register */
case 'r':
_cmd = Command::REGISTER;
break;
/* --unregister */
case 'u':
_cmd = Command::UNREGISTER;
break;
/* --ext */
case 'e':
_extension = optarg;
break;
/* --icon */
case 'i':
_iconPath = optarg;
break;
/* --all */
case 'a':
_regType = RegisterType::EVERYONE;
break;
/* --force */
case 'f':
_force = true;
break;
/* --list */
case 'l':
_cmd = Command::LIST;
break;
/* --exec */
case 'E':
_cmd = Command::EXEC;
break;
/* --version */
case 'V':
_printVersion();
exit(EXIT_SUCCESS);
/* --help */
case '?':
case 'h':
default:
_printUsage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (Command::NONE == _cmd) {
_printUsage(argv[0]);
exit(EXIT_FAILURE);
}
if ('.' != _extension[0]) {
_extension.insert(0, ".");
}
}
int App::run() {
std::unique_ptr<ICommand> cmd;
switch (_cmd) {
/* execute command */
case Command::EXEC:
cmd = std::unique_ptr<ExecCommand>(new ExecCommand(_wideArgs()));
break;
/* register extension */
case Command::REGISTER:
if (_regType == RegisterType::EVERYONE) {
_checkElevated();
}
cmd = std::unique_ptr<RegisterCommand>(
new RegisterCommand(_extension, _iconPath,
_regType == RegisterType::EVERYONE, _force));
break;
/* unregister extension */
case Command::UNREGISTER:
if (_regType == RegisterType::EVERYONE) {
_checkElevated();
}
cmd = std::unique_ptr<UnregisterCommand>(
new UnregisterCommand(_extension,
_regType == RegisterType::EVERYONE));
break;
/* list registered extensions */
case Command::LIST:
cmd = std::unique_ptr<ListCommand>(new ListCommand());
break;
case Command::NONE:
return 1;
}
return cmd->run();
}
WinPathW App::getPath() {
wchar_t buf[MAX_PATH + 1];
DWORD ret = GetModuleFileName(NULL, buf, sizeof(buf) / sizeof(buf[0]));
if (0 == ret) {
THROW_LAST_ERROR("Failed to get executable path.");
}
if (sizeof(buf) / sizeof(buf[0]) == ret &&
ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
throw std::runtime_error("Failed to get executable path.");
}
return WinPathW(std::wstring(buf, ret));
}
static char help[] =
""
"Options:\n"
" -r, --register Add a file type to the Windows registry.\n"
" -u, --unregister Remove a file type from the Windows registry.\n"
" --ext=EXT Register or unregister files of the given extension.\n"
" Default to .sh.\n"
" --icon=PATH,N Path and index of the icon to register for an extension.\n"
" Default to the icon of this application.\n"
" -a, --all Register or unregister extension for all users.\n"
" Default to current user only.\n"
" -f, --force Overwrite if already registered for another application.\n"
" -l, --list List registered extensions.\n"
" -h, --help Display this help and exit.\n"
" -V, --version Print version and exit.\n";
void App::_printUsage(char *progname) {
std::stringstream ss;
ss << "Usage: " << progname << " [OPTION]..." << std::endl;
ss << "Register a script file type (.sh) to Windows File Explorer."
<< std::endl << std::endl;
ss << help;
show_message(ss.str());
}
void App::_printVersion() {
std::cout << "cygregext " << VERSION << std::endl;
std::cout << "Copyright (C) 2017 Joni Eskelinen" << std::endl;
std::cout << "License MIT: The MIT License" << std::endl;
std::cout << "Icons: Tango Desktop Project" << std::endl;
}
std::vector<std::wstring> App::_wideArgs() {
std::vector<std::wstring> args;
LPWSTR* argv;
int argc;
/* use native WinApi GetCommandLineW since Cygwin hooks it */
native_GetCommandLineW fn = (native_GetCommandLineW)GetProcAddress(
GetModuleHandle(L"kernel32.dll"), "GetCommandLineW");
if (NULL == fn) {
THROW_LAST_ERROR("Failed to import GetCommandLineW");
}
argv = CommandLineToArgvW(fn(), &argc);
/* if Windows command line has less arguments than what was
passed to the main(), then application was invoked from Cygwin shell. */
if (argc < _argc) {
for (int i = 0; i < _argc; ++i) {
/* assume utf-8 */
args.push_back(mb_to_wide(_argv[i], CP_UTF8));
}
} else {
for (int i = 0; i < argc; ++i) {
args.push_back(argv[i]);
}
}
LocalFree(argv);
return args;
}
void App::_checkElevated() {
ElevatedProcess proc;
if (proc.isAdmin()) {
return;
}
proc.startElevated(_argc, _argv);
exit(EXIT_SUCCESS);
}
}
<commit_msg>Clarify usage message<commit_after>#include "app.hpp"
#include "config.h"
#include <windows.h>
#include <iostream>
#include <stdexcept>
#include <memory>
#include <getopt.h>
#include "cmd/register.hpp"
#include "cmd/exec.hpp"
#include "cmd/list.hpp"
#include "util/winerror.hpp"
#include "util/elevated.hpp"
#include "util/strconv.hpp"
#include "util/message.hpp"
namespace cygregext {
/* type of native WinApi GetCommandLineW */
typedef LPWSTR (__stdcall* native_GetCommandLineW)(void);
App::App(const int argc, char* const argv[]) :
_argc(argc),
_argv(argv),
_cmd(Command::NONE),
_regType(RegisterType::USER),
_extension(".sh"),
_iconPath(std::string()),
_force(false) {
static const char *opts = "ruaflhV";
static const struct option longopts[] = {
{ "register", no_argument, NULL, 'r' },
{ "unregister", no_argument, NULL, 'u' },
{ "ext", required_argument, NULL, 'e' },
{ "icon", required_argument, NULL, 'i' },
{ "all", no_argument, NULL, 'a' },
{ "force", no_argument, NULL, 'f' },
{ "list", no_argument, NULL, 'l' },
{ "exec", no_argument, NULL, 'E' },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{ 0, 0, 0, 0 }
};
while (1) {
int opt_index = 0;
int c = 0;
c = getopt_long(argc, argv, opts, longopts, &opt_index);
if (-1 == c) {
break;
}
switch (c) {
/* --register */
case 'r':
_cmd = Command::REGISTER;
break;
/* --unregister */
case 'u':
_cmd = Command::UNREGISTER;
break;
/* --ext */
case 'e':
_extension = optarg;
break;
/* --icon */
case 'i':
_iconPath = optarg;
break;
/* --all */
case 'a':
_regType = RegisterType::EVERYONE;
break;
/* --force */
case 'f':
_force = true;
break;
/* --list */
case 'l':
_cmd = Command::LIST;
break;
/* --exec */
case 'E':
_cmd = Command::EXEC;
break;
/* --version */
case 'V':
_printVersion();
exit(EXIT_SUCCESS);
/* --help */
case '?':
case 'h':
default:
_printUsage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (Command::NONE == _cmd) {
_printUsage(argv[0]);
exit(EXIT_FAILURE);
}
if ('.' != _extension[0]) {
_extension.insert(0, ".");
}
}
int App::run() {
std::unique_ptr<ICommand> cmd;
switch (_cmd) {
/* execute command */
case Command::EXEC:
cmd = std::unique_ptr<ExecCommand>(new ExecCommand(_wideArgs()));
break;
/* register extension */
case Command::REGISTER:
if (_regType == RegisterType::EVERYONE) {
_checkElevated();
}
cmd = std::unique_ptr<RegisterCommand>(
new RegisterCommand(_extension, _iconPath,
_regType == RegisterType::EVERYONE, _force));
break;
/* unregister extension */
case Command::UNREGISTER:
if (_regType == RegisterType::EVERYONE) {
_checkElevated();
}
cmd = std::unique_ptr<UnregisterCommand>(
new UnregisterCommand(_extension,
_regType == RegisterType::EVERYONE));
break;
/* list registered extensions */
case Command::LIST:
cmd = std::unique_ptr<ListCommand>(new ListCommand());
break;
case Command::NONE:
return 1;
}
return cmd->run();
}
WinPathW App::getPath() {
wchar_t buf[MAX_PATH + 1];
DWORD ret = GetModuleFileName(NULL, buf, sizeof(buf) / sizeof(buf[0]));
if (0 == ret) {
THROW_LAST_ERROR("Failed to get executable path.");
}
if (sizeof(buf) / sizeof(buf[0]) == ret &&
ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
throw std::runtime_error("Failed to get executable path.");
}
return WinPathW(std::wstring(buf, ret));
}
static char help[] =
""
"Options:\n"
" -r, --register Add a file type to the Windows registry.\n"
" -u, --unregister Remove a file type from the Windows registry.\n"
" --ext=EXT Register or unregister files of the given extension.\n"
" Default to .sh.\n"
" --icon=PATH,N Path and index of the icon to register for an extension.\n"
" Default to the icon of this application.\n"
" -a, --all Register or unregister extension for all users.\n"
" Default to current user only.\n"
" -f, --force Overwrite if already registered for another application.\n"
" -l, --list List registered extensions.\n"
" -h, --help Display this help and exit.\n"
" -V, --version Print version and exit.\n";
void App::_printUsage(char *progname) {
std::stringstream ss;
ss << "Usage: " << progname << " -r|-u|-l [OPTION]..." << std::endl;
ss << "Register a script file type (.sh) to Windows File Explorer."
<< std::endl << std::endl;
ss << help;
show_message(ss.str());
}
void App::_printVersion() {
std::cout << "cygregext " << VERSION << std::endl;
std::cout << "Copyright (C) 2017 Joni Eskelinen" << std::endl;
std::cout << "License MIT: The MIT License" << std::endl;
std::cout << "Icons: Tango Desktop Project" << std::endl;
}
std::vector<std::wstring> App::_wideArgs() {
std::vector<std::wstring> args;
LPWSTR* argv;
int argc;
/* use native WinApi GetCommandLineW since Cygwin hooks it */
native_GetCommandLineW fn = (native_GetCommandLineW)GetProcAddress(
GetModuleHandle(L"kernel32.dll"), "GetCommandLineW");
if (NULL == fn) {
THROW_LAST_ERROR("Failed to import GetCommandLineW");
}
argv = CommandLineToArgvW(fn(), &argc);
/* if Windows command line has less arguments than what was
passed to the main(), then application was invoked from Cygwin shell. */
if (argc < _argc) {
for (int i = 0; i < _argc; ++i) {
/* assume utf-8 */
args.push_back(mb_to_wide(_argv[i], CP_UTF8));
}
} else {
for (int i = 0; i < argc; ++i) {
args.push_back(argv[i]);
}
}
LocalFree(argv);
return args;
}
void App::_checkElevated() {
ElevatedProcess proc;
if (proc.isAdmin()) {
return;
}
proc.startElevated(_argc, _argv);
exit(EXIT_SUCCESS);
}
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <sstream>
#include <vector>
#include "inifile.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Helpers
//
std::string trim(std::string str, std::string ws = " \t")
{
// Remove leading whitespace
auto first = str.find_first_not_of(ws);
// No whitespace found
if (first == std::string::npos)
{
first = 0;
}
// Remove trailing whitespace
auto last = str.find_last_not_of(ws);
// No whitespace found
if (last == std::string::npos)
{
last = str.size() - 1;
}
// Skip if empty
if (first > last)
{
return "";
}
// Trim
return str.substr(first, last - first + 1);
}
std::vector<std::string> string_split(std::string s, char delim)
{
std::vector<std::string> result;
std::istringstream stream(s);
for (std::string token; std::getline(stream, token, delim); )
{
result.push_back(token);
}
return result;
}
size_t count_whitespaces(std::string str)
{
return std::count_if(
str.begin(),
str.end(),
[](unsigned char c) { return std::isspace(c); }
);
}
std::string tolower(std::string str)
{
std::transform(
str.begin(),
str.end(),
str.begin(),
[](unsigned char c) { return std::tolower(c); }
);
return str;
}
template <typename T>
inline bool as_T(std::string in, T& out)
{
std::istringstream stream(in);
return static_cast<bool>(stream >> out);
}
template <typename Map>
inline inifile::error_code get_string(Map const& map, std::string key, std::string& value)
{
if (map.count(key) > 1)
{
return inifile::MultipleEntries;
}
auto it = map.find(key);
if (it == map.end())
{
return inifile::NonExistent;
}
value = trim(it->second.value);
return inifile::Ok;
}
template <typename Map, typename T>
inline inifile::error_code get_T(Map const& map, std::string key, T& value)
{
std::string str = "";
inifile::error_code err = get_string(map, key, str);
if (err != inifile::Ok)
{
return err;
}
if (!as_T(str, value))
{
return inifile::ParseError;
}
return inifile::Ok;
}
template <typename Map, typename T>
inline inifile::error_code get_T3(Map const& map, std::string key, T& x, T& y, T& z)
{
std::string str = "";
inifile::error_code err = get_string(map, key, str);
if (err != inifile::Ok)
{
return err;
}
// Also remove enclosing parentheses
str = trim(str, "()");
str = trim(str, "[]");
str = trim(str, "{}");
std::string delims = " ,;|";
for (auto c : delims)
{
auto tokens = string_split(str, c);
if (tokens.size() >= 3)
{
std::string xyz[3];
int c = 0;
for (auto t : tokens)
{
if (count_whitespaces(t) < t.size())
{
xyz[c++] = t;
}
}
if (c == 3 && as_T(xyz[0], x) && as_T(xyz[1], y) && as_T(xyz[2], z))
{
return inifile::Ok;
}
}
}
return inifile::ParseError;
}
//-------------------------------------------------------------------------------------------------
// Interface
//
inifile::inifile(std::string filename)
: file_(filename)
{
if (!file_.good())
{
return;
}
std::string section = "";
for (std::string line; std::getline(file_, line); )
{
line = trim(line);
if (line.empty())
{
continue;
}
// Skip comments
if (line[0] == ';' || line[0] == '#')
{
continue;
}
// Section
if (line[0] == '[' && line[line.size() - 1] == ']')
{
section = trim(line.substr(1, line.size() - 2));
continue;
}
// Parse key/value pairs
auto p = string_split(line, '=');
if (p.size() != 2)
{
// TODO: error handling
continue;
}
std::string key = tolower(trim(p[0]));
std::string value = tolower(trim(p[1]));
entries_.emplace(std::make_pair(key, value_type{ section, value }));
}
good_ = true;
}
bool inifile::good() const
{
return good_;
}
inifile::error_code inifile::get_bool(std::string key, bool& value)
{
std::string str = "";
inifile::error_code err = visionaray::get_string(entries_, key, str);
if (err != inifile::Ok)
{
return err;
}
str = tolower(str);
if (str == "1" || str == "true" || str == "on")
{
value = true;
return Ok;
}
else if (str == "0" || str == "false" || str == "off")
{
value = false;
return Ok;
}
else
{
return ParseError;
}
}
inifile::error_code inifile::get_int8(std::string key, int8_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int16(std::string key, int16_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int32(std::string key, int32_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int64(std::string key, int64_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint8(std::string key, uint8_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint16(std::string key, uint16_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint32(std::string key, uint32_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint64(std::string key, uint64_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_float(std::string key, float& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_double(std::string key, double& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_long_double(std::string key, long double& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_string(std::string key, std::string& value, bool remove_quotes)
{
error_code err = visionaray::get_string(entries_, key, value);
if (err == Ok && remove_quotes)
{
// TODO: check that we removed *2* (and both the same) quotation marks
value = trim(value, "'");
value = trim(value, "\"");
}
return err;
}
inifile::error_code inifile::get_vec3i(std::string key, int32_t& x, int32_t& y, int32_t& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3ui(std::string key, uint32_t& x, uint32_t& y, uint32_t& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3f(std::string key, float& x, float& y, float& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3d(std::string key, double& x, double& y, double& z)
{
return get_T3(entries_, key, x, y, z);
}
} // visionaray
<commit_msg>Fix trim()<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <sstream>
#include <vector>
#include "inifile.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Helpers
//
std::string trim(std::string str, std::string ws = " \t")
{
// Remove leading whitespace
auto first = str.find_first_not_of(ws);
// Only whitespace found
if (first == std::string::npos)
{
return "";
}
// Remove trailing whitespace
auto last = str.find_last_not_of(ws);
// No whitespace found
if (last == std::string::npos)
{
last = str.size() - 1;
}
// Skip if empty
if (first > last)
{
return "";
}
// Trim
return str.substr(first, last - first + 1);
}
std::vector<std::string> string_split(std::string s, char delim)
{
std::vector<std::string> result;
std::istringstream stream(s);
for (std::string token; std::getline(stream, token, delim); )
{
result.push_back(token);
}
return result;
}
size_t count_whitespaces(std::string str)
{
return std::count_if(
str.begin(),
str.end(),
[](unsigned char c) { return std::isspace(c); }
);
}
std::string tolower(std::string str)
{
std::transform(
str.begin(),
str.end(),
str.begin(),
[](unsigned char c) { return std::tolower(c); }
);
return str;
}
template <typename T>
inline bool as_T(std::string in, T& out)
{
std::istringstream stream(in);
return static_cast<bool>(stream >> out);
}
template <typename Map>
inline inifile::error_code get_string(Map const& map, std::string key, std::string& value)
{
if (map.count(key) > 1)
{
return inifile::MultipleEntries;
}
auto it = map.find(key);
if (it == map.end())
{
return inifile::NonExistent;
}
value = trim(it->second.value);
return inifile::Ok;
}
template <typename Map, typename T>
inline inifile::error_code get_T(Map const& map, std::string key, T& value)
{
std::string str = "";
inifile::error_code err = get_string(map, key, str);
if (err != inifile::Ok)
{
return err;
}
if (!as_T(str, value))
{
return inifile::ParseError;
}
return inifile::Ok;
}
template <typename Map, typename T>
inline inifile::error_code get_T3(Map const& map, std::string key, T& x, T& y, T& z)
{
std::string str = "";
inifile::error_code err = get_string(map, key, str);
if (err != inifile::Ok)
{
return err;
}
// Also remove enclosing parentheses
str = trim(str, "()");
str = trim(str, "[]");
str = trim(str, "{}");
std::string delims = " ,;|";
for (auto c : delims)
{
auto tokens = string_split(str, c);
if (tokens.size() >= 3)
{
std::string xyz[3];
int c = 0;
for (auto t : tokens)
{
if (count_whitespaces(t) < t.size())
{
xyz[c++] = t;
}
}
if (c == 3 && as_T(xyz[0], x) && as_T(xyz[1], y) && as_T(xyz[2], z))
{
return inifile::Ok;
}
}
}
return inifile::ParseError;
}
//-------------------------------------------------------------------------------------------------
// Interface
//
inifile::inifile(std::string filename)
: file_(filename)
{
if (!file_.good())
{
return;
}
std::string section = "";
for (std::string line; std::getline(file_, line); )
{
line = trim(line);
if (line.empty())
{
continue;
}
// Skip comments
if (line[0] == ';' || line[0] == '#')
{
continue;
}
// Section
if (line[0] == '[' && line[line.size() - 1] == ']')
{
section = trim(line.substr(1, line.size() - 2));
continue;
}
// Parse key/value pairs
auto p = string_split(line, '=');
if (p.size() != 2)
{
// TODO: error handling
continue;
}
std::string key = tolower(trim(p[0]));
std::string value = tolower(trim(p[1]));
entries_.emplace(std::make_pair(key, value_type{ section, value }));
}
good_ = true;
}
bool inifile::good() const
{
return good_;
}
inifile::error_code inifile::get_bool(std::string key, bool& value)
{
std::string str = "";
inifile::error_code err = visionaray::get_string(entries_, key, str);
if (err != inifile::Ok)
{
return err;
}
str = tolower(str);
if (str == "1" || str == "true" || str == "on")
{
value = true;
return Ok;
}
else if (str == "0" || str == "false" || str == "off")
{
value = false;
return Ok;
}
else
{
return ParseError;
}
}
inifile::error_code inifile::get_int8(std::string key, int8_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int16(std::string key, int16_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int32(std::string key, int32_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_int64(std::string key, int64_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint8(std::string key, uint8_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint16(std::string key, uint16_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint32(std::string key, uint32_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_uint64(std::string key, uint64_t& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_float(std::string key, float& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_double(std::string key, double& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_long_double(std::string key, long double& value)
{
return get_T(entries_, key, value);
}
inifile::error_code inifile::get_string(std::string key, std::string& value, bool remove_quotes)
{
error_code err = visionaray::get_string(entries_, key, value);
if (err == Ok && remove_quotes)
{
// TODO: check that we removed *2* (and both the same) quotation marks
value = trim(value, "'");
value = trim(value, "\"");
}
return err;
}
inifile::error_code inifile::get_vec3i(std::string key, int32_t& x, int32_t& y, int32_t& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3ui(std::string key, uint32_t& x, uint32_t& y, uint32_t& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3f(std::string key, float& x, float& y, float& z)
{
return get_T3(entries_, key, x, y, z);
}
inifile::error_code inifile::get_vec3d(std::string key, double& x, double& y, double& z)
{
return get_T3(entries_, key, x, y, z);
}
} // visionaray
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_MESH_OPERATIONS_HPP
#define VIENNAGRID_MESH_OPERATIONS_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/segmentation.hpp"
//#include "viennagrid/mesh/element_creation.hpp"
#include "viennagrid/mesh/coboundary_iteration.hpp"
/** @file viennagrid/mesh/mesh_operations.hpp
@brief Helper routines on a mesh
*/
namespace viennagrid
{
/** @brief Copies a mesh and an associated segmentation over to another mesh and an associated segmentation */
template<typename SrcMeshT, typename SrcSegmentationT, typename DstMeshT, typename DstSegmentationT>
void copy_cells(SrcMeshT const & src_mesh_obj, SrcSegmentationT const & src_segmentation,
DstMeshT & dst_mesh_obj, DstSegmentationT & dst_segmentation )
{
// typedef typename src_segment_container_type::value_type src_segment_handle_type;
// typedef typename dst_segment_container_type::value_type dst_segment_handle_type;
typedef typename viennagrid::result_of::segment_handle<SrcSegmentationT>::type SrcSegmentHandleType;
typedef typename viennagrid::result_of::segment_handle<DstSegmentationT>::type DstSegmentHandleType;
//typedef typename viennagrid::result_of::cell_tag<SrcMeshT>::type SrcCellTag;
typedef typename viennagrid::result_of::cell<SrcMeshT>::type SrcCellType;
typedef typename viennagrid::result_of::const_vertex_range<SrcMeshT>::type SrcVertexRangeType;
typedef typename viennagrid::result_of::iterator<SrcVertexRangeType>::type SrcVertexRangeIterator;
typedef typename viennagrid::result_of::const_cell_range<SrcSegmentHandleType>::type SrcCellRangeType;
typedef typename viennagrid::result_of::iterator<SrcCellRangeType>::type SrcCellRangeIterator;
typedef typename viennagrid::result_of::const_vertex_handle<SrcMeshT>::type SrcConstVertexHandle;
typedef typename viennagrid::result_of::vertex_handle<DstMeshT>::type DstVertexHandleType;
if (&src_mesh_obj == &dst_mesh_obj)
return;
dst_mesh_obj.clear();
dst_segmentation.clear();
std::map<SrcConstVertexHandle, DstVertexHandleType> vertex_handle_map;
SrcVertexRangeType vertices( src_mesh_obj );
for (SrcVertexRangeIterator it = vertices.begin(); it != vertices.end(); ++it)
vertex_handle_map[it.handle()] = viennagrid::make_vertex( dst_mesh_obj, viennagrid::point(src_mesh_obj, *it) );
for (typename SrcSegmentationT::const_iterator seg_it = src_segmentation.begin(); seg_it != src_segmentation.end(); ++seg_it)
{
// dst_segments.push_back( viennagrid::make_view<dst_segment_handle_type>(dst_mesh) );
DstSegmentHandleType & dst_segment = dst_segmentation.get_make_segment( seg_it->id() );
SrcCellRangeType cells( *seg_it );
for (SrcCellRangeIterator it = cells.begin(); it != cells.end(); ++it)
{
SrcCellType const & cell = *it;
std::deque<DstVertexHandleType> vertex_handles;
typedef typename viennagrid::result_of::const_vertex_range<SrcCellType>::type SrcVertexOnSrcCellRangeType;
typedef typename viennagrid::result_of::iterator<SrcVertexOnSrcCellRangeType>::type SrcVertexOnSrcCellRangeIterator;
SrcVertexOnSrcCellRangeType cell_vertices(cell);
for (SrcVertexOnSrcCellRangeIterator jt = cell_vertices.begin(); jt != cell_vertices.end(); ++jt)
vertex_handles.push_back( vertex_handle_map[jt.handle()] );
typedef typename viennagrid::result_of::cell<DstMeshT>::type DstCellType;
viennagrid::make_element<DstCellType>( dst_segment, vertex_handles.begin(), vertex_handles.end() );
}
}
}
namespace detail
{
/** @brief For internal use only */
template<typename MeshT, typename ToEraseViewT, typename HandleT, typename ReferencingElementTypelist =
typename viennagrid::result_of::referencing_element_typelist<MeshT, typename viennagrid::detail::result_of::value_type<HandleT>::type >::type >
struct mark_referencing_elements_impl;
template<typename MeshT, typename ToEraseViewT, typename HandleT, typename CoboundaryElementT, typename TailT>
struct mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, viennagrid::typelist<CoboundaryElementT, TailT> >
{
static void mark(MeshT & mesh_obj, ToEraseViewT & mesh_view, HandleT host_element)
{
//typedef viennagrid::typelist<CoboundaryElementT, TailT> ReferencingElementTypelist;
typedef typename viennagrid::detail::result_of::value_type<HandleT>::type HostElementType;
//typedef typename viennagrid::result_of::handle<MeshT, CoboundaryElementT>::type CoboundaryElementHandle;
typedef typename viennagrid::result_of::coboundary_range<MeshT, HostElementType, CoboundaryElementT>::type CoboundaryElementRangeType;
typedef typename viennagrid::result_of::iterator<CoboundaryElementRangeType>::type CoboundaryElementRangeIterator;
typedef typename viennagrid::result_of::element_range<ToEraseViewT, CoboundaryElementT>::type CoboundaryElementViewRangeType;
CoboundaryElementRangeType coboundary_elements = viennagrid::coboundary_elements<HostElementType, CoboundaryElementT>(mesh_obj, host_element);
for (CoboundaryElementRangeIterator it = coboundary_elements.begin(); it != coboundary_elements.end(); ++it)
{
CoboundaryElementViewRangeType view_elements( mesh_view );
if ( viennagrid::find_by_handle(mesh_view, it.handle()) == view_elements.end() )
{
view_elements.insert_unique_handle( it.handle() );
}
}
mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, TailT>::mark(mesh_obj, mesh_view, host_element);
}
};
/** @brief For internal use only */
template<typename MeshT, typename ToEraseViewT, typename HandleT>
struct mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, viennagrid::null_type >
{
static void mark(MeshT &, ToEraseViewT &, HandleT) {}
};
} //namespace detail
/** @brief Marks elements which reference a given host element
*
* @tparam MeshT The mesh type in which the element to erase lives
* @tparam MeshViewT The mesh view type for all elements to erase
* @tparam HandleT The handle type of the element to delete
* @param mesh_obj The host mesh object
* @param element_view A mesh view which stores all elements to be marked
* @param host_element A handle object of the host element
*/
template<typename MeshT, typename MeshViewT, typename HandleT>
void mark_referencing_elements( MeshT & mesh_obj, MeshViewT & element_view, HandleT host_element )
{
detail::mark_referencing_elements_impl<MeshT, MeshViewT, HandleT>::mark(mesh_obj, element_view, host_element);
}
}
#endif
<commit_msg>added copy_vertex_map<commit_after>#ifndef VIENNAGRID_MESH_OPERATIONS_HPP
#define VIENNAGRID_MESH_OPERATIONS_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/segmentation.hpp"
#include "viennagrid/mesh/element_creation.hpp"
#include "viennagrid/mesh/coboundary_iteration.hpp"
/** @file viennagrid/mesh/mesh_operations.hpp
@brief Helper routines on a mesh
*/
namespace viennagrid
{
template<typename SrcMeshT, typename DstMeshT>
class vertex_copy_map
{
public:
vertex_copy_map( DstMeshT & dst_mesh_ ) : dst_mesh(dst_mesh_) {}
typedef typename viennagrid::result_of::vertex<SrcMeshT>::type SrcVertexType;
typedef typename viennagrid::result_of::vertex_id<SrcMeshT>::type SrcVertexIDType;
typedef typename viennagrid::result_of::vertex<DstMeshT>::type DstVertexType;
typedef typename viennagrid::result_of::vertex_handle<DstMeshT>::type DstVertexHandleType;
DstVertexHandleType operator()( SrcVertexType const & src_vertex )
{
typename std::map<SrcVertexIDType, DstVertexHandleType>::iterator vit = vertex_map.find( src_vertex.id() );
if (vit != vertex_map.end())
return vit->second;
else
{
DstVertexHandleType vh = viennagrid::make_vertex( dst_mesh, viennagrid::point(src_vertex) );
vertex_map[src_vertex.id()] = vh;
return vh;
}
}
private:
DstMeshT & dst_mesh;
std::map<SrcVertexIDType, DstVertexHandleType> vertex_map;
};
/** @brief Copies a mesh and an associated segmentation over to another mesh and an associated segmentation */
template<typename SrcMeshT, typename SrcSegmentationT, typename DstMeshT, typename DstSegmentationT>
void copy_cells(SrcMeshT const & src_mesh_obj, SrcSegmentationT const & src_segmentation,
DstMeshT & dst_mesh_obj, DstSegmentationT & dst_segmentation )
{
// typedef typename src_segment_container_type::value_type src_segment_handle_type;
// typedef typename dst_segment_container_type::value_type dst_segment_handle_type;
typedef typename viennagrid::result_of::segment_handle<SrcSegmentationT>::type SrcSegmentHandleType;
typedef typename viennagrid::result_of::segment_handle<DstSegmentationT>::type DstSegmentHandleType;
//typedef typename viennagrid::result_of::cell_tag<SrcMeshT>::type SrcCellTag;
typedef typename viennagrid::result_of::cell<SrcMeshT>::type SrcCellType;
typedef typename viennagrid::result_of::const_vertex_range<SrcMeshT>::type SrcVertexRangeType;
typedef typename viennagrid::result_of::iterator<SrcVertexRangeType>::type SrcVertexRangeIterator;
typedef typename viennagrid::result_of::const_cell_range<SrcSegmentHandleType>::type SrcCellRangeType;
typedef typename viennagrid::result_of::iterator<SrcCellRangeType>::type SrcCellRangeIterator;
typedef typename viennagrid::result_of::const_vertex_handle<SrcMeshT>::type SrcConstVertexHandle;
typedef typename viennagrid::result_of::vertex_handle<DstMeshT>::type DstVertexHandleType;
if (&src_mesh_obj == &dst_mesh_obj)
return;
dst_mesh_obj.clear();
dst_segmentation.clear();
std::map<SrcConstVertexHandle, DstVertexHandleType> vertex_handle_map;
SrcVertexRangeType vertices( src_mesh_obj );
for (SrcVertexRangeIterator it = vertices.begin(); it != vertices.end(); ++it)
vertex_handle_map[it.handle()] = viennagrid::make_vertex( dst_mesh_obj, viennagrid::point(src_mesh_obj, *it) );
for (typename SrcSegmentationT::const_iterator seg_it = src_segmentation.begin(); seg_it != src_segmentation.end(); ++seg_it)
{
// dst_segments.push_back( viennagrid::make_view<dst_segment_handle_type>(dst_mesh) );
DstSegmentHandleType & dst_segment = dst_segmentation.get_make_segment( seg_it->id() );
SrcCellRangeType cells( *seg_it );
for (SrcCellRangeIterator it = cells.begin(); it != cells.end(); ++it)
{
SrcCellType const & cell = *it;
std::deque<DstVertexHandleType> vertex_handles;
typedef typename viennagrid::result_of::const_vertex_range<SrcCellType>::type SrcVertexOnSrcCellRangeType;
typedef typename viennagrid::result_of::iterator<SrcVertexOnSrcCellRangeType>::type SrcVertexOnSrcCellRangeIterator;
SrcVertexOnSrcCellRangeType cell_vertices(cell);
for (SrcVertexOnSrcCellRangeIterator jt = cell_vertices.begin(); jt != cell_vertices.end(); ++jt)
vertex_handles.push_back( vertex_handle_map[jt.handle()] );
typedef typename viennagrid::result_of::cell<DstMeshT>::type DstCellType;
viennagrid::make_element<DstCellType>( dst_segment, vertex_handles.begin(), vertex_handles.end() );
}
}
}
namespace detail
{
/** @brief For internal use only */
template<typename MeshT, typename ToEraseViewT, typename HandleT, typename ReferencingElementTypelist =
typename viennagrid::result_of::referencing_element_typelist<MeshT, typename viennagrid::detail::result_of::value_type<HandleT>::type >::type >
struct mark_referencing_elements_impl;
template<typename MeshT, typename ToEraseViewT, typename HandleT, typename CoboundaryElementT, typename TailT>
struct mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, viennagrid::typelist<CoboundaryElementT, TailT> >
{
static void mark(MeshT & mesh_obj, ToEraseViewT & mesh_view, HandleT host_element)
{
//typedef viennagrid::typelist<CoboundaryElementT, TailT> ReferencingElementTypelist;
typedef typename viennagrid::detail::result_of::value_type<HandleT>::type HostElementType;
//typedef typename viennagrid::result_of::handle<MeshT, CoboundaryElementT>::type CoboundaryElementHandle;
typedef typename viennagrid::result_of::coboundary_range<MeshT, HostElementType, CoboundaryElementT>::type CoboundaryElementRangeType;
typedef typename viennagrid::result_of::iterator<CoboundaryElementRangeType>::type CoboundaryElementRangeIterator;
typedef typename viennagrid::result_of::element_range<ToEraseViewT, CoboundaryElementT>::type CoboundaryElementViewRangeType;
CoboundaryElementRangeType coboundary_elements = viennagrid::coboundary_elements<HostElementType, CoboundaryElementT>(mesh_obj, host_element);
for (CoboundaryElementRangeIterator it = coboundary_elements.begin(); it != coboundary_elements.end(); ++it)
{
CoboundaryElementViewRangeType view_elements( mesh_view );
if ( viennagrid::find_by_handle(mesh_view, it.handle()) == view_elements.end() )
{
view_elements.insert_unique_handle( it.handle() );
}
}
mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, TailT>::mark(mesh_obj, mesh_view, host_element);
}
};
/** @brief For internal use only */
template<typename MeshT, typename ToEraseViewT, typename HandleT>
struct mark_referencing_elements_impl<MeshT, ToEraseViewT, HandleT, viennagrid::null_type >
{
static void mark(MeshT &, ToEraseViewT &, HandleT) {}
};
} //namespace detail
/** @brief Marks elements which reference a given host element
*
* @tparam MeshT The mesh type in which the element to erase lives
* @tparam MeshViewT The mesh view type for all elements to erase
* @tparam HandleT The handle type of the element to delete
* @param mesh_obj The host mesh object
* @param element_view A mesh view which stores all elements to be marked
* @param host_element A handle object of the host element
*/
template<typename MeshT, typename MeshViewT, typename HandleT>
void mark_referencing_elements( MeshT & mesh_obj, MeshViewT & element_view, HandleT host_element )
{
detail::mark_referencing_elements_impl<MeshT, MeshViewT, HandleT>::mark(mesh_obj, element_view, host_element);
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Original author: Jim Blandy <[email protected]> <[email protected]>
// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.
#include "common/language.h"
namespace google_breakpad {
// C++ language-specific operations.
class CPPLanguage: public Language {
public:
string MakeQualifiedName(const string &parent_name,
const string &name) const {
if (parent_name.empty())
return name;
else
return parent_name + "::" + name;
}
};
const CPPLanguage CPPLanguageSingleton;
// Java language-specific operations.
class JavaLanguage: public Language {
public:
string MakeQualifiedName(const string &parent_name,
const string &name) const {
if (parent_name.empty())
return name;
else
return parent_name + "." + name;
}
};
JavaLanguage JavaLanguageSingleton;
// Assembler language-specific operations.
class AssemblerLanguage: public Language {
bool HasFunctions() const { return false; }
string MakeQualifiedName(const string &parent_name,
const string &name) const {
return name;
}
};
AssemblerLanguage AssemblerLanguageSingleton;
const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;
} // namespace google_breakpad
<commit_msg>Add missing constructor to CPPLanguage class to make it compile with CLang. P=rafael.espindola R=jimb at https://bugzilla.mozilla.org/show_bug.cgi?id=623121<commit_after>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Original author: Jim Blandy <[email protected]> <[email protected]>
// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.
#include "common/language.h"
namespace google_breakpad {
// C++ language-specific operations.
class CPPLanguage: public Language {
public:
CPPLanguage() {}
string MakeQualifiedName(const string &parent_name,
const string &name) const {
if (parent_name.empty())
return name;
else
return parent_name + "::" + name;
}
};
const CPPLanguage CPPLanguageSingleton;
// Java language-specific operations.
class JavaLanguage: public Language {
public:
string MakeQualifiedName(const string &parent_name,
const string &name) const {
if (parent_name.empty())
return name;
else
return parent_name + "." + name;
}
};
JavaLanguage JavaLanguageSingleton;
// Assembler language-specific operations.
class AssemblerLanguage: public Language {
bool HasFunctions() const { return false; }
string MakeQualifiedName(const string &parent_name,
const string &name) const {
return name;
}
};
AssemblerLanguage AssemblerLanguageSingleton;
const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;
} // namespace google_breakpad
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/widget/tooltip_manager_gtk.h"
#include "app/gfx/font.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "views/focus/focus_manager.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
// WARNING: this implementation is good for a start, but it doesn't give us
// control of tooltip positioning both on mouse events and when showing from
// keyboard. We may need to write our own to give us the control we need.
namespace views {
static gfx::Font* LoadDefaultFont() {
// Create a tooltip widget and extract the font from it (we have to realize
// it to make sure the correct font gets set).
GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
gtk_widget_set_name(window, "gtk-tooltip");
GtkWidget* label = gtk_label_new("");
gtk_widget_show(label);
gtk_container_add(GTK_CONTAINER(window), label);
gtk_widget_realize(window);
GtkStyle* style = gtk_widget_get_style(label);
PangoFontDescription* pfd = style->font_desc;
gfx::Font* font = new gfx::Font(gfx::Font::CreateFont(pfd));
pango_font_description_free(pfd);
gtk_widget_destroy(window);
return font;
}
// static
int TooltipManager::GetTooltipHeight() {
// This is only used to position the tooltip, and we don't yet support
// positioning the tooltip, it isn't worth trying to implement this.
return 0;
}
// static
gfx::Font TooltipManager::GetDefaultFont() {
static gfx::Font* font = NULL;
if (!font)
font = LoadDefaultFont();
return *font;
}
// static
const std::wstring& TooltipManager::GetLineSeparator() {
static std::wstring* line_separator = NULL;
if (!line_separator)
line_separator = new std::wstring(L"\n");
return *line_separator;
}
// Callback from gtk_container_foreach. If |*label_p| is NULL and |widget| is
// a GtkLabel, |*label_p| is set to |widget|. Used to find the first GtkLabel
// in a container.
static void LabelLocatorCallback(GtkWidget* widget,
gpointer label_p) {
GtkWidget** label = static_cast<GtkWidget**>(label_p);
if (!*label && GTK_IS_LABEL(widget))
*label = widget;
}
// By default GtkTooltip wraps at a longish string. We want more control over
// that wrapping. The only way to do that is dig out the label and set
// gtk_label_set_max_width_chars, which is what this code does. I also tried
// setting a custom widget on the tooltip, but there is a bug in Gtk that
// triggers continually hiding/showing the widget in that case.
static void AdjustLabel(GtkTooltip* tooltip) {
static const char kAdjustedLabelPropertyValue[] = "_adjusted_label_";
gpointer adjusted_value = g_object_get_data(G_OBJECT(tooltip),
kAdjustedLabelPropertyValue);
if (adjusted_value)
return;
adjusted_value = reinterpret_cast<gpointer>(1);
g_object_set_data(G_OBJECT(tooltip), kAdjustedLabelPropertyValue,
adjusted_value);
GtkWidget* parent;
{
// Create a label so that we can get the parent. The Tooltip ends up taking
// ownership of the label and deleting it.
GtkWidget* label = gtk_label_new("");
gtk_tooltip_set_custom(tooltip, label);
parent = gtk_widget_get_parent(label);
gtk_tooltip_set_custom(tooltip, NULL);
}
if (parent) {
// We found the parent, find the first label, which is where the tooltip
// text ends up going.
GtkLabel* real_label = NULL;
gtk_container_foreach(GTK_CONTAINER(parent), LabelLocatorCallback,
static_cast<gpointer>(&real_label));
if (real_label)
gtk_label_set_max_width_chars(GTK_LABEL(real_label), 3000);
}
}
TooltipManagerGtk::TooltipManagerGtk(WidgetGtk* widget)
: widget_(widget),
keyboard_view_(NULL) {
}
bool TooltipManagerGtk::ShowTooltip(int x, int y, bool for_keyboard,
GtkTooltip* tooltip) {
View* view = NULL;
gfx::Point view_loc;
if (keyboard_view_) {
view = keyboard_view_;
view_loc.SetPoint(view->width() / 2, view->height() / 2);
} else if (!for_keyboard) {
RootView* root_view = widget_->GetRootView();
view = root_view->GetViewForPoint(gfx::Point(x, y));
view_loc.SetPoint(x, y);
View::ConvertPointFromWidget(view, &view_loc);
} else {
FocusManager* focus_manager = widget_->GetFocusManager();
if (focus_manager) {
view = focus_manager->GetFocusedView();
if (view)
view_loc.SetPoint(view->width() / 2, view->height() / 2);
}
}
if (!view)
return false;
std::wstring text;
if (!view->GetTooltipText(view_loc.x(), view_loc.y(), &text))
return false;
AdjustLabel(tooltip);
// Sets the area of the tooltip. This way if different views in the same
// widget have tooltips the tooltip doesn't get stuck at the same location.
gfx::Rect vis_bounds = view->GetVisibleBounds();
gfx::Point widget_loc(vis_bounds.x(), vis_bounds.y());
View::ConvertPointToWidget(view, &widget_loc);
GdkRectangle tip_area = { widget_loc.x(), widget_loc.y(),
vis_bounds.width(), vis_bounds.height() };
gtk_tooltip_set_tip_area(tooltip, &tip_area);
int max_width, line_count;
gfx::Point screen_loc(x, y);
View::ConvertPointToScreen(widget_->GetRootView(), &screen_loc);
TrimTooltipToFit(&text, &max_width, &line_count, screen_loc.x(),
screen_loc.y());
gtk_tooltip_set_text(tooltip, WideToUTF8(text).c_str());
return true;
}
void TooltipManagerGtk::UpdateTooltip() {
// UpdateTooltip may be invoked after the widget has been destroyed.
GtkWidget* widget = widget_->GetNativeView();
if (!widget)
return;
GdkDisplay* display = gtk_widget_get_display(widget);
if (display)
gtk_tooltip_trigger_tooltip_query(display);
}
void TooltipManagerGtk::TooltipTextChanged(View* view) {
UpdateTooltip();
}
void TooltipManagerGtk::ShowKeyboardTooltip(View* view) {
if (view == keyboard_view_)
return; // We're already showing the tip for the specified view.
// We have to hide the current tooltip, then show again.
HideKeyboardTooltip();
std::wstring tooltip_text;
if (!view->GetTooltipText(0, 0, &tooltip_text))
return; // The view doesn't have a tooltip, nothing to do.
keyboard_view_ = view;
if (!SendShowHelpSignal()) {
keyboard_view_ = NULL;
return;
}
}
void TooltipManagerGtk::HideKeyboardTooltip() {
if (!keyboard_view_)
return;
SendShowHelpSignal();
keyboard_view_ = NULL;
}
bool TooltipManagerGtk::SendShowHelpSignal() {
GtkWidget* widget = widget_->window_contents();
GType itype = G_TYPE_FROM_INSTANCE(G_OBJECT(widget));
guint signal_id;
GQuark detail;
if (!g_signal_parse_name("show_help", itype, &signal_id, &detail, FALSE)) {
NOTREACHED();
return false;
}
gboolean result;
g_signal_emit(widget, signal_id, 0, GTK_WIDGET_HELP_TOOLTIP, &result);
return true;
}
} // namespace views
<commit_msg>Fixes possible crash in tool tip manager.<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 "views/widget/tooltip_manager_gtk.h"
#include "app/gfx/font.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "views/focus/focus_manager.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
// WARNING: this implementation is good for a start, but it doesn't give us
// control of tooltip positioning both on mouse events and when showing from
// keyboard. We may need to write our own to give us the control we need.
namespace views {
static gfx::Font* LoadDefaultFont() {
// Create a tooltip widget and extract the font from it (we have to realize
// it to make sure the correct font gets set).
GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
gtk_widget_set_name(window, "gtk-tooltip");
GtkWidget* label = gtk_label_new("");
gtk_widget_show(label);
gtk_container_add(GTK_CONTAINER(window), label);
gtk_widget_realize(window);
GtkStyle* style = gtk_widget_get_style(label);
PangoFontDescription* pfd = style->font_desc;
gfx::Font* font = new gfx::Font(gfx::Font::CreateFont(pfd));
pango_font_description_free(pfd);
gtk_widget_destroy(window);
return font;
}
// static
int TooltipManager::GetTooltipHeight() {
// This is only used to position the tooltip, and we don't yet support
// positioning the tooltip, it isn't worth trying to implement this.
return 0;
}
// static
gfx::Font TooltipManager::GetDefaultFont() {
static gfx::Font* font = NULL;
if (!font)
font = LoadDefaultFont();
return *font;
}
// static
const std::wstring& TooltipManager::GetLineSeparator() {
static std::wstring* line_separator = NULL;
if (!line_separator)
line_separator = new std::wstring(L"\n");
return *line_separator;
}
// Callback from gtk_container_foreach. If |*label_p| is NULL and |widget| is
// a GtkLabel, |*label_p| is set to |widget|. Used to find the first GtkLabel
// in a container.
static void LabelLocatorCallback(GtkWidget* widget,
gpointer label_p) {
GtkWidget** label = static_cast<GtkWidget**>(label_p);
if (!*label && GTK_IS_LABEL(widget))
*label = widget;
}
// By default GtkTooltip wraps at a longish string. We want more control over
// that wrapping. The only way to do that is dig out the label and set
// gtk_label_set_max_width_chars, which is what this code does. I also tried
// setting a custom widget on the tooltip, but there is a bug in Gtk that
// triggers continually hiding/showing the widget in that case.
static void AdjustLabel(GtkTooltip* tooltip) {
static const char kAdjustedLabelPropertyValue[] = "_adjusted_label_";
gpointer adjusted_value = g_object_get_data(G_OBJECT(tooltip),
kAdjustedLabelPropertyValue);
if (adjusted_value)
return;
adjusted_value = reinterpret_cast<gpointer>(1);
g_object_set_data(G_OBJECT(tooltip), kAdjustedLabelPropertyValue,
adjusted_value);
GtkWidget* parent;
{
// Create a label so that we can get the parent. The Tooltip ends up taking
// ownership of the label and deleting it.
GtkWidget* label = gtk_label_new("");
gtk_tooltip_set_custom(tooltip, label);
parent = gtk_widget_get_parent(label);
gtk_tooltip_set_custom(tooltip, NULL);
}
if (parent) {
// We found the parent, find the first label, which is where the tooltip
// text ends up going.
GtkLabel* real_label = NULL;
gtk_container_foreach(GTK_CONTAINER(parent), LabelLocatorCallback,
static_cast<gpointer>(&real_label));
if (real_label) {
// For some reason I'm occasionally seeing a crash in trying to get font
// metrics. Explicitly setting the font avoids this.
PangoFontDescription* pfd =
gfx::Font::PangoFontFromGfxFont(gfx::Font());
gtk_widget_modify_font(GTK_WIDGET(real_label), pfd);
pango_font_description_free(pfd);
gtk_label_set_max_width_chars(GTK_LABEL(real_label), 3000);
}
}
}
TooltipManagerGtk::TooltipManagerGtk(WidgetGtk* widget)
: widget_(widget),
keyboard_view_(NULL) {
}
bool TooltipManagerGtk::ShowTooltip(int x, int y, bool for_keyboard,
GtkTooltip* tooltip) {
View* view = NULL;
gfx::Point view_loc;
if (keyboard_view_) {
view = keyboard_view_;
view_loc.SetPoint(view->width() / 2, view->height() / 2);
} else if (!for_keyboard) {
RootView* root_view = widget_->GetRootView();
view = root_view->GetViewForPoint(gfx::Point(x, y));
view_loc.SetPoint(x, y);
View::ConvertPointFromWidget(view, &view_loc);
} else {
FocusManager* focus_manager = widget_->GetFocusManager();
if (focus_manager) {
view = focus_manager->GetFocusedView();
if (view)
view_loc.SetPoint(view->width() / 2, view->height() / 2);
}
}
if (!view)
return false;
std::wstring text;
if (!view->GetTooltipText(view_loc.x(), view_loc.y(), &text))
return false;
AdjustLabel(tooltip);
// Sets the area of the tooltip. This way if different views in the same
// widget have tooltips the tooltip doesn't get stuck at the same location.
gfx::Rect vis_bounds = view->GetVisibleBounds();
gfx::Point widget_loc(vis_bounds.x(), vis_bounds.y());
View::ConvertPointToWidget(view, &widget_loc);
GdkRectangle tip_area = { widget_loc.x(), widget_loc.y(),
vis_bounds.width(), vis_bounds.height() };
gtk_tooltip_set_tip_area(tooltip, &tip_area);
int max_width, line_count;
gfx::Point screen_loc(x, y);
View::ConvertPointToScreen(widget_->GetRootView(), &screen_loc);
TrimTooltipToFit(&text, &max_width, &line_count, screen_loc.x(),
screen_loc.y());
gtk_tooltip_set_text(tooltip, WideToUTF8(text).c_str());
return true;
}
void TooltipManagerGtk::UpdateTooltip() {
// UpdateTooltip may be invoked after the widget has been destroyed.
GtkWidget* widget = widget_->GetNativeView();
if (!widget)
return;
GdkDisplay* display = gtk_widget_get_display(widget);
if (display)
gtk_tooltip_trigger_tooltip_query(display);
}
void TooltipManagerGtk::TooltipTextChanged(View* view) {
UpdateTooltip();
}
void TooltipManagerGtk::ShowKeyboardTooltip(View* view) {
if (view == keyboard_view_)
return; // We're already showing the tip for the specified view.
// We have to hide the current tooltip, then show again.
HideKeyboardTooltip();
std::wstring tooltip_text;
if (!view->GetTooltipText(0, 0, &tooltip_text))
return; // The view doesn't have a tooltip, nothing to do.
keyboard_view_ = view;
if (!SendShowHelpSignal()) {
keyboard_view_ = NULL;
return;
}
}
void TooltipManagerGtk::HideKeyboardTooltip() {
if (!keyboard_view_)
return;
SendShowHelpSignal();
keyboard_view_ = NULL;
}
bool TooltipManagerGtk::SendShowHelpSignal() {
GtkWidget* widget = widget_->window_contents();
GType itype = G_TYPE_FROM_INSTANCE(G_OBJECT(widget));
guint signal_id;
GQuark detail;
if (!g_signal_parse_name("show_help", itype, &signal_id, &detail, FALSE)) {
NOTREACHED();
return false;
}
gboolean result;
g_signal_emit(widget, signal_id, 0, GTK_WIDGET_HELP_TOOLTIP, &result);
return true;
}
} // namespace views
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief RX65N/RX72N Envision Kit デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
/// #define CASH_KFONT
#include "common/renesas.hpp"
#include "common/cmt_mgr.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/shell.hpp"
#include "common/tpu_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#include "graphics/kfont.hpp"
#include "graphics/font.hpp"
#include "graphics/simple_dialog.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "dso_gui.hpp"
namespace {
static const int16_t LCD_X = 480;
static const int16_t LCD_Y = 272;
static const auto PIX = graphics::pixel::TYPE::RGB565;
typedef utils::fixed_fifo<uint8_t, 64> RB64;
typedef utils::fixed_fifo<uint8_t, 64> SB64;
#if defined(SIG_RX65N)
static const char* sys_msg_ = { "RX65N Envision Kit" };
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
// フレームバッファ開始アドレスは、100 番地から開始とする。
// ※0~FFは未使用領域
static void* LCD_ORG = reinterpret_cast<void*>(0x00000100);
// SD カード電源制御を使わない場合、「device::NULL_PORT」を指定する。
typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
// 書き込み禁止は使わない
typedef device::NULL_PORT SDC_WP;
// タッチセンサー「RESET」制御ポート
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
// タッチセンサー I2C ポート設定
typedef device::sci_i2c_io<device::SCI6, RB64, SB64, device::port_map::option::FIRST_I2C> FT5206_I2C;
#elif defined(SIG_RX72N)
static const char* sys_msg_ = { "RX72N Envision Kit" };
typedef device::system_io<16'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
// GLCDC の制御関係
typedef device::PORT<device::PORTB, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B7> LCD_LIGHT;
static void* LCD_ORG = reinterpret_cast<void*>(0x0080'0000);
// SD カードの制御ポート設定
typedef device::PORT<device::PORT4, device::bitpos::B2> SDC_POWER;
// 書き込み禁止は使わない
typedef device::NULL_PORT SDC_WP;
// タッチセンサー「RESET」制御ポート
typedef device::PORT<device::PORT6, device::bitpos::B6> FT5206_RESET;
// タッチセンサー I2C ポート設定
typedef device::sci_i2c_io<device::SCI6, RB64, SB64, device::port_map::option::THIRD_I2C> FT5206_I2C;
#endif
typedef device::cmt_mgr<device::CMT0> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<SCI_CH, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// RX65N/RX72N Envision Kit の SDHI は、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, SDC_WP, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
typedef device::glcdc_mgr<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC_MGR;
GLCDC_MGR glcdc_mgr_(nullptr, LCD_ORG);
typedef graphics::font8x16 AFONT;
AFONT afont_;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::font<AFONT, KFONT> FONT;
FONT font_(afont_, kfont_);
typedef graphics::render<GLCDC_MGR, FONT> RENDER;
RENDER render_(glcdc_mgr_, font_);
// 標準カラーインスタンス
typedef graphics::def_color DEF_COLOR;
typedef dsos::capture<8192> CAPTURE;
CAPTURE capture_;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> TOUCH;
TOUCH touch_(ft5206_i2c_);
typedef gui::simple_dialog<RENDER, TOUCH> DIALOG;
DIALOG dialog_(render_, touch_);
typedef dsos::dso_gui<RENDER, TOUCH, CAPTURE> DSO_GUI;
DSO_GUI dso_gui_(render_, touch_, capture_);
typedef utils::command<256> CMD;
CMD cmd_;
typedef utils::shell<CMD> SHELL;
SHELL shell_(cmd_);
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void setup_touch_panel_()
{
render_.sync_frame();
dialog_.modal(vtx::spos(400, 60),
"Touch panel device wait...\nPlease touch it with some screen.");
uint8_t nnn = 0;
while(1) {
render_.sync_frame();
touch_.update();
auto num = touch_.get_touch_num();
if(num == 0) {
++nnn;
if(nnn >= 60) break;
} else {
nnn = 0;
}
}
render_.clear(DEF_COLOR::Black);
}
void command_()
{
if(!cmd_.service()) {
return;
}
if(shell_.analize()) {
return;
}
if(cmd_.cmp_word(0, "cap")) { // capture
// trigger_ = utils::capture_trigger::SINGLE;
// capture_.set_trigger(trigger_);
} else if(cmd_.cmp_word(0, "help")) {
shell_.help();
utils::format(" cap single trigger\n");
} else {
utils::format("Command error: '%s'\n") % cmd_.get_command();
}
}
}
/// widget の登録・グローバル関数
bool insert_widget(gui::widget* w)
{
return dso_gui_.at_widd().insert(w);
}
/// widget の解除・グローバル関数
void remove_widget(gui::widget* w)
{
dso_gui_.at_widd().remove(w);
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = utils::str::get_compiled_time();
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
}
{ // キャプチャー開始
uint32_t freq = 2000000; // 2 MHz
// uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("\r%s Start for Digital Storage Oscilloscope\n") % sys_msg_;
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_mgr_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_mgr_.control(GLCDC_MGR::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
} else {
utils::format("GLCDC Fail\n");
}
}
#if 0
{ // DRW2D 初期化
auto ver = render_.get_version();
utils::format("DRW2D Version: %04X\n") % ver;
if(render_.start()) {
utils:: format("Start DRW2D\n");
} else {
utils:: format("DRW2D Fail\n");
}
}
#endif
{ // FT5206 touch screen controller
TOUCH::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!touch_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
setup_touch_panel_();
dso_gui_.start();
LED::OUTPUT();
cmd_.set_prompt("# ");
glcdc_mgr_.enable_double();
while(1) {
render_.sync_frame();
touch_.update();
sdh_.service();
command_();
dso_gui_.update();
update_led_();
}
}
<commit_msg>Update: DRW2D<commit_after>//=====================================================================//
/*! @file
@brief RX65N/RX72N Envision Kit デジタル・ストレージ・オシロスコープ @n
マイコン内臓12ビットA/D変換を使って、波形を観測するガジェット
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
/// #define CASH_KFONT
#include "common/renesas.hpp"
#include "common/cmt_mgr.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/sci_i2c_io.hpp"
#include "common/format.hpp"
#include "common/command.hpp"
#include "common/shell.hpp"
#include "common/tpu_io.hpp"
#include "graphics/font8x16.hpp"
#include "graphics/graphics.hpp"
#include "graphics/filer.hpp"
#include "graphics/kfont.hpp"
#include "graphics/font.hpp"
#include "graphics/simple_dialog.hpp"
#include "chip/FT5206.hpp"
#include "capture.hpp"
#include "dso_gui.hpp"
namespace {
static const int16_t LCD_X = 480;
static const int16_t LCD_Y = 272;
static const auto PIX = graphics::pixel::TYPE::RGB565;
typedef utils::fixed_fifo<uint8_t, 64> RB64;
typedef utils::fixed_fifo<uint8_t, 64> SB64;
#if defined(SIG_RX65N)
static const char* sys_msg_ = { "RX65N Envision Kit" };
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;
// フレームバッファ開始アドレスは、100 番地から開始とする。
// ※0~FFは未使用領域
static void* LCD_ORG = reinterpret_cast<void*>(0x00000100);
// SD カード電源制御を使わない場合、「device::NULL_PORT」を指定する。
typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;
// 書き込み禁止は使わない
typedef device::NULL_PORT SDC_WP;
// タッチセンサー「RESET」制御ポート
typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
// タッチセンサー I2C ポート設定
typedef device::sci_i2c_io<device::SCI6, RB64, SB64, device::port_map::option::FIRST_I2C> FT5206_I2C;
#elif defined(SIG_RX72N)
static const char* sys_msg_ = { "RX72N Envision Kit" };
typedef device::system_io<16'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
// GLCDC の制御関係
typedef device::PORT<device::PORTB, device::bitpos::B3> LCD_DISP;
typedef device::PORT<device::PORT6, device::bitpos::B7> LCD_LIGHT;
static void* LCD_ORG = reinterpret_cast<void*>(0x0080'0000);
// SD カードの制御ポート設定
typedef device::PORT<device::PORT4, device::bitpos::B2> SDC_POWER;
// 書き込み禁止は使わない
typedef device::NULL_PORT SDC_WP;
// タッチセンサー「RESET」制御ポート
typedef device::PORT<device::PORT6, device::bitpos::B6> FT5206_RESET;
// タッチセンサー I2C ポート設定
typedef device::sci_i2c_io<device::SCI6, RB64, SB64, device::port_map::option::THIRD_I2C> FT5206_I2C;
#endif
typedef device::cmt_mgr<device::CMT0> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 512> RECV_BUFF;
typedef utils::fixed_fifo<char, 1024> SEND_BUFF;
typedef device::sci_io<SCI_CH, RECV_BUFF, SEND_BUFF> SCI;
SCI sci_;
// RX65N/RX72N Envision Kit の SDHI は、候補3になっている
typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, SDC_WP, device::port_map::option::THIRD> SDHI;
SDHI sdh_;
typedef device::glcdc_mgr<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC_MGR;
GLCDC_MGR glcdc_mgr_(nullptr, LCD_ORG);
typedef graphics::font8x16 AFONT;
AFONT afont_;
#ifdef CASH_KFONT
typedef graphics::kfont<16, 16, 64> KFONT;
#else
typedef graphics::kfont<16, 16> KFONT;
#endif
KFONT kfont_;
typedef graphics::font<AFONT, KFONT> FONT;
FONT font_(afont_, kfont_);
// typedef graphics::render<GLCDC_MGR, FONT> RENDER;
typedef device::drw2d_mgr<GLCDC_MGR, FONT> RENDER;
RENDER render_(glcdc_mgr_, font_);
// 標準カラーインスタンス
typedef graphics::def_color DEF_COLOR;
typedef dsos::capture<8192> CAPTURE;
CAPTURE capture_;
FT5206_I2C ft5206_i2c_;
typedef chip::FT5206<FT5206_I2C> TOUCH;
TOUCH touch_(ft5206_i2c_);
typedef gui::simple_dialog<RENDER, TOUCH> DIALOG;
DIALOG dialog_(render_, touch_);
typedef dsos::dso_gui<RENDER, TOUCH, CAPTURE> DSO_GUI;
DSO_GUI dso_gui_(render_, touch_, capture_);
typedef utils::command<256> CMD;
CMD cmd_;
typedef utils::shell<CMD> SHELL;
SHELL shell_(cmd_);
void update_led_()
{
static uint8_t n = 0;
++n;
if(n >= 30) {
n = 0;
}
if(n < 10) {
LED::P = 0;
} else {
LED::P = 1;
}
}
void setup_touch_panel_()
{
render_.sync_frame();
dialog_.modal(vtx::spos(400, 60),
"Touch panel device wait...\nPlease touch it with some screen.");
uint8_t nnn = 0;
while(1) {
render_.sync_frame();
touch_.update();
auto num = touch_.get_touch_num();
if(num == 0) {
++nnn;
if(nnn >= 60) break;
} else {
nnn = 0;
}
}
render_.clear(DEF_COLOR::Black);
}
void command_()
{
if(!cmd_.service()) {
return;
}
if(shell_.analize()) {
return;
}
if(cmd_.cmp_word(0, "cap")) { // capture
// trigger_ = utils::capture_trigger::SINGLE;
// capture_.set_trigger(trigger_);
} else if(cmd_.cmp_word(0, "help")) {
shell_.help();
utils::format(" cap single trigger\n");
} else {
utils::format("Command error: '%s'\n") % cmd_.get_command();
}
}
}
/// widget の登録・グローバル関数
bool insert_widget(gui::widget* w)
{
return dso_gui_.at_widd().insert(w);
}
/// widget の解除・グローバル関数
void remove_widget(gui::widget* w)
{
dso_gui_.at_widd().remove(w);
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdh_.disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdh_.disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdh_.disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdh_.disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
time_t t = utils::str::get_compiled_time();
/// rtc_.get_time(t);
return utils::str::get_fattime(t);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
{ // SD カード・クラスの初期化
sdh_.start();
}
{ // キャプチャー開始
uint32_t freq = 2000000; // 2 MHz
// uint32_t freq = 100000; // 100 KHz
if(!capture_.start(freq)) {
utils::format("Capture not start...\n");
}
}
utils::format("\r%s Start for Digital Storage Oscilloscope\n") % sys_msg_;
{ // GLCDC の初期化
LCD_DISP::DIR = 1;
LCD_LIGHT::DIR = 1;
LCD_DISP::P = 0; // DISP Disable
LCD_LIGHT::P = 0; // BackLight Disable (No PWM)
if(glcdc_mgr_.start()) {
utils::format("Start GLCDC\n");
LCD_DISP::P = 1; // DISP Enable
LCD_LIGHT::P = 1; // BackLight Enable (No PWM)
if(!glcdc_mgr_.control(GLCDC_MGR::CONTROL_CMD::START_DISPLAY)) {
utils::format("GLCDC ctrl fail...\n");
}
glcdc_mgr_.enable_double_buffer();
} else {
utils::format("GLCDC Fail\n");
}
}
{ // DRW2D 初期化
if(render_.start()) {
utils:: format("Start DRW2D\n");
auto ver = render_.get_version();
utils::format(" Version: %04X\n") % ver;
} else {
utils:: format("DRW2D Fail\n");
}
}
{ // FT5206 touch screen controller
TOUCH::reset<FT5206_RESET>();
uint8_t intr_lvl = 1;
if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
utils::format("FT5206 I2C Start Fail...\n");
}
if(!touch_.start()) {
utils::format("FT5206 Start Fail...\n");
}
}
setup_touch_panel_();
dso_gui_.start();
LED::OUTPUT();
cmd_.set_prompt("# ");
while(1) {
render_.sync_frame();
touch_.update();
sdh_.service();
command_();
dso_gui_.update();
update_led_();
}
}
<|endoftext|> |
<commit_before>//-- SystemZMachineScheduler.cpp - SystemZ Scheduler Interface -*- C++ -*---==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// -------------------------- Post RA scheduling ---------------------------- //
// SystemZPostRASchedStrategy is a scheduling strategy which is plugged into
// the MachineScheduler. It has a sorted Available set of SUs and a pickNode()
// implementation that looks to optimize decoder grouping and balance the
// usage of processor resources.
//===----------------------------------------------------------------------===//
#include "SystemZMachineScheduler.h"
using namespace llvm;
#define DEBUG_TYPE "misched"
#ifndef NDEBUG
// Print the set of SUs
void SystemZPostRASchedStrategy::SUSet::
dump(SystemZHazardRecognizer &HazardRec) {
dbgs() << "{";
for (auto &SU : *this) {
HazardRec.dumpSU(SU, dbgs());
if (SU != *rbegin())
dbgs() << ", ";
}
dbgs() << "}\n";
}
#endif
SystemZPostRASchedStrategy::
SystemZPostRASchedStrategy(const MachineSchedContext *C)
: DAG(nullptr), HazardRec(C) {}
void SystemZPostRASchedStrategy::initialize(ScheduleDAGMI *dag) {
DAG = dag;
HazardRec.setDAG(dag);
HazardRec.Reset();
}
// Pick the next node to schedule.
SUnit *SystemZPostRASchedStrategy::pickNode(bool &IsTopNode) {
// Only scheduling top-down.
IsTopNode = true;
if (Available.empty())
return nullptr;
// If only one choice, return it.
if (Available.size() == 1) {
DEBUG (dbgs() << "+++ Only one: ";
HazardRec.dumpSU(*Available.begin(), dbgs()); dbgs() << "\n";);
return *Available.begin();
}
// All nodes that are possible to schedule are stored by in the
// Available set.
DEBUG(dbgs() << "+++ Available: "; Available.dump(HazardRec););
Candidate Best;
for (auto *SU : Available) {
// SU is the next candidate to be compared against current Best.
Candidate c(SU, HazardRec);
// Remeber which SU is the best candidate.
if (Best.SU == nullptr || c < Best) {
Best = c;
DEBUG(dbgs() << "+++ Best sofar: ";
HazardRec.dumpSU(Best.SU, dbgs());
if (Best.GroupingCost != 0)
dbgs() << "\tGrouping cost:" << Best.GroupingCost;
if (Best.ResourcesCost != 0)
dbgs() << " Resource cost:" << Best.ResourcesCost;
dbgs() << " Height:" << Best.SU->getHeight();
dbgs() << "\n";);
}
// Once we know we have seen all SUs that affect grouping or use unbuffered
// resources, we can stop iterating if Best looks good.
if (!SU->isScheduleHigh && Best.noCost())
break;
}
assert (Best.SU != nullptr);
return Best.SU;
}
SystemZPostRASchedStrategy::Candidate::
Candidate(SUnit *SU_, SystemZHazardRecognizer &HazardRec) : Candidate() {
SU = SU_;
// Check the grouping cost. For a node that must begin / end a
// group, it is positive if it would do so prematurely, or negative
// if it would fit naturally into the schedule.
GroupingCost = HazardRec.groupingCost(SU);
// Check the resources cost for this SU.
ResourcesCost = HazardRec.resourcesCost(SU);
}
bool SystemZPostRASchedStrategy::Candidate::
operator<(const Candidate &other) {
// Check decoder grouping.
if (GroupingCost < other.GroupingCost)
return true;
if (GroupingCost > other.GroupingCost)
return false;
// Compare the use of resources.
if (ResourcesCost < other.ResourcesCost)
return true;
if (ResourcesCost > other.ResourcesCost)
return false;
// Higher SU is otherwise generally better.
if (SU->getHeight() > other.SU->getHeight())
return true;
if (SU->getHeight() < other.SU->getHeight())
return false;
// If all same, fall back to original order.
if (SU->NodeNum < other.SU->NodeNum)
return true;
return false;
}
void SystemZPostRASchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {
DEBUG(dbgs() << "+++ Scheduling SU(" << SU->NodeNum << ")\n";);
// Remove SU from Available set and update HazardRec.
Available.erase(SU);
HazardRec.EmitInstruction(SU);
}
void SystemZPostRASchedStrategy::releaseTopNode(SUnit *SU) {
// Set isScheduleHigh flag on all SUs that we want to consider first in
// pickNode().
const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
bool AffectsGrouping = (SC->isValid() && (SC->BeginGroup || SC->EndGroup));
SU->isScheduleHigh = (AffectsGrouping || SU->isUnbuffered);
// Put all released SUs in the Available set.
Available.insert(SU);
}
<commit_msg>Fix build.<commit_after>//-- SystemZMachineScheduler.cpp - SystemZ Scheduler Interface -*- C++ -*---==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// -------------------------- Post RA scheduling ---------------------------- //
// SystemZPostRASchedStrategy is a scheduling strategy which is plugged into
// the MachineScheduler. It has a sorted Available set of SUs and a pickNode()
// implementation that looks to optimize decoder grouping and balance the
// usage of processor resources.
//===----------------------------------------------------------------------===//
#include "SystemZMachineScheduler.h"
using namespace llvm;
#define DEBUG_TYPE "misched"
#ifndef NDEBUG
// Print the set of SUs
void SystemZPostRASchedStrategy::SUSet::
dump(SystemZHazardRecognizer &HazardRec) const {
dbgs() << "{";
for (auto &SU : *this) {
HazardRec.dumpSU(SU, dbgs());
if (SU != *rbegin())
dbgs() << ", ";
}
dbgs() << "}\n";
}
#endif
SystemZPostRASchedStrategy::
SystemZPostRASchedStrategy(const MachineSchedContext *C)
: DAG(nullptr), HazardRec(C) {}
void SystemZPostRASchedStrategy::initialize(ScheduleDAGMI *dag) {
DAG = dag;
HazardRec.setDAG(dag);
HazardRec.Reset();
}
// Pick the next node to schedule.
SUnit *SystemZPostRASchedStrategy::pickNode(bool &IsTopNode) {
// Only scheduling top-down.
IsTopNode = true;
if (Available.empty())
return nullptr;
// If only one choice, return it.
if (Available.size() == 1) {
DEBUG (dbgs() << "+++ Only one: ";
HazardRec.dumpSU(*Available.begin(), dbgs()); dbgs() << "\n";);
return *Available.begin();
}
// All nodes that are possible to schedule are stored by in the
// Available set.
DEBUG(dbgs() << "+++ Available: "; Available.dump(HazardRec););
Candidate Best;
for (auto *SU : Available) {
// SU is the next candidate to be compared against current Best.
Candidate c(SU, HazardRec);
// Remeber which SU is the best candidate.
if (Best.SU == nullptr || c < Best) {
Best = c;
DEBUG(dbgs() << "+++ Best sofar: ";
HazardRec.dumpSU(Best.SU, dbgs());
if (Best.GroupingCost != 0)
dbgs() << "\tGrouping cost:" << Best.GroupingCost;
if (Best.ResourcesCost != 0)
dbgs() << " Resource cost:" << Best.ResourcesCost;
dbgs() << " Height:" << Best.SU->getHeight();
dbgs() << "\n";);
}
// Once we know we have seen all SUs that affect grouping or use unbuffered
// resources, we can stop iterating if Best looks good.
if (!SU->isScheduleHigh && Best.noCost())
break;
}
assert (Best.SU != nullptr);
return Best.SU;
}
SystemZPostRASchedStrategy::Candidate::
Candidate(SUnit *SU_, SystemZHazardRecognizer &HazardRec) : Candidate() {
SU = SU_;
// Check the grouping cost. For a node that must begin / end a
// group, it is positive if it would do so prematurely, or negative
// if it would fit naturally into the schedule.
GroupingCost = HazardRec.groupingCost(SU);
// Check the resources cost for this SU.
ResourcesCost = HazardRec.resourcesCost(SU);
}
bool SystemZPostRASchedStrategy::Candidate::
operator<(const Candidate &other) {
// Check decoder grouping.
if (GroupingCost < other.GroupingCost)
return true;
if (GroupingCost > other.GroupingCost)
return false;
// Compare the use of resources.
if (ResourcesCost < other.ResourcesCost)
return true;
if (ResourcesCost > other.ResourcesCost)
return false;
// Higher SU is otherwise generally better.
if (SU->getHeight() > other.SU->getHeight())
return true;
if (SU->getHeight() < other.SU->getHeight())
return false;
// If all same, fall back to original order.
if (SU->NodeNum < other.SU->NodeNum)
return true;
return false;
}
void SystemZPostRASchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {
DEBUG(dbgs() << "+++ Scheduling SU(" << SU->NodeNum << ")\n";);
// Remove SU from Available set and update HazardRec.
Available.erase(SU);
HazardRec.EmitInstruction(SU);
}
void SystemZPostRASchedStrategy::releaseTopNode(SUnit *SU) {
// Set isScheduleHigh flag on all SUs that we want to consider first in
// pickNode().
const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
bool AffectsGrouping = (SC->isValid() && (SC->BeginGroup || SC->EndGroup));
SU->isScheduleHigh = (AffectsGrouping || SU->isUnbuffered);
// Put all released SUs in the Available set.
Available.insert(SU);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#define SOFA_COMPONENT_ENGINE_PROJECTIVETRANSFORMENGINE_CPP
#include <SofaMiscEngine/ProjectiveTransformEngine.inl>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace engine
{
SOFA_DECL_CLASS(ProjectiveTransformEngine)
int ProjectiveTransformEngineClass = core::RegisterObject("Project the position of 3d points onto a plane according to a projection matrix")
#ifdef SOFA_FLOAT
.add< ProjectiveTransformEngine<defaulttype::Vec3fTypes> >(true) // default template
#else
.add< ProjectiveTransformEngine<defaulttype::Vec3dTypes> >(true) // default template
#endif
#ifndef SOFA_DOUBLE
.add< ProjectiveTransformEngine<defaulttype::Vec3fTypes> >()
#endif
.add< ProjectiveTransformEngine<defaulttype::ExtVec3fTypes> >()
;
#ifndef SOFA_FLOAT
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::Vec3dTypes>;
#endif //SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::Vec3fTypes>;
#endif //SOFA_DOUBLE
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::ExtVec3fTypes>;
} // namespace constraint
} // namespace component
} // namespace sofa
<commit_msg>fix default template when compiled with USE_FLOAT<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#define SOFA_COMPONENT_ENGINE_PROJECTIVETRANSFORMENGINE_CPP
#include <SofaMiscEngine/ProjectiveTransformEngine.inl>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace engine
{
SOFA_DECL_CLASS(ProjectiveTransformEngine)
int ProjectiveTransformEngineClass = core::RegisterObject("Project the position of 3d points onto a plane according to a projection matrix")
#ifdef SOFA_FLOAT
.add< ProjectiveTransformEngine<defaulttype::Vec3fTypes> >(true) // default template
#else
.add< ProjectiveTransformEngine<defaulttype::Vec3dTypes> >(true) // default template
#ifndef SOFA_DOUBLE
.add< ProjectiveTransformEngine<defaulttype::Vec3fTypes> >()
#endif
#endif
.add< ProjectiveTransformEngine<defaulttype::ExtVec3fTypes> >()
;
#ifndef SOFA_FLOAT
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::Vec3dTypes>;
#endif //SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::Vec3fTypes>;
#endif //SOFA_DOUBLE
template class SOFA_MISC_ENGINE_API ProjectiveTransformEngine<defaulttype::ExtVec3fTypes>;
} // namespace constraint
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "dictionary.h"
// appleseed.foundation headers.
#include "foundation/utility/foreach.h"
// Standard headers.
#include <cassert>
#include <map>
#include <string>
namespace foundation
{
typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, Dictionary> DictionaryMap;
//
// StringDictionary::const_iterator class implementation.
//
struct StringDictionary::const_iterator::Impl
{
StringMap::const_iterator m_it;
};
StringDictionary::const_iterator::const_iterator()
: impl(new Impl())
{
}
StringDictionary::const_iterator::const_iterator(const const_iterator& rhs)
: impl(new Impl(*rhs.impl))
{
}
StringDictionary::const_iterator::~const_iterator()
{
delete impl;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator=(const const_iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool StringDictionary::const_iterator::operator==(const const_iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool StringDictionary::const_iterator::operator!=(const const_iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator++()
{
++impl->m_it;
return *this;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator--()
{
--impl->m_it;
return *this;
}
const StringDictionary::const_iterator::value_type& StringDictionary::const_iterator::operator*() const
{
return *this;
}
const char* StringDictionary::const_iterator::key() const
{
return impl->m_it->first.c_str();
}
const char* StringDictionary::const_iterator::value() const
{
return impl->m_it->second.c_str();
}
//
// StringDictionary class implementation.
//
struct StringDictionary::Impl
{
StringMap m_strings;
};
StringDictionary::StringDictionary()
: impl(new Impl())
{
}
StringDictionary::StringDictionary(const StringDictionary& rhs)
: impl(new Impl(*rhs.impl))
{
}
StringDictionary::~StringDictionary()
{
delete impl;
}
StringDictionary& StringDictionary::operator=(const StringDictionary& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool StringDictionary::operator==(const StringDictionary& rhs) const
{
if (size() != rhs.size())
return false;
for (
StringMap::const_iterator it = impl->m_strings.begin(), rhs_it = rhs.impl->m_strings.begin();
it != impl->m_strings.end();
++it, ++rhs_it)
{
if (it->first != rhs_it->first || it->second != rhs_it->second)
return false;
}
return true;
}
bool StringDictionary::operator!=(const StringDictionary& rhs) const
{
return !(*this == rhs);
}
size_t StringDictionary::size() const
{
return impl->m_strings.size();
}
bool StringDictionary::empty() const
{
return impl->m_strings.empty();
}
void StringDictionary::clear()
{
impl->m_strings.clear();
}
StringDictionary& StringDictionary::insert(const char* key, const char* value)
{
assert(key);
assert(value);
impl->m_strings[key] = value;
return *this;
}
StringDictionary& StringDictionary::set(const char* key, const char* value)
{
assert(key);
assert(value);
const StringMap::iterator i = impl->m_strings.find(key);
if (i == impl->m_strings.end())
throw ExceptionDictionaryKeyNotFound(key);
i->second = value;
return *this;
}
const char* StringDictionary::get(const char* key) const
{
assert(key);
const StringMap::const_iterator i = impl->m_strings.find(key);
if (i == impl->m_strings.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second.c_str();
}
bool StringDictionary::exist(const char* key) const
{
assert(key);
return impl->m_strings.find(key) != impl->m_strings.end();
}
StringDictionary& StringDictionary::remove(const char* key)
{
assert(key);
const StringMap::iterator i = impl->m_strings.find(key);
if (i != impl->m_strings.end())
impl->m_strings.erase(i);
return *this;
}
StringDictionary::const_iterator StringDictionary::begin() const
{
const_iterator it;
it.impl->m_it = impl->m_strings.begin();
return it;
}
StringDictionary::const_iterator StringDictionary::end() const
{
const_iterator it;
it.impl->m_it = impl->m_strings.end();
return it;
}
//
// DictionaryDictionary::iterator class implementation.
//
struct DictionaryDictionary::iterator::Impl
{
DictionaryMap::iterator m_it;
};
DictionaryDictionary::iterator::iterator()
: impl(new Impl())
{
}
DictionaryDictionary::iterator::iterator(const iterator& rhs)
: impl(new Impl(*rhs.impl))
{
}
DictionaryDictionary::iterator::~iterator()
{
delete impl;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator=(const iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::iterator::operator==(const iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool DictionaryDictionary::iterator::operator!=(const iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator++()
{
++impl->m_it;
return *this;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator--()
{
--impl->m_it;
return *this;
}
DictionaryDictionary::iterator::value_type& DictionaryDictionary::iterator::operator*()
{
return *this;
}
const char* DictionaryDictionary::iterator::key() const
{
return impl->m_it->first.c_str();
}
Dictionary& DictionaryDictionary::iterator::value()
{
return impl->m_it->second;
}
//
// DictionaryDictionary::const_iterator class implementation.
//
struct DictionaryDictionary::const_iterator::Impl
{
DictionaryMap::const_iterator m_it;
};
DictionaryDictionary::const_iterator::const_iterator()
: impl(new Impl())
{
}
DictionaryDictionary::const_iterator::const_iterator(const const_iterator& rhs)
: impl(new Impl())
{
impl->m_it = rhs.impl->m_it;
}
DictionaryDictionary::const_iterator::const_iterator(const iterator& rhs)
: impl(new Impl())
{
impl->m_it = rhs.impl->m_it;
}
DictionaryDictionary::const_iterator::~const_iterator()
{
delete impl;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator=(const const_iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::const_iterator::operator==(const const_iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool DictionaryDictionary::const_iterator::operator!=(const const_iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator++()
{
++impl->m_it;
return *this;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator--()
{
--impl->m_it;
return *this;
}
const DictionaryDictionary::const_iterator::value_type& DictionaryDictionary::const_iterator::operator*() const
{
return *this;
}
const char* DictionaryDictionary::const_iterator::key() const
{
return impl->m_it->first.c_str();
}
const Dictionary& DictionaryDictionary::const_iterator::value() const
{
return impl->m_it->second;
}
//
// DictionaryDictionary class implementation.
//
struct DictionaryDictionary::Impl
{
DictionaryMap m_dictionaries;
};
DictionaryDictionary::DictionaryDictionary()
: impl(new Impl())
{
}
DictionaryDictionary::DictionaryDictionary(const DictionaryDictionary& rhs)
: impl(new Impl(*rhs.impl))
{
}
DictionaryDictionary::~DictionaryDictionary()
{
delete impl;
}
DictionaryDictionary& DictionaryDictionary::operator=(const DictionaryDictionary& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::operator==(const DictionaryDictionary& rhs) const
{
if (size() != rhs.size())
return false;
for (
DictionaryMap::const_iterator it = impl->m_dictionaries.begin(), rhs_it = rhs.impl->m_dictionaries.begin();
it != impl->m_dictionaries.end();
++it, ++rhs_it)
{
if (it->first != rhs_it->first || it->second != rhs_it->second)
return false;
}
return true;
}
bool DictionaryDictionary::operator!=(const DictionaryDictionary& rhs) const
{
return !(*this == rhs);
}
size_t DictionaryDictionary::size() const
{
return impl->m_dictionaries.size();
}
bool DictionaryDictionary::empty() const
{
return impl->m_dictionaries.empty();
}
void DictionaryDictionary::clear()
{
impl->m_dictionaries.clear();
}
DictionaryDictionary& DictionaryDictionary::insert(const char* key, const Dictionary& value)
{
assert(key);
impl->m_dictionaries[key] = value;
return *this;
}
DictionaryDictionary& DictionaryDictionary::set(const char* key, const Dictionary& value)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(key);
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
i->second = value;
return *this;
}
Dictionary& DictionaryDictionary::get(const char* key)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(key);
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second;
}
const Dictionary& DictionaryDictionary::get(const char* key) const
{
assert(key);
const DictionaryMap::const_iterator i = impl->m_dictionaries.find(key);
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second;
}
bool DictionaryDictionary::exist(const char* key) const
{
assert(key);
return impl->m_dictionaries.find(key) != impl->m_dictionaries.end();
}
DictionaryDictionary& DictionaryDictionary::remove(const char* key)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(key);
if (i != impl->m_dictionaries.end())
impl->m_dictionaries.erase(i);
return *this;
}
DictionaryDictionary::iterator DictionaryDictionary::begin()
{
iterator it;
it.impl->m_it = impl->m_dictionaries.begin();
return it;
}
DictionaryDictionary::iterator DictionaryDictionary::end()
{
iterator it;
it.impl->m_it = impl->m_dictionaries.end();
return it;
}
DictionaryDictionary::const_iterator DictionaryDictionary::begin() const
{
const_iterator it;
it.impl->m_it = impl->m_dictionaries.begin();
return it;
}
DictionaryDictionary::const_iterator DictionaryDictionary::end() const
{
const_iterator it;
it.impl->m_it = impl->m_dictionaries.end();
return it;
}
//
// Dictionary class implementation.
//
Dictionary& Dictionary::merge(const Dictionary& rhs)
{
// Merge strings.
for (const_each<StringDictionary> i = rhs.strings(); i; ++i)
insert(i->key(), i->value());
// Recursively merge dictionaries.
for (const_each<DictionaryDictionary> i = rhs.dictionaries(); i; ++i)
{
if (dictionaries().exist(i->key()))
dictionary(i->key()).merge(i->value());
else insert(i->key(), i->value());
}
return *this;
}
} // namespace foundation
<commit_msg>Use interned strings as dictionary keys.<commit_after>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "dictionary.h"
// appleseed.foundation headers.
#include "foundation/utility/foreach.h"
// Standard headers.
#include <cassert>
#include <map>
#include <string>
namespace foundation
{
typedef std::map<InternedString, std::string> StringMap;
typedef std::map<InternedString, Dictionary> DictionaryMap;
//
// StringDictionary::const_iterator class implementation.
//
struct StringDictionary::const_iterator::Impl
{
StringMap::const_iterator m_it;
};
StringDictionary::const_iterator::const_iterator()
: impl(new Impl())
{
}
StringDictionary::const_iterator::const_iterator(const const_iterator& rhs)
: impl(new Impl(*rhs.impl))
{
}
StringDictionary::const_iterator::~const_iterator()
{
delete impl;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator=(const const_iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool StringDictionary::const_iterator::operator==(const const_iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool StringDictionary::const_iterator::operator!=(const const_iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator++()
{
++impl->m_it;
return *this;
}
StringDictionary::const_iterator& StringDictionary::const_iterator::operator--()
{
--impl->m_it;
return *this;
}
const StringDictionary::const_iterator::value_type& StringDictionary::const_iterator::operator*() const
{
return *this;
}
const char* StringDictionary::const_iterator::key() const
{
return impl->m_it->first.c_str();
}
const char* StringDictionary::const_iterator::value() const
{
return impl->m_it->second.c_str();
}
//
// StringDictionary class implementation.
//
struct StringDictionary::Impl
{
StringMap m_strings;
};
StringDictionary::StringDictionary()
: impl(new Impl())
{
}
StringDictionary::StringDictionary(const StringDictionary& rhs)
: impl(new Impl(*rhs.impl))
{
}
StringDictionary::~StringDictionary()
{
delete impl;
}
StringDictionary& StringDictionary::operator=(const StringDictionary& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool StringDictionary::operator==(const StringDictionary& rhs) const
{
if (size() != rhs.size())
return false;
for (
StringMap::const_iterator it = impl->m_strings.begin(), rhs_it = rhs.impl->m_strings.begin();
it != impl->m_strings.end();
++it, ++rhs_it)
{
if (it->first != rhs_it->first || it->second != rhs_it->second)
return false;
}
return true;
}
bool StringDictionary::operator!=(const StringDictionary& rhs) const
{
return !(*this == rhs);
}
size_t StringDictionary::size() const
{
return impl->m_strings.size();
}
bool StringDictionary::empty() const
{
return impl->m_strings.empty();
}
void StringDictionary::clear()
{
impl->m_strings.clear();
}
StringDictionary& StringDictionary::insert(const char* key, const char* value)
{
assert(key);
assert(value);
impl->m_strings[InternedString(key)] = value;
return *this;
}
StringDictionary& StringDictionary::set(const char* key, const char* value)
{
assert(key);
assert(value);
const StringMap::iterator i = impl->m_strings.find(InternedString(key));
if (i == impl->m_strings.end())
throw ExceptionDictionaryKeyNotFound(key);
i->second = value;
return *this;
}
const char* StringDictionary::get(const char* key) const
{
assert(key);
const StringMap::const_iterator i = impl->m_strings.find(InternedString(key));
if (i == impl->m_strings.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second.c_str();
}
bool StringDictionary::exist(const char* key) const
{
assert(key);
return impl->m_strings.find(InternedString(key)) != impl->m_strings.end();
}
StringDictionary& StringDictionary::remove(const char* key)
{
assert(key);
const StringMap::iterator i = impl->m_strings.find(InternedString(key));
if (i != impl->m_strings.end())
impl->m_strings.erase(i);
return *this;
}
StringDictionary::const_iterator StringDictionary::begin() const
{
const_iterator it;
it.impl->m_it = impl->m_strings.begin();
return it;
}
StringDictionary::const_iterator StringDictionary::end() const
{
const_iterator it;
it.impl->m_it = impl->m_strings.end();
return it;
}
//
// DictionaryDictionary::iterator class implementation.
//
struct DictionaryDictionary::iterator::Impl
{
DictionaryMap::iterator m_it;
};
DictionaryDictionary::iterator::iterator()
: impl(new Impl())
{
}
DictionaryDictionary::iterator::iterator(const iterator& rhs)
: impl(new Impl(*rhs.impl))
{
}
DictionaryDictionary::iterator::~iterator()
{
delete impl;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator=(const iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::iterator::operator==(const iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool DictionaryDictionary::iterator::operator!=(const iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator++()
{
++impl->m_it;
return *this;
}
DictionaryDictionary::iterator& DictionaryDictionary::iterator::operator--()
{
--impl->m_it;
return *this;
}
DictionaryDictionary::iterator::value_type& DictionaryDictionary::iterator::operator*()
{
return *this;
}
const char* DictionaryDictionary::iterator::key() const
{
return impl->m_it->first.c_str();
}
Dictionary& DictionaryDictionary::iterator::value()
{
return impl->m_it->second;
}
//
// DictionaryDictionary::const_iterator class implementation.
//
struct DictionaryDictionary::const_iterator::Impl
{
DictionaryMap::const_iterator m_it;
};
DictionaryDictionary::const_iterator::const_iterator()
: impl(new Impl())
{
}
DictionaryDictionary::const_iterator::const_iterator(const const_iterator& rhs)
: impl(new Impl())
{
impl->m_it = rhs.impl->m_it;
}
DictionaryDictionary::const_iterator::const_iterator(const iterator& rhs)
: impl(new Impl())
{
impl->m_it = rhs.impl->m_it;
}
DictionaryDictionary::const_iterator::~const_iterator()
{
delete impl;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator=(const const_iterator& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::const_iterator::operator==(const const_iterator& rhs) const
{
return impl->m_it == rhs.impl->m_it;
}
bool DictionaryDictionary::const_iterator::operator!=(const const_iterator& rhs) const
{
return impl->m_it != rhs.impl->m_it;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator++()
{
++impl->m_it;
return *this;
}
DictionaryDictionary::const_iterator& DictionaryDictionary::const_iterator::operator--()
{
--impl->m_it;
return *this;
}
const DictionaryDictionary::const_iterator::value_type& DictionaryDictionary::const_iterator::operator*() const
{
return *this;
}
const char* DictionaryDictionary::const_iterator::key() const
{
return impl->m_it->first.c_str();
}
const Dictionary& DictionaryDictionary::const_iterator::value() const
{
return impl->m_it->second;
}
//
// DictionaryDictionary class implementation.
//
struct DictionaryDictionary::Impl
{
DictionaryMap m_dictionaries;
};
DictionaryDictionary::DictionaryDictionary()
: impl(new Impl())
{
}
DictionaryDictionary::DictionaryDictionary(const DictionaryDictionary& rhs)
: impl(new Impl(*rhs.impl))
{
}
DictionaryDictionary::~DictionaryDictionary()
{
delete impl;
}
DictionaryDictionary& DictionaryDictionary::operator=(const DictionaryDictionary& rhs)
{
*impl = *rhs.impl;
return *this;
}
bool DictionaryDictionary::operator==(const DictionaryDictionary& rhs) const
{
if (size() != rhs.size())
return false;
for (
DictionaryMap::const_iterator it = impl->m_dictionaries.begin(), rhs_it = rhs.impl->m_dictionaries.begin();
it != impl->m_dictionaries.end();
++it, ++rhs_it)
{
if (it->first != rhs_it->first || it->second != rhs_it->second)
return false;
}
return true;
}
bool DictionaryDictionary::operator!=(const DictionaryDictionary& rhs) const
{
return !(*this == rhs);
}
size_t DictionaryDictionary::size() const
{
return impl->m_dictionaries.size();
}
bool DictionaryDictionary::empty() const
{
return impl->m_dictionaries.empty();
}
void DictionaryDictionary::clear()
{
impl->m_dictionaries.clear();
}
DictionaryDictionary& DictionaryDictionary::insert(const char* key, const Dictionary& value)
{
assert(key);
impl->m_dictionaries[InternedString(key)] = value;
return *this;
}
DictionaryDictionary& DictionaryDictionary::set(const char* key, const Dictionary& value)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(InternedString(key));
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
i->second = value;
return *this;
}
Dictionary& DictionaryDictionary::get(const char* key)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(InternedString(key));
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second;
}
const Dictionary& DictionaryDictionary::get(const char* key) const
{
assert(key);
const DictionaryMap::const_iterator i = impl->m_dictionaries.find(InternedString(key));
if (i == impl->m_dictionaries.end())
throw ExceptionDictionaryKeyNotFound(key);
return i->second;
}
bool DictionaryDictionary::exist(const char* key) const
{
assert(key);
return impl->m_dictionaries.find(InternedString(key)) != impl->m_dictionaries.end();
}
DictionaryDictionary& DictionaryDictionary::remove(const char* key)
{
assert(key);
const DictionaryMap::iterator i = impl->m_dictionaries.find(InternedString(key));
if (i != impl->m_dictionaries.end())
impl->m_dictionaries.erase(i);
return *this;
}
DictionaryDictionary::iterator DictionaryDictionary::begin()
{
iterator it;
it.impl->m_it = impl->m_dictionaries.begin();
return it;
}
DictionaryDictionary::iterator DictionaryDictionary::end()
{
iterator it;
it.impl->m_it = impl->m_dictionaries.end();
return it;
}
DictionaryDictionary::const_iterator DictionaryDictionary::begin() const
{
const_iterator it;
it.impl->m_it = impl->m_dictionaries.begin();
return it;
}
DictionaryDictionary::const_iterator DictionaryDictionary::end() const
{
const_iterator it;
it.impl->m_it = impl->m_dictionaries.end();
return it;
}
//
// Dictionary class implementation.
//
Dictionary& Dictionary::merge(const Dictionary& rhs)
{
// Merge strings.
for (const_each<StringDictionary> i = rhs.strings(); i; ++i)
insert(i->key(), i->value());
// Recursively merge dictionaries.
for (const_each<DictionaryDictionary> i = rhs.dictionaries(); i; ++i)
{
if (dictionaries().exist(i->key()))
dictionary(i->key()).merge(i->value());
else insert(i->key(), i->value());
}
return *this;
}
} // namespace foundation
<|endoftext|> |
<commit_before>#include "CGUITitleLabelsWidget.h"
#include "CProgramContext.h"
#include "SciDataManager.h"
#include "CMainMenuState.h"
#include <iomanip>
CGUITitleLabelsWidget::CGUITitleLabelsWidget(SciDataManager * DataManager)
{
static Range ValueRange = DataManager->GridValues.getValueRange("Avg Oxy", 5.0);
std::wstringstream s;
s << std::fixed;
s << "Range (";
s << std::setprecision(3);
s << ValueRange.first;
s << " - ";
s << ValueRange.second;
s << ")";
// Top Label
Gwen::Controls::Label * BigLabel = new Gwen::Controls::Label(GUIManager->getCanvas());
BigLabel->SetFont(GUIManager->getLargeFont());
BigLabel->SetText(Gwen::UnicodeString(L"Dataset: ") + Gwen::UnicodeString(CMainMenuState::get().DataSetName.begin(), CMainMenuState::get().DataSetName.end()));
BigLabel->SetBounds(10, 10, 1590, 300);
BigLabel->SetTextColor(Gwen::Color(235, 255, 235, 215));
// Second Label
Gwen::Controls::Label * MediumLabel = new Gwen::Controls::Label(GUIManager->getCanvas());
MediumLabel->SetFont(GUIManager->getMediumFont());
MediumLabel->SetText(Gwen::UnicodeString(L"Current Field: Avg Oxy - ") + Gwen::UnicodeString(s.str()));
MediumLabel->SetBounds(20, 70, 600, 300);
MediumLabel->SetTextColor(Gwen::Color(235, 235, 255, 215));
// Volume Range Label
VolumeRangeIndicator = new Gwen::Controls::Label(GUIManager->getCanvas());
VolumeRangeIndicator->SetFont(GUIManager->getMediumFont());
VolumeRangeIndicator->SetBounds(20, 110, 900, 300);
VolumeRangeIndicator->SetTextColor(Gwen::Color(255, 235, 235, 215));
// Volume Range Label
VolumeCalculationIndicator = new Gwen::Controls::Label(GUIManager->getCanvas());
VolumeCalculationIndicator->SetFont(GUIManager->getMediumFont());
VolumeCalculationIndicator->SetBounds(20, 150, 900, 300);
VolumeCalculationIndicator->SetTextColor(Gwen::Color(255, 235, 235, 215));
}
void CGUITitleLabelsWidget::resetVolumeRangeIndicator(SciDataManager * DataManager)
{
static Range ValueRange = DataManager->GridValues.getValueRange("Avg Oxy", 5.0);
{
std::wstringstream s;
s << std::fixed;
s << "Value Range: ";
s << std::setprecision(3);
s << (CProgramContext::get().Scene.VolumeSceneObject->Control.EmphasisLocation * (ValueRange.second - ValueRange.first) + ValueRange.first);
s << " ";
s << std::setprecision(4);
s << (CProgramContext::get().Scene.VolumeSceneObject->Control.LocalRange / 2.f * (ValueRange.second - ValueRange.first));
VolumeRangeIndicator->SetText(s.str());
}
{
std::wstringstream s;
s << "Volume: ";
s << std::setprecision(3);
s << std::scientific;
s << DataManager->getGridVolume("\"Avg Oxy\"", CProgramContext::get().Scene.VolumeSceneObject->Control.EmphasisLocation * (ValueRange.second - ValueRange.first) + ValueRange.first,
CProgramContext::get().Scene.VolumeSceneObject->Control.LocalRange / 2.f * (ValueRange.second - ValueRange.first), 2) * 20.0 * 20.0;
s << " m^3";
VolumeCalculationIndicator->SetText(s.str());
}
}
void CGUITitleLabelsWidget::clearVolumeRangeIndicator()
{
VolumeRangeIndicator->SetText(L"");
}
<commit_msg>+ Fixed title widget<commit_after>#include "CGUITitleLabelsWidget.h"
#include "CProgramContext.h"
#include "SciDataManager.h"
#include "CMainMenuState.h"
#include <iomanip>
CGUITitleLabelsWidget::CGUITitleLabelsWidget(SciDataManager * DataManager)
{
static Range ValueRange = DataManager->RawValues.getValueRange("Avg Oxy", 5.0);
std::wstringstream s;
s << std::fixed;
s << "Range (";
s << std::setprecision(3);
s << ValueRange.first;
s << ", ";
s << ValueRange.second;
s << ")";
// Top Label
Gwen::Controls::Label * BigLabel = new Gwen::Controls::Label(GUIManager->getCanvas());
BigLabel->SetFont(GUIManager->getLargeFont());
BigLabel->SetText(Gwen::UnicodeString(L"Dataset: ") + Gwen::UnicodeString(CMainMenuState::get().DataSetName.begin(), CMainMenuState::get().DataSetName.end()));
BigLabel->SetBounds(10, 10, 1590, 300);
BigLabel->SetTextColor(Gwen::Color(235, 255, 235, 215));
// Second Label
Gwen::Controls::Label * MediumLabel = new Gwen::Controls::Label(GUIManager->getCanvas());
MediumLabel->SetFont(GUIManager->getMediumFont());
MediumLabel->SetText(Gwen::UnicodeString(L"Current Field: Avg Oxy - ") + Gwen::UnicodeString(s.str()));
MediumLabel->SetBounds(20, 70, 1000, 300);
MediumLabel->SetTextColor(Gwen::Color(235, 235, 255, 215));
// Volume Range Label
VolumeRangeIndicator = new Gwen::Controls::Label(GUIManager->getCanvas());
VolumeRangeIndicator->SetFont(GUIManager->getMediumFont());
VolumeRangeIndicator->SetBounds(20, 110, 1000, 300);
VolumeRangeIndicator->SetTextColor(Gwen::Color(255, 235, 235, 215));
// Volume Range Label
VolumeCalculationIndicator = new Gwen::Controls::Label(GUIManager->getCanvas());
VolumeCalculationIndicator->SetFont(GUIManager->getMediumFont());
VolumeCalculationIndicator->SetBounds(20, 150, 1000, 300);
VolumeCalculationIndicator->SetTextColor(Gwen::Color(255, 235, 235, 215));
}
void CGUITitleLabelsWidget::resetVolumeRangeIndicator(SciDataManager * DataManager)
{
static Range ValueRange = DataManager->RawValues.getValueRange("Avg Oxy", 5.0);
{
std::wstringstream s;
s << std::fixed;
s << "Value Range: ";
s << std::setprecision(3);
s << (CProgramContext::get().Scene.VolumeSceneObject->Control.EmphasisLocation * (ValueRange.second - ValueRange.first) + ValueRange.first);
s << " ";
s << std::setprecision(4);
s << (CProgramContext::get().Scene.VolumeSceneObject->Control.LocalRange / 2.f * (ValueRange.second - ValueRange.first));
VolumeRangeIndicator->SetText(s.str());
}
{
static Range ValueRange = DataManager->GridValues.getValueRange("Avg Oxy", 5.0);
static Range XValueRange = DataManager->RawValues.getValueRange("x", 5.0);
static Range YValueRange = DataManager->RawValues.getValueRange("DFS Depth (m)", 5.0);
YValueRange.first = 0.0;
static Range ZValueRange = DataManager->RawValues.getValueRange("y", 5.0);
double EntireVolume = 1.0;
EntireVolume *= XValueRange.second - XValueRange.first;
EntireVolume *= YValueRange.second - YValueRange.first;
EntireVolume *= ZValueRange.second - ZValueRange.first;
double UnitVolume = EntireVolume / 24.0 / 24.0 / 24.0;
//printf("Entire Volume: %f UnitVolume %f\n", EntireVolume, UnitVolume);
std::wstringstream s;
s << "Volume: ";
s << std::setprecision(3);
s << std::scientific;
s << DataManager->getGridVolume("Avg Oxy", CProgramContext::get().Scene.VolumeSceneObject->Control.EmphasisLocation * (ValueRange.second - ValueRange.first) + ValueRange.first,
CProgramContext::get().Scene.VolumeSceneObject->Control.LocalRange / 2.f * (ValueRange.second - ValueRange.first), 2) * UnitVolume;
s << " m^3";
VolumeCalculationIndicator->SetText(s.str());
}
}
void CGUITitleLabelsWidget::clearVolumeRangeIndicator()
{
VolumeRangeIndicator->SetText(L"");
VolumeCalculationIndicator->SetText(L"");
}
<|endoftext|> |
<commit_before>//@author A0114171W
#include "stdafx.h"
#include "operation.h"
#include "operations/post_operation.h"
#include "operations/put_operation.h"
#include "operations/erase_operation.h"
#include "operations/branch_operation.h"
#include "internal_transaction.h"
#include "../exception.h"
#include "internal_datastore.h"
namespace You {
namespace DataStore {
namespace Internal {
const std::string DataStore::FILE_PATH = std::string("data.xml");
const std::wstring DataStore::ROOT_NODE_NAME = std::wstring(L"You");
DataStore& DataStore::get() {
static DataStore store;
return store;
}
You::DataStore::Transaction DataStore::begin() {
You::DataStore::Transaction result;
transactionStack.push(std::weak_ptr<Internal::Transaction>(result));
return result;
}
void DataStore::onTransactionCommit(Transaction& transaction) {
// Only transaction on top of the stack may be committed
assert(*transactionStack.top().lock() == transaction);
auto self = transactionStack.top();
if (transactionStack.size() == 1) {
// it is the only active transaction, execute the operations and save
pugi::xml_document temp;
temp.reset(document);
executeTransaction(transaction, temp);
document.reset(temp);
saveData();
transactionStack.pop();
} else {
// There is a transaction before it that is yet to be committed.
// Merge with that transaction
transactionStack.pop();
auto below = transactionStack.top().lock();
below->mergeOperationsQueue(transaction.operationsQueue);
below->mergeOperationsQueue(transaction.mergedOperationsQueue);
}
}
void DataStore::onTransactionRollback(Transaction& transaction) {
// Can only rollback the latest transaction
assert(*(transactionStack.top().lock()) == transaction);
transactionStack.pop();
}
void DataStore::post(std::wstring branch, std::wstring id,
const KeyValuePairs& kvp) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::PostOperation>(branch, id, kvp);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
void DataStore::put(std::wstring branch, std::wstring id,
const KeyValuePairs& kvp) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::PutOperation>(branch, id, kvp);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
void DataStore::erase(std::wstring branch, std::wstring id) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::EraseOperation>(branch, id);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
std::vector<KeyValuePairs> DataStore::getAll(std::wstring nodeName) {
loadData();
pugi::xml_node dataNode = BranchOperation::get(root, nodeName);
std::vector<KeyValuePairs> allData;
for (auto i = dataNode.begin(); i != dataNode.end(); ++i) {
allData.push_back(SerializationOperation::deserialize(*i));
}
return allData;
}
void DataStore::wipeData() {
document.reset();
std::remove(FILE_PATH.c_str());
}
bool DataStore::saveData() {
bool status = document.save_file(FILE_PATH.c_str());
return status;
}
void DataStore::loadData() {
bool isInitialized = !document.first_child().empty();
if (!isInitialized) {
pugi::xml_parse_result loadStatus = document.load_file(FILE_PATH.c_str());
bool loadSuccessful = loadStatus;
bool isFirstLoad =
loadStatus.status == pugi::xml_parse_status::status_file_not_found;
if (!loadSuccessful && !isFirstLoad) {
// TODO(digawp): find a way to inform user where in the xml
// the error is located.
// Possible solution: log
onXmlParseResult(loadStatus);
} else {
root = BranchOperation::get(document, ROOT_NODE_NAME.c_str());
}
}
}
void DataStore::executeTransaction(Transaction& transaction,
pugi::xml_node& node) {
for (auto operation = transaction.operationsQueue.begin();
operation != transaction.operationsQueue.end();
++operation) {
bool status = operation->run(node);
if (!status) {
transaction.rollback();
assert(false);
}
}
for (auto mergedOperation = transaction.mergedOperationsQueue.begin();
mergedOperation != transaction.mergedOperationsQueue.end();
++mergedOperation) {
bool status = mergedOperation->run(node);
if (!status) {
transaction.rollback();
assert(false);
}
}
}
void DataStore::onXmlParseResult(const pugi::xml_parse_result& result) {
bool isIoError =
result.status == pugi::xml_parse_status::status_io_error ||
result.status == pugi::xml_parse_status::status_out_of_memory ||
result.status == pugi::xml_parse_status::status_internal_error;
if (isIoError) {
throw IOException();
} else {
throw NotWellFormedXmlException();
}
}
} // namespace Internal
} // namespace DataStore
} // namespace You
<commit_msg>executeTransaction on temporary root, update root after commit<commit_after>//@author A0114171W
#include "stdafx.h"
#include "operation.h"
#include "operations/post_operation.h"
#include "operations/put_operation.h"
#include "operations/erase_operation.h"
#include "operations/branch_operation.h"
#include "internal_transaction.h"
#include "../exception.h"
#include "internal_datastore.h"
namespace You {
namespace DataStore {
namespace Internal {
const std::string DataStore::FILE_PATH = std::string("data.xml");
const std::wstring DataStore::ROOT_NODE_NAME = std::wstring(L"You");
DataStore& DataStore::get() {
static DataStore store;
return store;
}
You::DataStore::Transaction DataStore::begin() {
You::DataStore::Transaction result;
transactionStack.push(std::weak_ptr<Internal::Transaction>(result));
return result;
}
void DataStore::onTransactionCommit(Transaction& transaction) {
// Only transaction on top of the stack may be committed
assert(*transactionStack.top().lock() == transaction);
auto self = transactionStack.top();
if (transactionStack.size() == 1) {
// it is the only active transaction, execute the operations and save
pugi::xml_document temp;
temp.reset(document);
pugi::xml_node tempRoot = BranchOperation::get(temp, ROOT_NODE_NAME.c_str());
executeTransaction(transaction, tempRoot);
document.reset(temp);
root = BranchOperation::get(document, ROOT_NODE_NAME.c_str());
saveData();
transactionStack.pop();
} else {
// There is a transaction before it that is yet to be committed.
// Merge with that transaction
transactionStack.pop();
auto below = transactionStack.top().lock();
below->mergeOperationsQueue(transaction.operationsQueue);
below->mergeOperationsQueue(transaction.mergedOperationsQueue);
}
}
void DataStore::onTransactionRollback(Transaction& transaction) {
// Can only rollback the latest transaction
assert(*(transactionStack.top().lock()) == transaction);
transactionStack.pop();
}
void DataStore::post(std::wstring branch, std::wstring id,
const KeyValuePairs& kvp) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::PostOperation>(branch, id, kvp);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
void DataStore::put(std::wstring branch, std::wstring id,
const KeyValuePairs& kvp) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::PutOperation>(branch, id, kvp);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
void DataStore::erase(std::wstring branch, std::wstring id) {
assert(!transactionStack.empty());
std::unique_ptr<Internal::Operation> operation =
std::make_unique<Internal::EraseOperation>(branch, id);
auto transaction = transactionStack.top().lock();
assert(transaction); // Checks if the pointer is valid
transaction->push(std::move(operation));
}
std::vector<KeyValuePairs> DataStore::getAll(std::wstring nodeName) {
loadData();
pugi::xml_node dataNode = BranchOperation::get(root, nodeName);
std::vector<KeyValuePairs> allData;
for (auto i = dataNode.begin(); i != dataNode.end(); ++i) {
allData.push_back(SerializationOperation::deserialize(*i));
}
return allData;
}
void DataStore::wipeData() {
document.reset();
std::remove(FILE_PATH.c_str());
}
bool DataStore::saveData() {
bool status = document.save_file(FILE_PATH.c_str());
return status;
}
void DataStore::loadData() {
bool isInitialized = !document.first_child().empty();
if (!isInitialized) {
pugi::xml_parse_result loadStatus = document.load_file(FILE_PATH.c_str());
bool loadSuccessful = loadStatus;
bool isFirstLoad =
loadStatus.status == pugi::xml_parse_status::status_file_not_found;
if (!loadSuccessful && !isFirstLoad) {
// TODO(digawp): find a way to inform user where in the xml
// the error is located.
// Possible solution: log
onXmlParseResult(loadStatus);
} else {
root = BranchOperation::get(document, ROOT_NODE_NAME.c_str());
}
}
}
void DataStore::executeTransaction(Transaction& transaction,
pugi::xml_node& node) {
for (auto operation = transaction.operationsQueue.begin();
operation != transaction.operationsQueue.end();
++operation) {
bool status = operation->run(node);
if (!status) {
transaction.rollback();
assert(false);
}
}
for (auto mergedOperation = transaction.mergedOperationsQueue.begin();
mergedOperation != transaction.mergedOperationsQueue.end();
++mergedOperation) {
bool status = mergedOperation->run(node);
if (!status) {
transaction.rollback();
assert(false);
}
}
}
void DataStore::onXmlParseResult(const pugi::xml_parse_result& result) {
bool isIoError =
result.status == pugi::xml_parse_status::status_io_error ||
result.status == pugi::xml_parse_status::status_out_of_memory ||
result.status == pugi::xml_parse_status::status_internal_error;
if (isIoError) {
throw IOException();
} else {
throw NotWellFormedXmlException();
}
}
} // namespace Internal
} // namespace DataStore
} // namespace You
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/any.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/assert.h>
namespace stingray
{
namespace Detail {
namespace any
{
void ObjectHolder<ISerializablePtr>::Serialize(ObjectOStream& ar) const
{ ar.Serialize("obj", Object); }
void ObjectHolder<ISerializablePtr>::Deserialize(ObjectIStream& ar)
{ ar.Deserialize("obj", Object); }
}}
void any::Copy(const any& other)
{
STINGRAYKIT_ASSERT(_type == Type::Empty);
switch (other._type)
{
case Type::Empty:
case Type::Bool:
case Type::Char:
case Type::UChar:
case Type::Short:
case Type::UShort:
case Type::Int:
case Type::UInt:
case Type::Long:
case Type::ULong:
case Type::LongLong:
case Type::ULongLong:
case Type::Float:
case Type::Double:
_data = other._data;
break;
case Type::String:
_data.String.Ctor(other._data.String.Ref());
break;
case Type::Object:
case Type::SerializableObject:
_data.Object = other._data.Object->Clone();
break;
default:
STINGRAYKIT_THROW(ArgumentException("type", other._type));
}
_type = other._type;
}
void any::Destroy()
{
switch (_type)
{
case Type::String:
_data.String.Dtor();
break;
case Type::Object:
case Type::SerializableObject:
delete _data.Object;
break;
default:
break;
}
_type = Type::Empty;
}
bool any::IsSerializable() const
{ return _type != Type::Object || _data.Object->IsSerializable(); }
#define STRING(NAME) case Type::NAME: return stingray::ToString(_data.NAME)
std::string any::ToString() const
{
switch (_type)
{
case Type::Empty: return "<empty>";
STRING(Bool);
STRING(Char);
STRING(UChar);
STRING(Short);
STRING(UShort);
STRING(Int);
STRING(UInt);
STRING(Long);
STRING(ULong);
STRING(LongLong);
STRING(ULongLong);
STRING(Float);
STRING(Double);
case Type::String:
return _data.String.Ref();
case Type::Object:
case Type::SerializableObject:
return _data.Object->ToString();
}
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type);
}
#undef STRING
#define SERIALIZE(NAME) case Type::NAME: ar.Serialize("val", _data.NAME); return
void any::Serialize(ObjectOStream& ar) const
{
ar.Serialize("type", _type);
switch (_type)
{
case Type::Empty: return;
SERIALIZE(Bool);
SERIALIZE(Char);
SERIALIZE(UChar);
SERIALIZE(Short);
SERIALIZE(UShort);
SERIALIZE(Int);
SERIALIZE(UInt);
SERIALIZE(Long);
SERIALIZE(ULong);
SERIALIZE(LongLong);
SERIALIZE(ULongLong);
SERIALIZE(Float);
SERIALIZE(Double);
case Type::String: ar.Serialize("val", _data.String.Ref()); return;
case Type::Object:
case Type::SerializableObject:
{
STINGRAYKIT_CHECK(_data.Object->IsSerializable(),
StringBuilder() % "'any' object (" % Demangle(typeid(*_data.Object).name()) % ") is not a serializable one!");
ar.Serialize(".class", _data.Object->GetClassName());
_data.Object->Serialize(ar);
}
return;
}
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type); //you could see warning about unhandled type if leave it here
}
#undef SERIALIZE
#define DESERIALIZE(NAME) case Type::NAME: ar.Deserialize("val", _data.NAME); break
void any::Deserialize(ObjectIStream& ar)
{
Destroy();
Type type = Type::Empty;
ar.Deserialize("type", type);
switch (type)
{
case Type::Empty: break;
DESERIALIZE(Bool);
DESERIALIZE(Char);
DESERIALIZE(UChar);
DESERIALIZE(Short);
DESERIALIZE(UShort);
DESERIALIZE(Int);
DESERIALIZE(UInt);
DESERIALIZE(Long);
DESERIALIZE(ULong);
DESERIALIZE(LongLong);
DESERIALIZE(ULongLong);
DESERIALIZE(Float);
DESERIALIZE(Double);
case Type::String:
{
std::string s;
ar.Deserialize("val", s);
Init(s);
}
break;
case Type::Object:
case Type::SerializableObject:
{
std::string classname;
ar.Deserialize(".class", classname);
_data.Object = Factory::Instance().Create<IObjectHolder>(classname);
_data.Object->Deserialize(ar);
}
break;
default:
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type);
}
_type = type;
}
#undef DESERIALIZE
}
<commit_msg>any: make is-serializable condition more proper<commit_after>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/any.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/assert.h>
namespace stingray
{
namespace Detail {
namespace any
{
void ObjectHolder<ISerializablePtr>::Serialize(ObjectOStream& ar) const
{ ar.Serialize("obj", Object); }
void ObjectHolder<ISerializablePtr>::Deserialize(ObjectIStream& ar)
{ ar.Deserialize("obj", Object); }
}}
void any::Copy(const any& other)
{
STINGRAYKIT_ASSERT(_type == Type::Empty);
switch (other._type)
{
case Type::Empty:
case Type::Bool:
case Type::Char:
case Type::UChar:
case Type::Short:
case Type::UShort:
case Type::Int:
case Type::UInt:
case Type::Long:
case Type::ULong:
case Type::LongLong:
case Type::ULongLong:
case Type::Float:
case Type::Double:
_data = other._data;
break;
case Type::String:
_data.String.Ctor(other._data.String.Ref());
break;
case Type::Object:
case Type::SerializableObject:
_data.Object = other._data.Object->Clone();
break;
default:
STINGRAYKIT_THROW(ArgumentException("type", other._type));
}
_type = other._type;
}
void any::Destroy()
{
switch (_type)
{
case Type::String:
_data.String.Dtor();
break;
case Type::Object:
case Type::SerializableObject:
delete _data.Object;
break;
default:
break;
}
_type = Type::Empty;
}
bool any::IsSerializable() const
{ return (_type != Type::Object && _type != Type::SerializableObject) || _data.Object->IsSerializable(); }
#define STRING(NAME) case Type::NAME: return stingray::ToString(_data.NAME)
std::string any::ToString() const
{
switch (_type)
{
case Type::Empty: return "<empty>";
STRING(Bool);
STRING(Char);
STRING(UChar);
STRING(Short);
STRING(UShort);
STRING(Int);
STRING(UInt);
STRING(Long);
STRING(ULong);
STRING(LongLong);
STRING(ULongLong);
STRING(Float);
STRING(Double);
case Type::String:
return _data.String.Ref();
case Type::Object:
case Type::SerializableObject:
return _data.Object->ToString();
}
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type);
}
#undef STRING
#define SERIALIZE(NAME) case Type::NAME: ar.Serialize("val", _data.NAME); return
void any::Serialize(ObjectOStream& ar) const
{
ar.Serialize("type", _type);
switch (_type)
{
case Type::Empty: return;
SERIALIZE(Bool);
SERIALIZE(Char);
SERIALIZE(UChar);
SERIALIZE(Short);
SERIALIZE(UShort);
SERIALIZE(Int);
SERIALIZE(UInt);
SERIALIZE(Long);
SERIALIZE(ULong);
SERIALIZE(LongLong);
SERIALIZE(ULongLong);
SERIALIZE(Float);
SERIALIZE(Double);
case Type::String: ar.Serialize("val", _data.String.Ref()); return;
case Type::Object:
case Type::SerializableObject:
{
STINGRAYKIT_CHECK(_data.Object->IsSerializable(),
StringBuilder() % "'any' object (" % Demangle(typeid(*_data.Object).name()) % ") is not a serializable one!");
ar.Serialize(".class", _data.Object->GetClassName());
_data.Object->Serialize(ar);
}
return;
}
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type); //you could see warning about unhandled type if leave it here
}
#undef SERIALIZE
#define DESERIALIZE(NAME) case Type::NAME: ar.Deserialize("val", _data.NAME); break
void any::Deserialize(ObjectIStream& ar)
{
Destroy();
Type type = Type::Empty;
ar.Deserialize("type", type);
switch (type)
{
case Type::Empty: break;
DESERIALIZE(Bool);
DESERIALIZE(Char);
DESERIALIZE(UChar);
DESERIALIZE(Short);
DESERIALIZE(UShort);
DESERIALIZE(Int);
DESERIALIZE(UInt);
DESERIALIZE(Long);
DESERIALIZE(ULong);
DESERIALIZE(LongLong);
DESERIALIZE(ULongLong);
DESERIALIZE(Float);
DESERIALIZE(Double);
case Type::String:
{
std::string s;
ar.Deserialize("val", s);
Init(s);
}
break;
case Type::Object:
case Type::SerializableObject:
{
std::string classname;
ar.Deserialize(".class", classname);
_data.Object = Factory::Instance().Create<IObjectHolder>(classname);
_data.Object->Deserialize(ar);
}
break;
default:
STINGRAYKIT_THROW(StringBuilder() % "Unknown type: " % _type);
}
_type = type;
}
#undef DESERIALIZE
}
<|endoftext|> |
<commit_before>#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_classad.h"
#include "condor_attributes.h"
#include "condor_adtypes.h"
#include "condor_qmgr.h"
/* gshadow is a wrapper around globusrun, meant to be a scheduler universe
* scheduler. It monitors job status and updates its ClassAd.
*/
#define QUERY_DELAY_SECS_DEFAULT 15 //can be overriden ClassAd
#define QMGMT_TIMEOUT 300 //this is copied per Todd's advice from shadow val.
//these are global so the sig handlers can use them.
char *contactString = NULL;
char *globusrun = NULL;
/*
Wait up for one of those nice debuggers which attaches to a running
process. These days, most every debugger can do this with a notable
exception being the ULTRIX version of "dbx".
*/
void wait_for_debugger( int do_wait )
{
sigset_t sigset;
// This is not strictly POSIX conforming becuase it uses SIGTRAP, but
// since it is only used in those environments where is is defined, it
// will probably pass...
#if defined(SIGTRAP)
/* Make sure we don't block the signal used by the
** debugger to control the debugged process (us).
*/
sigemptyset( &sigset );
sigaddset( &sigset, SIGTRAP );
sigprocmask( SIG_UNBLOCK, &sigset, 0 );
#endif
while( do_wait )
;
}
void
remove_job( int signal ) {
if ( contactString && globusrun && ( fork() == 0 ) ) {
//calling globusrun -kill <contact string> is like condor_rm
//I used exec here rather than popen because pclose blocks
//until completion, and I figured we wanted a fast shutdown.
execl( globusrun, globusrun, "-kill", contactString, NULL );
//if we get here, execl failed...
fprintf(stderr, "ERROR on execl %s %s -kill %s\n", globusrun,
globusrun, contactString );
// dprintf(D_ALWAYS, "ERROR on execl %s %s -kill %s\n", globusrun,
// globusrun, contactString );
}
exit( signal );
}
void
my_exit( int signal ) {
//probably want to change this
remove_job( signal );
}
int
main( int argc, char *argv[] ) {
FILE *run = NULL;
char Gstatus[64] = "";
char buffer[2048] = "";
char args[ATTRLIST_MAX_EXPRESSION] = "";
int delay = QUERY_DELAY_SECS_DEFAULT;
//install sig handlers
signal( SIGUSR1, remove_job );
signal( SIGQUIT, my_exit );
signal( SIGTERM, my_exit );
signal( SIGPIPE, SIG_IGN );
//wait_for_debugger( 1 );
//atoi returns zero on error, so --help, etc. will print usage...
//(there shouldn't be a cluster # 0....)
int cluster;
if ( !( cluster = atoi( argv[1] ) ) )
{
// dprintf( D_FULLDEBUG, "%s invalid command invocation\n" );
fprintf( stderr, "usage: %s <cluster>.<pid> <sinful schedd addr> \\"
"<globusrunpath> <args>\n", argv[0] );
exit( 1 );
}
int proc = 0;
char *decimal = strchr( argv[1], '.' );
proc = atoi( ++decimal ); //move past decimal
//THIS MUST be a fatal error if we cannot connect, since we
//start the globus job without getting GlobusArgs...
Qmgr_connection *schedd = ConnectQ( argv[2], QMGMT_TIMEOUT );
if ( !schedd ) {
//wait a bit and try once more...
sleep( 30 );
if ( !( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) ) {
// dprintf( D_ALWAYS, "%s ERROR, can't connect to schedd (%s)\n",argv[2]);
fprintf( stderr, "%s ERROR, cannot connect to schedd (%s)\n", argv[2] );
exit( 2 );
}
}
//these two attributes should always exist in the ClassAd
if ( GetAttributeString( cluster, proc, "GlobusStatus", Gstatus )
|| GetAttributeString( cluster, proc, "GlobusArgs", args ) )
{
// dprintf(D_ALWAYS,"ERROR, cannot find ClassAd for %d.%d\n", cluster, proc);
fprintf(stderr,"ERROR, cannot find ClassAd for %d.%d\n", cluster, proc);
DisconnectQ( schedd );
exit( 3 );
}
//these values *might* be in ClassAd
GetAttributeString( cluster, proc, "GlobusContactString", buffer );
if ( buffer[0] ) {
contactString = strdup( buffer );
}
GetAttributeInt( cluster, proc, "GlobusQueryDelay", &delay );
DisconnectQ( schedd ); //close because popen for globusrun takes long time
schedd = NULL;
globusrun = strdup( argv[3] );
struct stat statbuf;
if ( ( stat( globusrun, &statbuf ) < 0 )
// || (((statbuf.st_mode)&0xF000) != 0x0001)
)
{
// dprintf( D_ALWAYS, "ERROR stat'ing globusrun (%s)\n", globusrun );
fprintf( stderr, "ERROR stat'ing globusrun (%s)\n", globusrun );
exit( 4 );
}
//if there was no contactString in the ad, it hasn't
//been submitted to globusrun yet
if ( !strcmp( contactString, "X" ) )
{
sprintf( buffer, "%s %s", globusrun, args );
if ( !(run = popen( buffer, "r" ) ) ) {
// dprintf( D_ALWAYS, "unable to popen \"%s\"", buffer );
fprintf( stderr, "unable to popen \"%s\"", buffer );
exit( 5 );
}
while ( !feof( run ) ) {
if ( !fgets( buffer, 80, run ) ) {
fprintf(stderr, "error reading output of globus job\n" );
}
if ( !strncasecmp( buffer, "http", 4 ) ) {
contactString = strdup( chomp( buffer ) );
break;
}
}
if ( contactString ) {
if ( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) {
SetAttributeString( cluster, proc, "GlobusContactString",
contactString );
DisconnectQ( schedd );
}
else {
//FATAL error if we can't set GlobusContactString!
// dprintf( D_ALWAYS, "Error contacting schedd %s\n", argv[2] );
fprintf( stderr, "Error contacting schedd %s\n", argv[2] );
exit( 6 );
}
}
else {
// dprintf( D_ALWAYS, "Error reading contactString from globusrun\n" );
fprintf( stderr, "Error reading contactString from globusrun\n" );
exit( 7 );
}
}
schedd = NULL;
FILE *statusfp = NULL;
char status[80] = "";
sprintf( buffer, "%s -status %s", globusrun, contactString );
//loop until we're done or killed with a signal
while ( strcasecmp( Gstatus, "DONE" ) ) {
if ( !(statusfp = popen( buffer, "r" ) ) ) {
// dprintf( D_ALWAYS, "cannot popen( %s )\n", buffer );
fprintf( stderr, "cannot popen( %s )\n", buffer );
exit( 8 );
}
if ( !fgets( status, 80, statusfp ) ) {
// dprintf( D_ALWAYS, "pipe read errno %d\n", errno );
fprintf( stderr, "pipe read errno %d\n", errno );
}
chomp( status );
//I might have to close stderr at this point, a bug in globus reports
//Error to stderr, but nothing to stdout.
//I am currently using a modified Globusrun until they fix the bug.
if ( !strncasecmp( status, "ERROR", 5 ) ) {
strcpy( status, "DONE" );
}
pclose( statusfp );
if ( strcasecmp( Gstatus, status ) ) {
strcpy( Gstatus, status );
//this update is NOT fatal, just try again later
if ( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) {
SetAttributeString( cluster, proc, "GlobusStatus", Gstatus );
DisconnectQ( schedd );
}
else {
// dprintf( D_ALWAYS, "unable to update classAd for %d.%d\n",
// cluster, proc );
fprintf( stderr, "unable to update classAd for %d.%d\n",
cluster, proc );
}
}
sleep( delay );
}
}
<commit_msg>Added a decl for chomp so that it will compile with gcc 2.95<commit_after>#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_classad.h"
#include "condor_attributes.h"
#include "condor_adtypes.h"
#include "condor_qmgr.h"
/* gshadow is a wrapper around globusrun, meant to be a scheduler universe
* scheduler. It monitors job status and updates its ClassAd.
*/
#define QUERY_DELAY_SECS_DEFAULT 15 //can be overriden ClassAd
#define QMGMT_TIMEOUT 300 //this is copied per Todd's advice from shadow val.
//these are global so the sig handlers can use them.
char *contactString = NULL;
char *globusrun = NULL;
extern "C" char * chomp(char*);
/*
Wait up for one of those nice debuggers which attaches to a running
process. These days, most every debugger can do this with a notable
exception being the ULTRIX version of "dbx".
*/
void wait_for_debugger( int do_wait )
{
sigset_t sigset;
// This is not strictly POSIX conforming becuase it uses SIGTRAP, but
// since it is only used in those environments where is is defined, it
// will probably pass...
#if defined(SIGTRAP)
/* Make sure we don't block the signal used by the
** debugger to control the debugged process (us).
*/
sigemptyset( &sigset );
sigaddset( &sigset, SIGTRAP );
sigprocmask( SIG_UNBLOCK, &sigset, 0 );
#endif
while( do_wait )
;
}
void
remove_job( int signal ) {
if ( contactString && globusrun && ( fork() == 0 ) ) {
//calling globusrun -kill <contact string> is like condor_rm
//I used exec here rather than popen because pclose blocks
//until completion, and I figured we wanted a fast shutdown.
execl( globusrun, globusrun, "-kill", contactString, NULL );
//if we get here, execl failed...
fprintf(stderr, "ERROR on execl %s %s -kill %s\n", globusrun,
globusrun, contactString );
// dprintf(D_ALWAYS, "ERROR on execl %s %s -kill %s\n", globusrun,
// globusrun, contactString );
}
exit( signal );
}
void
my_exit( int signal ) {
//probably want to change this
remove_job( signal );
}
int
main( int argc, char *argv[] ) {
FILE *run = NULL;
char Gstatus[64] = "";
char buffer[2048] = "";
char args[ATTRLIST_MAX_EXPRESSION] = "";
int delay = QUERY_DELAY_SECS_DEFAULT;
//install sig handlers
signal( SIGUSR1, remove_job );
signal( SIGQUIT, my_exit );
signal( SIGTERM, my_exit );
signal( SIGPIPE, SIG_IGN );
//wait_for_debugger( 1 );
//atoi returns zero on error, so --help, etc. will print usage...
//(there shouldn't be a cluster # 0....)
int cluster;
if ( !( cluster = atoi( argv[1] ) ) )
{
// dprintf( D_FULLDEBUG, "%s invalid command invocation\n" );
fprintf( stderr, "usage: %s <cluster>.<pid> <sinful schedd addr> \\"
"<globusrunpath> <args>\n", argv[0] );
exit( 1 );
}
int proc = 0;
char *decimal = strchr( argv[1], '.' );
proc = atoi( ++decimal ); //move past decimal
//THIS MUST be a fatal error if we cannot connect, since we
//start the globus job without getting GlobusArgs...
Qmgr_connection *schedd = ConnectQ( argv[2], QMGMT_TIMEOUT );
if ( !schedd ) {
//wait a bit and try once more...
sleep( 30 );
if ( !( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) ) {
// dprintf( D_ALWAYS, "%s ERROR, can't connect to schedd (%s)\n",argv[2]);
fprintf( stderr, "%s ERROR, cannot connect to schedd (%s)\n", argv[2] );
exit( 2 );
}
}
//these two attributes should always exist in the ClassAd
if ( GetAttributeString( cluster, proc, "GlobusStatus", Gstatus )
|| GetAttributeString( cluster, proc, "GlobusArgs", args ) )
{
// dprintf(D_ALWAYS,"ERROR, cannot find ClassAd for %d.%d\n", cluster, proc);
fprintf(stderr,"ERROR, cannot find ClassAd for %d.%d\n", cluster, proc);
DisconnectQ( schedd );
exit( 3 );
}
//these values *might* be in ClassAd
GetAttributeString( cluster, proc, "GlobusContactString", buffer );
if ( buffer[0] ) {
contactString = strdup( buffer );
}
GetAttributeInt( cluster, proc, "GlobusQueryDelay", &delay );
DisconnectQ( schedd ); //close because popen for globusrun takes long time
schedd = NULL;
globusrun = strdup( argv[3] );
struct stat statbuf;
if ( ( stat( globusrun, &statbuf ) < 0 )
// || (((statbuf.st_mode)&0xF000) != 0x0001)
)
{
// dprintf( D_ALWAYS, "ERROR stat'ing globusrun (%s)\n", globusrun );
fprintf( stderr, "ERROR stat'ing globusrun (%s)\n", globusrun );
exit( 4 );
}
//if there was no contactString in the ad, it hasn't
//been submitted to globusrun yet
if ( !strcmp( contactString, "X" ) )
{
sprintf( buffer, "%s %s", globusrun, args );
if ( !(run = popen( buffer, "r" ) ) ) {
// dprintf( D_ALWAYS, "unable to popen \"%s\"", buffer );
fprintf( stderr, "unable to popen \"%s\"", buffer );
exit( 5 );
}
while ( !feof( run ) ) {
if ( !fgets( buffer, 80, run ) ) {
fprintf(stderr, "error reading output of globus job\n" );
}
if ( !strncasecmp( buffer, "http", 4 ) ) {
contactString = strdup( chomp( buffer ) );
break;
}
}
if ( contactString ) {
if ( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) {
SetAttributeString( cluster, proc, "GlobusContactString",
contactString );
DisconnectQ( schedd );
}
else {
//FATAL error if we can't set GlobusContactString!
// dprintf( D_ALWAYS, "Error contacting schedd %s\n", argv[2] );
fprintf( stderr, "Error contacting schedd %s\n", argv[2] );
exit( 6 );
}
}
else {
// dprintf( D_ALWAYS, "Error reading contactString from globusrun\n" );
fprintf( stderr, "Error reading contactString from globusrun\n" );
exit( 7 );
}
}
schedd = NULL;
FILE *statusfp = NULL;
char status[80] = "";
sprintf( buffer, "%s -status %s", globusrun, contactString );
//loop until we're done or killed with a signal
while ( strcasecmp( Gstatus, "DONE" ) ) {
if ( !(statusfp = popen( buffer, "r" ) ) ) {
// dprintf( D_ALWAYS, "cannot popen( %s )\n", buffer );
fprintf( stderr, "cannot popen( %s )\n", buffer );
exit( 8 );
}
if ( !fgets( status, 80, statusfp ) ) {
// dprintf( D_ALWAYS, "pipe read errno %d\n", errno );
fprintf( stderr, "pipe read errno %d\n", errno );
}
chomp( status );
//I might have to close stderr at this point, a bug in globus reports
//Error to stderr, but nothing to stdout.
//I am currently using a modified Globusrun until they fix the bug.
if ( !strncasecmp( status, "ERROR", 5 ) ) {
strcpy( status, "DONE" );
}
pclose( statusfp );
if ( strcasecmp( Gstatus, status ) ) {
strcpy( Gstatus, status );
//this update is NOT fatal, just try again later
if ( schedd = ConnectQ( argv[2], QMGMT_TIMEOUT ) ) {
SetAttributeString( cluster, proc, "GlobusStatus", Gstatus );
DisconnectQ( schedd );
}
else {
// dprintf( D_ALWAYS, "unable to update classAd for %d.%d\n",
// cluster, proc );
fprintf( stderr, "unable to update classAd for %d.%d\n",
cluster, proc );
}
}
sleep( delay );
}
}
<|endoftext|> |
<commit_before>// -*- c-style: gnu -*-
#include "act-types.h"
#include "act-config.h"
#include "act-format.h"
#include "act-util.h"
#include <xlocale.h>
namespace act {
field_id
lookup_field_id(const char *str)
{
switch (tolower_l(str[0], nullptr))
{
case 'a':
if (strcasecmp(str, "activity") == 0)
return field_activity;
else if (strcasecmp(str, "average_hr") == 0)
return field_average_hr;
break;
case 'c':
if (strcasecmp(str, "calories") == 0)
return field_calories;
else if (strcasecmp(str, "course") == 0)
return field_course;
break;
case 'd':
if (strcasecmp(str, "date") == 0)
return field_date;
else if (strcasecmp(str, "dew-point") == 0)
return field_dew_point;
else if (strcasecmp(str, "distance") == 0)
return field_distance;
else if (strcasecmp(str, "duration") == 0)
return field_duration;
break;
case 'e':
if (strcasecmp(str, "effort") == 0)
return field_effort;
else if (strcasecmp(str, "equipment") == 0)
return field_equipment;
break;
case 'g':
if (strcasecmp(str, "gps-file") == 0)
return field_gps_file;
break;
case 'k':
if (strcasecmp(str, "keywords") == 0)
return field_keywords;
break;
case 'm':
if (strcasecmp(str, "max-hr") == 0)
return field_max_hr;
else if (strcasecmp(str, "max-pace") == 0)
return field_max_pace;
else if (strcasecmp(str, "max-speed") == 0)
return field_max_speed;
break;
case 'p':
if (strcasecmp(str, "pace") == 0)
return field_pace;
break;
case 'q':
if (strcasecmp(str, "quality") == 0)
return field_quality;
break;
case 'r':
if (strcasecmp(str, "resting-hr") == 0)
return field_resting_hr;
break;
case 't':
if (strcasecmp(str, "temperature") == 0)
return field_temperature;
else if (strcasecmp(str, "type") == 0)
return field_type;
break;
case 'w':
if (strcasecmp(str, "weather") == 0)
return field_weather;
else if (strcasecmp(str, "weight") == 0)
return field_weight;
break;
}
return field_custom;
}
const char *
canonical_field_name(field_id id)
{
switch (id)
{
case field_activity:
return "Activity";
case field_average_hr:
return "Average-HR";
case field_calories:
return "Calories";
case field_course:
return "Course";
case field_custom:
return 0;
case field_date:
return "Date";
case field_dew_point:
return "Dew-Point";
case field_distance:
return "Distance";
case field_duration:
return "Duration";
case field_effort:
return "Effort";
case field_equipment:
return "Equipment";
case field_gps_file:
return "GPS-File";
case field_keywords:
return "Keywords";
case field_max_hr:
return "Max-HR";
case field_max_pace:
return "Max-Pace";
case field_max_speed:
return "Max-Speed";
case field_pace:
return "Pace";
case field_quality:
return "Quality";
case field_resting_hr:
return "Resting-HR";
case field_speed:
return "Speed";
case field_temperature:
return "Temperature";
case field_type:
return "Type";
case field_weather:
return "Weather";
case field_weight:
return "Weight";
}
}
field_data_type
lookup_field_data_type(const field_id id)
{
switch (id)
{
case field_activity:
case field_course:
case field_gps_file:
case field_type:
case field_custom:
return type_string;
case field_average_hr:
case field_calories:
case field_max_hr:
case field_resting_hr:
return type_number;
case field_date:
return type_date;
case field_distance:
return type_distance;
case field_duration:
return type_duration;
case field_effort:
case field_quality:
return type_fraction;
case field_equipment:
case field_keywords:
case field_weather:
return type_keywords;
case field_max_pace:
case field_pace:
return type_pace;
case field_max_speed:
case field_speed:
return type_speed;
case field_dew_point:
case field_temperature:
return type_temperature;
case field_weight:
return type_weight;
}
}
bool
canonicalize_field_string(field_data_type type, std::string &str)
{
switch (type)
{
case type_string:
return true;
case type_number: {
double value;
if (parse_number(str, &value))
{
str.clear();
format_number(str, value);
return true;
}
break; }
case type_date: {
time_t date;
if (parse_date_time(str, &date, nullptr))
{
str.clear();
format_date_time(str, date);
return true;
}
break; }
case type_duration: {
double dur;
if (parse_duration(str, &dur))
{
str.clear();
format_duration(str, dur);
return true;
}
break; }
case type_distance: {
double dist;
unit_type unit;
if (parse_distance(str, &dist, &unit))
{
str.clear();
format_distance(str, dist, unit);
return true;
}
break; }
case type_pace: {
double pace;
unit_type unit;
if (parse_pace(str, &pace, &unit))
{
str.clear();
format_pace(str, pace, unit);
return true;
}
break; }
case type_speed: {
double speed;
unit_type unit;
if (parse_speed(str, &speed, &unit))
{
str.clear();
format_speed(str, speed, unit);
return true;
}
break; }
case type_temperature: {
double temp;
unit_type unit;
if (parse_temperature(str, &temp, &unit))
{
str.clear();
format_temperature(str, temp, unit);
return true;
}
break; }
case type_weight: {
double temp;
unit_type unit;
if (parse_weight(str, &temp, &unit))
{
str.clear();
format_weight(str, temp, unit);
return true;
}
break; }
case type_fraction: {
double value;
if (parse_fraction(str, &value))
{
str.clear();
format_fraction(str, value);
return true;
}
break; }
case type_keywords: {
std::vector<std::string> keys;
if (parse_keywords(str, &keys))
{
str.clear();
format_keywords(str, keys);
return true;
}
break; }
}
return false;
}
namespace {
int
days_since_1970(const struct tm &tm)
{
/* Adapted from Linux kernel's mktime(). */
int year = tm.tm_year + 1900;
int month = tm.tm_mon - 1; /* 0..11 -> 11,12,1..10 */
if (month < 0)
month += 12, year -= 1;
int day = tm.tm_mday;
return ((year/4 - year/100 + year/400 + 367*month/12 + day)
+ year*365 - 719499);
}
void
append_days_date(std::string &str, int days)
{
time_t date = days * (time_t) (24*60*60);
struct tm tm = {0};
localtime_r(&date, &tm);
char buf[128];
strftime_l(buf, sizeof(buf), "%F", &tm, nullptr);
str.append(buf);
}
} // anonymous namespace
int
date_interval::date_index(time_t date) const
{
struct tm tm = {0};
localtime_r(&date, &tm);
switch (unit)
{
case days:
return days_since_1970(tm);
case weeks: {
// 1970-01-01 was a thursday.
static int week_offset = 4 - shared_config().start_of_week();
return (days_since_1970(tm) - week_offset) / 7; }
case months:
return (tm.tm_year - 70) * 12 + tm.tm_mon;
case years:
return tm.tm_year - 70;
}
}
void
date_interval::append_date(std::string &str, int x) const
{
switch (unit)
{
case days:
append_days_date(str, x);
break;
case weeks: {
static int week_offset = 4 - shared_config().start_of_week();
int days = x * 7 + week_offset;
append_days_date(str, days);
break; }
case months: {
int month = x % 12;
int year = 1970 + x / 12;
char buf[128];
static const char *names[] = {"January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December"};
snprintf_l(buf, sizeof(buf), nullptr, "%s %04d", names[month], year);
str.append(buf);
break; }
case years: {
char buf[64];
snprintf_l(buf, sizeof(buf), nullptr, "%d", 1970 + x);
str.append(buf);
break; }
}
}
} // namespace act
<commit_msg>fix weekly date intervals<commit_after>// -*- c-style: gnu -*-
#include "act-types.h"
#include "act-config.h"
#include "act-format.h"
#include "act-util.h"
#include <xlocale.h>
namespace act {
field_id
lookup_field_id(const char *str)
{
switch (tolower_l(str[0], nullptr))
{
case 'a':
if (strcasecmp(str, "activity") == 0)
return field_activity;
else if (strcasecmp(str, "average_hr") == 0)
return field_average_hr;
break;
case 'c':
if (strcasecmp(str, "calories") == 0)
return field_calories;
else if (strcasecmp(str, "course") == 0)
return field_course;
break;
case 'd':
if (strcasecmp(str, "date") == 0)
return field_date;
else if (strcasecmp(str, "dew-point") == 0)
return field_dew_point;
else if (strcasecmp(str, "distance") == 0)
return field_distance;
else if (strcasecmp(str, "duration") == 0)
return field_duration;
break;
case 'e':
if (strcasecmp(str, "effort") == 0)
return field_effort;
else if (strcasecmp(str, "equipment") == 0)
return field_equipment;
break;
case 'g':
if (strcasecmp(str, "gps-file") == 0)
return field_gps_file;
break;
case 'k':
if (strcasecmp(str, "keywords") == 0)
return field_keywords;
break;
case 'm':
if (strcasecmp(str, "max-hr") == 0)
return field_max_hr;
else if (strcasecmp(str, "max-pace") == 0)
return field_max_pace;
else if (strcasecmp(str, "max-speed") == 0)
return field_max_speed;
break;
case 'p':
if (strcasecmp(str, "pace") == 0)
return field_pace;
break;
case 'q':
if (strcasecmp(str, "quality") == 0)
return field_quality;
break;
case 'r':
if (strcasecmp(str, "resting-hr") == 0)
return field_resting_hr;
break;
case 't':
if (strcasecmp(str, "temperature") == 0)
return field_temperature;
else if (strcasecmp(str, "type") == 0)
return field_type;
break;
case 'w':
if (strcasecmp(str, "weather") == 0)
return field_weather;
else if (strcasecmp(str, "weight") == 0)
return field_weight;
break;
}
return field_custom;
}
const char *
canonical_field_name(field_id id)
{
switch (id)
{
case field_activity:
return "Activity";
case field_average_hr:
return "Average-HR";
case field_calories:
return "Calories";
case field_course:
return "Course";
case field_custom:
return 0;
case field_date:
return "Date";
case field_dew_point:
return "Dew-Point";
case field_distance:
return "Distance";
case field_duration:
return "Duration";
case field_effort:
return "Effort";
case field_equipment:
return "Equipment";
case field_gps_file:
return "GPS-File";
case field_keywords:
return "Keywords";
case field_max_hr:
return "Max-HR";
case field_max_pace:
return "Max-Pace";
case field_max_speed:
return "Max-Speed";
case field_pace:
return "Pace";
case field_quality:
return "Quality";
case field_resting_hr:
return "Resting-HR";
case field_speed:
return "Speed";
case field_temperature:
return "Temperature";
case field_type:
return "Type";
case field_weather:
return "Weather";
case field_weight:
return "Weight";
}
}
field_data_type
lookup_field_data_type(const field_id id)
{
switch (id)
{
case field_activity:
case field_course:
case field_gps_file:
case field_type:
case field_custom:
return type_string;
case field_average_hr:
case field_calories:
case field_max_hr:
case field_resting_hr:
return type_number;
case field_date:
return type_date;
case field_distance:
return type_distance;
case field_duration:
return type_duration;
case field_effort:
case field_quality:
return type_fraction;
case field_equipment:
case field_keywords:
case field_weather:
return type_keywords;
case field_max_pace:
case field_pace:
return type_pace;
case field_max_speed:
case field_speed:
return type_speed;
case field_dew_point:
case field_temperature:
return type_temperature;
case field_weight:
return type_weight;
}
}
bool
canonicalize_field_string(field_data_type type, std::string &str)
{
switch (type)
{
case type_string:
return true;
case type_number: {
double value;
if (parse_number(str, &value))
{
str.clear();
format_number(str, value);
return true;
}
break; }
case type_date: {
time_t date;
if (parse_date_time(str, &date, nullptr))
{
str.clear();
format_date_time(str, date);
return true;
}
break; }
case type_duration: {
double dur;
if (parse_duration(str, &dur))
{
str.clear();
format_duration(str, dur);
return true;
}
break; }
case type_distance: {
double dist;
unit_type unit;
if (parse_distance(str, &dist, &unit))
{
str.clear();
format_distance(str, dist, unit);
return true;
}
break; }
case type_pace: {
double pace;
unit_type unit;
if (parse_pace(str, &pace, &unit))
{
str.clear();
format_pace(str, pace, unit);
return true;
}
break; }
case type_speed: {
double speed;
unit_type unit;
if (parse_speed(str, &speed, &unit))
{
str.clear();
format_speed(str, speed, unit);
return true;
}
break; }
case type_temperature: {
double temp;
unit_type unit;
if (parse_temperature(str, &temp, &unit))
{
str.clear();
format_temperature(str, temp, unit);
return true;
}
break; }
case type_weight: {
double temp;
unit_type unit;
if (parse_weight(str, &temp, &unit))
{
str.clear();
format_weight(str, temp, unit);
return true;
}
break; }
case type_fraction: {
double value;
if (parse_fraction(str, &value))
{
str.clear();
format_fraction(str, value);
return true;
}
break; }
case type_keywords: {
std::vector<std::string> keys;
if (parse_keywords(str, &keys))
{
str.clear();
format_keywords(str, keys);
return true;
}
break; }
}
return false;
}
namespace {
int
days_since_1970(const struct tm &tm)
{
/* Adapted from Linux kernel's mktime(). */
int year = tm.tm_year + 1900;
int month = tm.tm_mon - 1; /* 0..11 -> 11,12,1..10 */
if (month < 0)
month += 12, year -= 1;
int day = tm.tm_mday;
return ((year/4 - year/100 + year/400 + 367*month/12 + day)
+ year*365 - 719499);
}
void
append_days_date(std::string &str, int days)
{
time_t date = days * (time_t) (24*60*60);
struct tm tm = {0};
localtime_r(&date, &tm);
char buf[128];
strftime_l(buf, sizeof(buf), "%F", &tm, nullptr);
str.append(buf);
}
} // anonymous namespace
int
date_interval::date_index(time_t date) const
{
struct tm tm = {0};
localtime_r(&date, &tm);
switch (unit)
{
case days:
return days_since_1970(tm);
case weeks: {
// 1970-01-01 was a thursday.
static int week_offset = 4 - shared_config().start_of_week();
return (days_since_1970(tm) + week_offset) / 7; }
case months:
return (tm.tm_year - 70) * 12 + tm.tm_mon;
case years:
return tm.tm_year - 70;
}
}
void
date_interval::append_date(std::string &str, int x) const
{
switch (unit)
{
case days:
append_days_date(str, x);
break;
case weeks: {
static int week_offset = 4 - shared_config().start_of_week();
int days = x * 7 - week_offset;
append_days_date(str, days);
break; }
case months: {
int month = x % 12;
int year = 1970 + x / 12;
char buf[128];
static const char *names[] = {"January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December"};
snprintf_l(buf, sizeof(buf), nullptr, "%s %04d", names[month], year);
str.append(buf);
break; }
case years: {
char buf[64];
snprintf_l(buf, sizeof(buf), nullptr, "%d", 1970 + x);
str.append(buf);
break; }
}
}
} // namespace act
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"
#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>
#include <sensor_msgs/JointState.h>
class CalibrateCameraServer {
private:
ros::NodeHandle n;
actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
std::string action_name;
ros::ServiceClient client;
std::string camera_name;
std::string camera_topic;
calibrate_chest::CalibrateCameraFeedback feedback;
calibrate_chest::CalibrateCameraResult result;
public:
CalibrateCameraServer(const std::string& name, const std::string& camera_name) :
server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
action_name(name),
client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
camera_name(camera_name),
camera_topic(camera_name + "/depth/points")
{
server.start();
}
private:
bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
{
return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
}
void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
{
pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
for (int i = 0; i < points.size(); ++i) {
if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
inlier_cloud->push_back(points[i]);
}
else {
outlier_cloud->push_back(points[i]);
}
}
pcl::visualization::PCLVisualizer viewer("3D Viewer");
viewer.setBackgroundColor(0, 0, 0);
viewer.addCoordinateSystem(1.0);
viewer.initCameraParameters();
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
boost::this_thread::sleep(boost::posix_time::microseconds(100000));
}
}
void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
{
Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f normal = first.cross(second);
normal.normalize();
plane.segment<3>(0) = normal;
plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
}
void extract_height_and_angle(const Eigen::Vector4f& plane)
{
feedback.status = "Checking and saving calibration...";
server.publishFeedback(feedback);
ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
double dist = fabs(plane(3)/plane(2)); // distance along z axis
double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
ROS_INFO("Distance to plane along camera axis: %f", dist);
ROS_INFO("Height above ground: %f", height);
double angle = asin(height/dist);
double angle_deg = 180.0f*angle/M_PI;
ROS_INFO("Angle radians: %f", angle);
ROS_INFO("Angle degrees: %f", angle_deg);
result.angle = angle_deg;
result.height = height;
if (fabs(45.0f - angle_deg) > 3.0f) {
result.status = "Angle not close enough to 45 degrees.";
server.setAborted(result);
return;
}
mongodb_store::SetParam srv;
char buffer[250];
// store height above ground in datacentre
ros::param::set(std::string("/") + camera_name + "_height", height);
sprintf(buffer, "{\"path\":\"/%s_height\",\"value\":%f}", camera_name.c_str(), height);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set height, is config manager running?");
}
// store angle between camera and horizontal plane
ros::param::set(std::string("/") + camera_name + "_angle", angle);
sprintf(buffer, "{\"path\":\"/%s_angle\",\"value\":%f}", camera_name.c_str(), angle);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set angle, is config manager running?");
}
result.status = "Successfully computed and saved calibration.";
server.setSucceeded(result);
}
void publish_calibration()
{
feedback.status = "Publishing calibration...";
feedback.progress = 0.0f;
// get calibration with respect to ground plane from the calibrate_chest node
double height, angle;
n.param<double>(std::string("/") + camera_name + "_height", height, 1.10f); // get the height calibration
n.param<double>(std::string("/") + camera_name + "_angle", angle, 0.72f); // get the angle calibration
ros::Rate rate(1.0f);
ros::Publisher pub = n.advertise<sensor_msgs::JointState>("/chest_calibration_publisher/state", 1);
int counter = 0; // only publish for the first 10 secs, transforms will stay in tf
while (n.ok() && counter < 5) {
sensor_msgs::JointState joint_state;
joint_state.header.stamp = ros::Time::now();
joint_state.name.resize(2);
joint_state.position.resize(2);
joint_state.velocity.resize(2);
joint_state.name[0] = camera_name + "_height_joint";
joint_state.name[1] = camera_name + "_tilt_joint";
joint_state.position[0] = height;
joint_state.position[1] = angle;
joint_state.velocity[0] = 0;
joint_state.velocity[1] = 0;
pub.publish(joint_state);
feedback.progress = float(counter+1)/5.0f;
server.publishFeedback(feedback);
rate.sleep();
++counter;
}
ROS_INFO("Stopping to publish chest transform after 5 seconds, quitting...");
result.status = "Published calibration.";
result.angle = 180.0f/M_PI*angle;
result.height = height;
server.setSucceeded(result);
}
public:
void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
{
//if (!do_calibrate) {
// return;
//}
//do_calibrate = false;
feedback.status = "Calibrating...";
feedback.progress = 0.0f;
server.publishFeedback(feedback);
ROS_INFO("Got a pointcloud, calibrating...");
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*msg, cloud);
int nbr = cloud.size();
int max = 1000; // ransac iterations
double threshold = 0.02; // threshold for plane inliers
Eigen::Vector4f best_plane; // best plane parameters found
int best_inliers = -1; // best number of inliers
int inds[3];
Eigen::Vector4f plane;
int inliers;
for (int i = 0; i < max; ++i) {
for (int j = 0; j < 3; ++j) {
inds[j] = rand() % nbr; // get a random point
}
// check that the points aren't the same
if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
continue;
}
compute_plane(plane, cloud, inds);
inliers = 0;
for (int j = 0; j < nbr; j += 30) { // count number of inliers
if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
++inliers;
}
}
if (inliers > best_inliers) {
best_plane = plane;
best_inliers = inliers;
}
if (i % 10 == 0 || i == max - 1) {
feedback.progress = float(i+1)/float(max);
server.publishFeedback(feedback);
}
}
extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
//plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
}
void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
{
if (goal->command == "calibrate") {
sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
if (msg) {
msg_callback(msg);
}
else {
result.status = "Did not receive any point cloud.";
server.setAborted(result);
}
}
else if (goal->command == "publish") {
publish_calibration();
}
else {
result.status = "Enter command \"calibrate\" or \"publish\".";
server.setAborted(result);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "calibrate_chest");
CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion");
ros::spin();
return 0;
}
<commit_msg>Made desired angle configurable<commit_after>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"
#include <sstream>
#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>
#include <sensor_msgs/JointState.h>
class CalibrateCameraServer {
private:
ros::NodeHandle n;
actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
std::string action_name;
ros::ServiceClient client;
std::string camera_name;
std::string camera_topic;
double desired_angle;
calibrate_chest::CalibrateCameraFeedback feedback;
calibrate_chest::CalibrateCameraResult result;
public:
CalibrateCameraServer(const std::string& name, const std::string& camera_name, double angle) :
server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
action_name(name),
client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
camera_name(camera_name),
camera_topic(camera_name + "/depth/points"),
desired_angle(angle)
{
server.start();
}
private:
bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
{
return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
}
void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
{
pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
for (int i = 0; i < points.size(); ++i) {
if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
inlier_cloud->push_back(points[i]);
}
else {
outlier_cloud->push_back(points[i]);
}
}
pcl::visualization::PCLVisualizer viewer("3D Viewer");
viewer.setBackgroundColor(0, 0, 0);
viewer.addCoordinateSystem(1.0);
viewer.initCameraParameters();
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
boost::this_thread::sleep(boost::posix_time::microseconds(100000));
}
}
void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
{
Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f normal = first.cross(second);
normal.normalize();
plane.segment<3>(0) = normal;
plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
}
void extract_height_and_angle(const Eigen::Vector4f& plane)
{
feedback.status = "Checking and saving calibration...";
server.publishFeedback(feedback);
ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
double dist = fabs(plane(3)/plane(2)); // distance along z axis
double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
ROS_INFO("Distance to plane along camera axis: %f", dist);
ROS_INFO("Height above ground: %f", height);
double angle = asin(height/dist);
double angle_deg = 180.0f*angle/M_PI;
ROS_INFO("Angle radians: %f", angle);
ROS_INFO("Angle degrees: %f", angle_deg);
result.angle = angle_deg;
result.height = height;
if (fabs(desired_angle - angle_deg) > 3.0f) {
std::stringstream ss;
ss << desired_angle;
result.status = std::string("Angle not close enough to ") + ss.str() + " degrees.";
server.setAborted(result);
return;
}
mongodb_store::SetParam srv;
char buffer[250];
// store height above ground in datacentre
ros::param::set(std::string("/") + camera_name + "_height", height);
sprintf(buffer, "{\"path\":\"/%s_height\",\"value\":%f}", camera_name.c_str(), height);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set height, is config manager running?");
}
// store angle between camera and horizontal plane
ros::param::set(std::string("/") + camera_name + "_angle", angle);
sprintf(buffer, "{\"path\":\"/%s_angle\",\"value\":%f}", camera_name.c_str(), angle);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set angle, is config manager running?");
}
result.status = "Successfully computed and saved calibration.";
server.setSucceeded(result);
}
void publish_calibration()
{
feedback.status = "Publishing calibration...";
feedback.progress = 0.0f;
// get calibration with respect to ground plane from the calibrate_chest node
double height, angle;
n.param<double>(std::string("/") + camera_name + "_height", height, 1.10f); // get the height calibration
n.param<double>(std::string("/") + camera_name + "_angle", angle, 0.72f); // get the angle calibration
ros::Rate rate(1.0f);
ros::Publisher pub = n.advertise<sensor_msgs::JointState>("/chest_calibration_publisher/state", 1);
int counter = 0; // only publish for the first 10 secs, transforms will stay in tf
while (n.ok() && counter < 5) {
sensor_msgs::JointState joint_state;
joint_state.header.stamp = ros::Time::now();
joint_state.name.resize(2);
joint_state.position.resize(2);
joint_state.velocity.resize(2);
joint_state.name[0] = camera_name + "_height_joint";
joint_state.name[1] = camera_name + "_tilt_joint";
joint_state.position[0] = height;
joint_state.position[1] = angle;
joint_state.velocity[0] = 0;
joint_state.velocity[1] = 0;
pub.publish(joint_state);
feedback.progress = float(counter+1)/5.0f;
server.publishFeedback(feedback);
rate.sleep();
++counter;
}
ROS_INFO("Stopping to publish chest transform after 5 seconds, quitting...");
result.status = "Published calibration.";
result.angle = 180.0f/M_PI*angle;
result.height = height;
server.setSucceeded(result);
}
public:
void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
{
//if (!do_calibrate) {
// return;
//}
//do_calibrate = false;
feedback.status = "Calibrating...";
feedback.progress = 0.0f;
server.publishFeedback(feedback);
ROS_INFO("Got a pointcloud, calibrating...");
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*msg, cloud);
int nbr = cloud.size();
int max = 1000; // ransac iterations
double threshold = 0.02; // threshold for plane inliers
Eigen::Vector4f best_plane; // best plane parameters found
int best_inliers = -1; // best number of inliers
int inds[3];
Eigen::Vector4f plane;
int inliers;
for (int i = 0; i < max; ++i) {
for (int j = 0; j < 3; ++j) {
inds[j] = rand() % nbr; // get a random point
}
// check that the points aren't the same
if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
continue;
}
compute_plane(plane, cloud, inds);
inliers = 0;
for (int j = 0; j < nbr; j += 30) { // count number of inliers
if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
++inliers;
}
}
if (inliers > best_inliers) {
best_plane = plane;
best_inliers = inliers;
}
if (i % 10 == 0 || i == max - 1) {
feedback.progress = float(i+1)/float(max);
server.publishFeedback(feedback);
}
}
extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
//plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
}
void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
{
if (goal->command == "calibrate") {
sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
if (msg) {
msg_callback(msg);
}
else {
result.status = "Did not receive any point cloud.";
server.setAborted(result);
}
}
else if (goal->command == "publish") {
publish_calibration();
}
else {
result.status = "Enter command \"calibrate\" or \"publish\".";
server.setAborted(result);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "calibrate_chest");
CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion", 46.0);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __REPLICASET_HPP_INCLUDED__
#define __REPLICASET_HPP_INCLUDED__
#include <iterator>
#include <memory>
#include <set>
#include <string>
struct Replica
{
std::string hostname;
short port;
Replica()
: hostname(),
port()
{
}
Replica(std::string h, short p=8081)
: hostname(h),
port(p)
{
}
};
struct compare_replica
{
bool operator()(const Replica& lhs, const Replica& rhs) const
{
return lhs.hostname < rhs.hostname;
}
};
class ReplicaSet
{
public:
ReplicaSet();
~ReplicaSet();
void Add(Replica replica);
void Remove(Replica replica);
bool Contains(Replica replica);
int GetSize();
void Clear();
std::shared_ptr<ReplicaSet> Intersection(std::shared_ptr<ReplicaSet> other);
using iterator = std::set<Replica, compare_replica>::iterator;
using const_iterator = std::set<Replica, compare_replica>::const_iterator;
ReplicaSet::iterator begin() const;
ReplicaSet::iterator end() const;
private:
std::set<Replica, compare_replica> replicaset;
};
#endif
<commit_msg>Update replicaset iterator definition syntax<commit_after>#ifndef __REPLICASET_HPP_INCLUDED__
#define __REPLICASET_HPP_INCLUDED__
#include <iterator>
#include <memory>
#include <set>
#include <string>
struct Replica
{
std::string hostname;
short port;
Replica()
: hostname(),
port()
{
}
Replica(std::string h, short p=8081)
: hostname(h),
port(p)
{
}
};
struct compare_replica
{
bool operator()(const Replica& lhs, const Replica& rhs) const
{
return lhs.hostname < rhs.hostname;
}
};
class ReplicaSet
{
public:
ReplicaSet();
~ReplicaSet();
void Add(Replica replica);
void Remove(Replica replica);
bool Contains(Replica replica);
int GetSize();
void Clear();
std::shared_ptr<ReplicaSet> Intersection(std::shared_ptr<ReplicaSet> other);
typedef typename std::set<Replica, compare_replica>::iterator iterator;
typedef typename std::set<Replica, compare_replica>::const_iterator const_iterator;
ReplicaSet::iterator begin() const;
ReplicaSet::iterator end() const;
private:
std::set<Replica, compare_replica> replicaset;
};
#endif
<|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: AliTRDtrackingEfficiencyCombined.cxx 27496 2008-07-22 08:35:45Z cblume $ */
////////////////////////////////////////////////////////////////////////////
// //
// Reconstruction QA //
// //
// Authors: //
// Markus Fasel <[email protected]> //
// //
////////////////////////////////////////////////////////////////////////////
#include <TObjArray.h>
#include <TProfile.h>
#include <TMath.h>
#include <TCanvas.h>
#include "TTreeStream.h"
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliTrackReference.h"
#include "AliAnalysisManager.h"
#include "AliTRDseedV1.h"
#include "AliTRDtrackV1.h"
#include "AliTRDtrackInfo/AliTRDtrackInfo.h"
#include "AliTRDtrackingEfficiencyCombined.h"
ClassImp(AliTRDtrackingEfficiencyCombined)
//_____________________________________________________________________________
AliTRDtrackingEfficiencyCombined::AliTRDtrackingEfficiencyCombined()
:AliTRDrecoTask("TrackingEffMC", "Combined Tracking Efficiency")
{
//
// Default constructor
//
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::CreateOutputObjects(){
//
// Create output objects
//
OpenFile(0, "RECREATE");
const Int_t nbins = 11;
Float_t xbins[nbins+1] = {.5, .7, .9, 1.3, 1.7, 2.4, 3.5, 4.5, 5.5, 7., 9., 11.};
fContainer = new TObjArray();
fContainer->Add(new TProfile("trEffComb", "Combined Tracking Efficiency", nbins, xbins));
fContainer->Add(new TProfile("trContComb", "Combined Tracking Contamination", nbins, xbins));
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::Exec(Option_t *){
//
// Do it
//
const Float_t kAlpha = 0.349065850;
Int_t naccepted = 0, nrejected = 0, ndoublecounted = 0;
Int_t labelsacc[10000];
Int_t labelsrej[10000];
Float_t momacc[10000];
Float_t momrej[10000];
if(!AliTracker::GetFieldMap()){
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., AliMagFMaps::k5kG);
AliTracker::SetFieldMap(field, kTRUE);
}
TProfile *efficiency = (TProfile *)fContainer->At(0);
TProfile *contamination = (TProfile *)fContainer->At(1);
Int_t nTrackInfos = fTracks->GetEntriesFast();
Double_t mom = 0;
AliTRDtrackV1 *TRDtrack = 0x0;
AliTRDtrackInfo *trkInf = 0x0;
AliTrackReference *trackRef = 0x0;
for(Int_t itinf = 0; itinf < nTrackInfos; itinf++){
mom = 0.;
trkInf = dynamic_cast<AliTRDtrackInfo *>(fTracks->UncheckedAt(itinf));
if(!trkInf) continue;
if((TRDtrack = trkInf->GetTRDtrack()) || trkInf->GetNumberOfClustersRefit()){
// check if allready found by the tracker
Bool_t found = kFALSE;
for(Int_t il = 0; il < naccepted; il++){
if(labelsacc[il] == trkInf->GetLabel()) found = kTRUE;
}
if(found){
mom = trackRef ? trackRef->P() : TRDtrack->P();
contamination->Fill(mom, 1);
ndoublecounted++;
continue;
}
if(trkInf->GetNTrackRefs()){
Int_t iref = 0;
while(!(trackRef = trkInf->GetTrackRef(iref++)));
}
if(!trackRef) printf("Error: Track Reference missing for Track %d\n", TRDtrack->GetLabel());
mom = trackRef ? trackRef->P() : TRDtrack->P();
// Accept track
if(fDebugLevel > 3)printf("Accept track\n");
momacc[naccepted] = mom;
labelsacc[naccepted++] = trkInf->GetLabel();
/* printf("Reconstructed: event %3d Tracks: MC[%d] ESD[%d] NRefs[%d]\n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), trkInf->GetLabel(), trkInf->GetTrackId(), trkInf->GetNTrackRefs());*/
} else{
if(fDebugLevel>10) printf("Analysing Track References\n");
// Check if track is findable
Float_t xmin = 10000.0, xmax = 0.0;
Float_t ymin = 0.0, ymax = 0.0;
Float_t zmin = 0.0, zmax = 0.0;
Float_t lastx = 0.0, x = 0.0;
Int_t nLayers = 0;
/* trackRef = trkInf->GetTrackRef(0);*/
/* xmin = trackRef->LocalX(); xmax = trackRef->LocalX();
ymin = trackRef->LocalY(); ymax = trackRef->LocalY();
mom = trackRef->P();*/
Int_t *sector = new Int_t[trkInf->GetNTrackRefs()];
for(Int_t itr = 0; itr < trkInf->GetNTrackRefs(); itr++){
trackRef = trkInf->GetTrackRef(itr);
if(fDebugLevel>10) printf("%d. x[%f], y[%f], z[%f]\n", itr, trackRef->LocalX(), trackRef->LocalY(), trackRef->Z());
x = trackRef->LocalX();
if(x < 250. || x > 370.) continue; // Be Sure that we are inside TRD
sector[itr] = Int_t(trackRef->Alpha()/kAlpha);
if(x < xmin){
xmin = trackRef->LocalX();
ymin = trackRef->LocalY();
zmin = trackRef->Z();
mom = trackRef->P();
}
if(x > xmax){
xmax = trackRef->LocalX();
ymax = trackRef->LocalY();
zmax = trackRef->Z();
}
if(itr > 0){
Float_t dist = TMath::Abs(x - lastx);
if(fDebugLevel>10) printf("x = %f, lastx = %f, dist = %f\n", x, lastx, dist);
if(TMath::Abs(dist - 3.7) < 0.1) nLayers++; // ref(i+1) has to be larger than ref(i)
}
lastx = x;
}
// Apply cuts
Bool_t findable = kTRUE;
if(trkInf->GetNTrackRefs() > 2 && xmax > xmin){
if(mom < 0.55) findable = kFALSE; // momentum cut at 0.6
Double_t yangle = (ymax -ymin)/(xmax - xmin);
Double_t zangle = (zmax -zmin)/(xmax - xmin);
if(fDebugLevel>10) printf("track: y-Angle = %f, z-Angle = %f\n", yangle, zangle);
if(fDebugLevel>10) printf("nLayers = %d\n", nLayers);
if(TMath::ATan(TMath::Abs(yangle)) > 45.) findable = kFALSE;
if(TMath::ATan(TMath::Abs(zangle)) > 45.) findable = kFALSE;
if(nLayers < 4) findable = kFALSE;
if(!trkInf->IsPrimary()) findable = kFALSE;
Bool_t samesec = kTRUE;
for(Int_t iref = 1; iref < trkInf->GetNTrackRefs(); iref++)
if(sector[iref] != sector[0]) samesec = kFALSE;
if(!samesec) findable = kFALSE; // Discard all tracks which are passing more than one sector
if(fDebugLevel){
Double_t trackAngle = TMath::ATan(yangle);
Bool_t primary = trkInf->IsPrimary();
(*fDebugStream) << "NotFoundTrack"
<< "Momentum=" << mom
<< "trackAngle="<< trackAngle
<< "NLayers=" << nLayers
<< "Primary=" << primary
<< "\n";
}
}
else
findable = kFALSE;
delete[] sector;
if(findable){
momrej[nrejected] = mom;
labelsrej[nrejected++] = trkInf->GetLabel();
/* printf("Not Reconstructed: event %3d Tracks: MC[%d] ESD[%d] NRefs[%d]\n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), trkInf->GetLabel(), trkInf->GetTrackId(), trkInf->GetNTrackRefs());*/
}
}
}
for(Int_t itk = 0; itk < naccepted; itk++){
if(fDebugLevel > 2)printf("Accepted MC track: %d\n", labelsacc[itk]);
efficiency->Fill(momacc[itk], 1);
contamination->Fill(momacc[itk], 0);
}
Int_t nall = naccepted;
for(Int_t imis = 0; imis < nrejected; imis++){
Bool_t found = kFALSE;
for(Int_t ifound = 0; ifound < naccepted; ifound++){
if(labelsacc[ifound] == labelsrej[imis]){
found = kTRUE;
break;
}
}
if(!found){
efficiency->Fill(momrej[imis], 0);
contamination->Fill(momrej[imis], 0);
if(fDebugLevel > 2)printf("Rejected MC track: %d\n", labelsrej[imis]);
nall++;
}
}
//if(fDebugLevel>=1)
printf("%3d Tracks: MC[%3d] TRD[%3d | %5.2f%%] \n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), nall, naccepted, 1.E2*Float_t(naccepted)/Float_t(nall));
printf("%3d Tracks: ALL[%3d] DoubleCounted[%3d | %5.2f%%] \n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), nall + ndoublecounted, ndoublecounted, 1.E2*Float_t(ndoublecounted)/Float_t(nall + ndoublecounted));
PostData(0, fContainer);
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::Terminate(Option_t *)
{
//
// Termination
//
if(fDebugStream){
delete fDebugStream;
fDebugStream = 0x0;
fDebugLevel = 0;
}
fContainer = dynamic_cast<TObjArray*>(GetOutputData(0));
if (!fContainer) {
Printf("ERROR: list not available");
return;
}
/*TProfile *hEff = (TProfile*)fContainer->At(0);
TProfile *hEffCont = (TProfile*)fContainer->At(1);
Printf("Eff[%p] EffCont[%p]\n", (void*)hEff, (void*)hEffCont);
TCanvas *c2 = new TCanvas("c2","",800,400);
c2->Divide(2,1);
c2->cd(1);
hEff->DrawCopy("e1");
c2->cd(2);
hEffCont->DrawCopy("e1");*/
}
<commit_msg>insert protection against kink candidates from TPC<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: AliTRDtrackingEfficiencyCombined.cxx 27496 2008-07-22 08:35:45Z cblume $ */
////////////////////////////////////////////////////////////////////////////
// //
// Reconstruction QA //
// //
// Authors: //
// Markus Fasel <[email protected]> //
// //
////////////////////////////////////////////////////////////////////////////
#include <TObjArray.h>
#include <TProfile.h>
#include <TMath.h>
#include <TCanvas.h>
#include "TTreeStream.h"
#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliTrackReference.h"
#include "AliAnalysisManager.h"
#include "AliTRDseedV1.h"
#include "AliTRDtrackV1.h"
#include "AliTRDtrackInfo/AliTRDtrackInfo.h"
#include "AliTRDtrackingEfficiencyCombined.h"
ClassImp(AliTRDtrackingEfficiencyCombined)
//_____________________________________________________________________________
AliTRDtrackingEfficiencyCombined::AliTRDtrackingEfficiencyCombined()
:AliTRDrecoTask("TrackingEffMC", "Combined Tracking Efficiency")
{
//
// Default constructor
//
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::CreateOutputObjects(){
//
// Create output objects
//
OpenFile(0, "RECREATE");
const Int_t nbins = 11;
Float_t xbins[nbins+1] = {.5, .7, .9, 1.3, 1.7, 2.4, 3.5, 4.5, 5.5, 7., 9., 11.};
fContainer = new TObjArray();
fContainer->Add(new TProfile("trEffComb", "Combined Tracking Efficiency", nbins, xbins));
fContainer->Add(new TProfile("trContComb", "Combined Tracking Contamination", nbins, xbins));
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::Exec(Option_t *){
//
// Do it
//
const Float_t kAlpha = 0.349065850;
Int_t naccepted = 0, nrejected = 0, ndoublecounted = 0;
Int_t labelsacc[10000];
Int_t labelsrej[10000];
Float_t momacc[10000];
Float_t momrej[10000];
TProfile *efficiency = (TProfile *)fContainer->At(0);
TProfile *contamination = (TProfile *)fContainer->At(1);
Int_t nTrackInfos = fTracks->GetEntriesFast();
Double_t mom = 0;
AliTRDtrackV1 *TRDtrack = 0x0;
AliTRDtrackInfo *trkInf = 0x0;
AliTrackReference *trackRef = 0x0;
for(Int_t itinf = 0; itinf < nTrackInfos; itinf++){
mom = 0.;
trkInf = dynamic_cast<AliTRDtrackInfo *>(fTracks->UncheckedAt(itinf));
if(!trkInf) continue;
if((TRDtrack = trkInf->GetTRDtrack()) || trkInf->GetNumberOfClustersRefit()){
// check if allready found by the tracker
Bool_t found = kFALSE;
for(Int_t il = 0; il < naccepted; il++){
if(labelsacc[il] == trkInf->GetLabel()) found = kTRUE;
}
if(found){
mom = trackRef ? trackRef->P() : TRDtrack->P();
contamination->Fill(mom, 1);
ndoublecounted++;
continue;
}
if(trkInf->GetNTrackRefs()){
Int_t iref = 0;
while(!(trackRef = trkInf->GetTrackRef(iref++)));
}
if(!trackRef) printf("Error: Track Reference missing for Track %d\n", trkInf->GetLabel());
mom = trackRef ? trackRef->P() : TRDtrack->P();
// Accept track
if(fDebugLevel > 3)printf("Accept track\n");
momacc[naccepted] = mom;
labelsacc[naccepted++] = trkInf->GetLabel();
/* printf("Reconstructed: event %3d Tracks: MC[%d] ESD[%d] NRefs[%d]\n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), trkInf->GetLabel(), trkInf->GetTrackId(), trkInf->GetNTrackRefs());*/
} else{
if(fDebugLevel>10) printf("Analysing Track References\n");
// Check if track is findable
Float_t xmin = 10000.0, xmax = 0.0;
Float_t ymin = 0.0, ymax = 0.0;
Float_t zmin = 0.0, zmax = 0.0;
Float_t lastx = 0.0, x = 0.0;
Int_t nLayers = 0;
/* trackRef = trkInf->GetTrackRef(0);*/
/* xmin = trackRef->LocalX(); xmax = trackRef->LocalX();
ymin = trackRef->LocalY(); ymax = trackRef->LocalY();
mom = trackRef->P();*/
Int_t *sector = new Int_t[trkInf->GetNTrackRefs()];
for(Int_t itr = 0; itr < trkInf->GetNTrackRefs(); itr++){
trackRef = trkInf->GetTrackRef(itr);
if(fDebugLevel>10) printf("%d. x[%f], y[%f], z[%f]\n", itr, trackRef->LocalX(), trackRef->LocalY(), trackRef->Z());
x = trackRef->LocalX();
if(x < 250. || x > 370.) continue; // Be Sure that we are inside TRD
sector[itr] = Int_t(trackRef->Alpha()/kAlpha);
if(x < xmin){
xmin = trackRef->LocalX();
ymin = trackRef->LocalY();
zmin = trackRef->Z();
mom = trackRef->P();
}
if(x > xmax){
xmax = trackRef->LocalX();
ymax = trackRef->LocalY();
zmax = trackRef->Z();
}
if(itr > 0){
Float_t dist = TMath::Abs(x - lastx);
if(fDebugLevel>10) printf("x = %f, lastx = %f, dist = %f\n", x, lastx, dist);
if(TMath::Abs(dist - 3.7) < 0.1) nLayers++; // ref(i+1) has to be larger than ref(i)
}
lastx = x;
}
// Apply cuts
Bool_t findable = kTRUE;
if(trkInf->GetNTrackRefs() > 2 && xmax > xmin){
if(mom < 0.55) findable = kFALSE; // momentum cut at 0.6
Double_t yangle = (ymax -ymin)/(xmax - xmin);
Double_t zangle = (zmax -zmin)/(xmax - xmin);
if(fDebugLevel>10) printf("track: y-Angle = %f, z-Angle = %f\n", yangle, zangle);
if(fDebugLevel>10) printf("nLayers = %d\n", nLayers);
if(TMath::ATan(TMath::Abs(yangle)) > 45.) findable = kFALSE;
if(TMath::ATan(TMath::Abs(zangle)) > 45.) findable = kFALSE;
if(nLayers < 4) findable = kFALSE;
if(!trkInf->IsPrimary()) findable = kFALSE;
Bool_t samesec = kTRUE;
for(Int_t iref = 1; iref < trkInf->GetNTrackRefs(); iref++)
if(sector[iref] != sector[0]) samesec = kFALSE;
if(!samesec) findable = kFALSE; // Discard all tracks which are passing more than one sector
if(fDebugLevel){
Double_t trackAngle = TMath::ATan(yangle);
Bool_t primary = trkInf->IsPrimary();
(*fDebugStream) << "NotFoundTrack"
<< "Momentum=" << mom
<< "trackAngle="<< trackAngle
<< "NLayers=" << nLayers
<< "Primary=" << primary
<< "\n";
}
}
else
findable = kFALSE;
delete[] sector;
if(findable){
momrej[nrejected] = mom;
labelsrej[nrejected++] = trkInf->GetLabel();
/* printf("Not Reconstructed: event %3d Tracks: MC[%d] ESD[%d] NRefs[%d]\n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), trkInf->GetLabel(), trkInf->GetTrackId(), trkInf->GetNTrackRefs());*/
}
}
}
for(Int_t itk = 0; itk < naccepted; itk++){
if(fDebugLevel > 2)printf("Accepted MC track: %d\n", labelsacc[itk]);
efficiency->Fill(momacc[itk], 1);
contamination->Fill(momacc[itk], 0);
}
Int_t nall = naccepted;
for(Int_t imis = 0; imis < nrejected; imis++){
Bool_t found = kFALSE;
for(Int_t ifound = 0; ifound < naccepted; ifound++){
if(labelsacc[ifound] == labelsrej[imis]){
found = kTRUE;
break;
}
}
if(!found){
efficiency->Fill(momrej[imis], 0);
contamination->Fill(momrej[imis], 0);
if(fDebugLevel > 2)printf("Rejected MC track: %d\n", labelsrej[imis]);
nall++;
}
}
//if(fDebugLevel>=1)
printf("%3d Tracks: MC[%3d] TRD[%3d | %5.2f%%] \n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), nall, naccepted, 1.E2*Float_t(naccepted)/Float_t(nall));
printf("%3d Tracks: ALL[%3d] DoubleCounted[%3d | %5.2f%%] \n", (Int_t)AliAnalysisManager::GetAnalysisManager()->GetCurrentEntry(), nall + ndoublecounted, ndoublecounted, 1.E2*Float_t(ndoublecounted)/Float_t(nall + ndoublecounted));
PostData(0, fContainer);
}
//_____________________________________________________________________________
void AliTRDtrackingEfficiencyCombined::Terminate(Option_t *)
{
//
// Termination
//
if(fDebugStream){
delete fDebugStream;
fDebugStream = 0x0;
fDebugLevel = 0;
}
fContainer = dynamic_cast<TObjArray*>(GetOutputData(0));
if (!fContainer) {
Printf("ERROR: list not available");
return;
}
/*TProfile *hEff = (TProfile*)fContainer->At(0);
TProfile *hEffCont = (TProfile*)fContainer->At(1);
Printf("Eff[%p] EffCont[%p]\n", (void*)hEff, (void*)hEffCont);
TCanvas *c2 = new TCanvas("c2","",800,400);
c2->Divide(2,1);
c2->cd(1);
hEff->DrawCopy("e1");
c2->cd(2);
hEffCont->DrawCopy("e1");*/
}
<|endoftext|> |
<commit_before>#include "YMain.h"
/** YDA **/
#include "YSpriteSheetManager.h"
#include "YPoint.h"
#include "YVector.h"
#include "YFileSystem.h"
/** Penguin **/
#include "Penguin.h"
#include "Fish.h"
#include "Crab.h"
/** C++ **/
#include <functional>
#include <vector>
#undef main
YSpriteSheetManager::kError loadResources(YSpriteSheetManager* a_manager)
{
typedef struct Sprites
{
std::string key;
std::string value;
} Sprite;
Sprite sprites[] = {
{"background", "tropical_island_day.png"},
{"penguin", "penguin.png"},
{"fish_blue", "fish_blue.png"},
{"fish_green", "fish_green.png"},
{"fish_red", "fish_red.png"},
{"crab_pink", "crab_pink.png"},
{"scuma", "scuma.png"}
};
int size = sizeof(sprites) / sizeof(Sprite);
bool success = true;
YSpriteSheetManager::kError result;
for (int i = 0; i < size; ++i)
{
std::string key = sprites[i].key;
std::string value = YFileSystem::getCurrentDir() + "\\" + sprites[i].value;
result = a_manager->add(key, value);
if (result != YSpriteSheetManager::NONE)
{
printf("Error on loading %s\n",
value.c_str());
success &= false;
}
}
return success == true ? YSpriteSheetManager::NONE : YSpriteSheetManager::LOADING_ERROR;
}
int main(int argc, char* argv[])
{
/** creates window **/
YMain* game = new YMain("Penguins - [email protected]",
640,
480);
/** loads resources **/
YSpriteSheetManager* spriteManager = new YSpriteSheetManager(game->renderer());
if (loadResources(spriteManager) != YSpriteSheetManager::NONE)
{
printf("Error on loading resources!\n");
return 1;
}
/** creates penguin **/
Penguin* penguin = new Penguin(spriteManager->findByName("penguin"),
YPoint(160.f, -10.f),
YFrame(0, 0, 8, 10, 10, 5));
penguin->firstFrame(0);
penguin->lastFrame(3);
/** creates fishes **/
std::vector<Fish*> fishes;
for (int i = 0; i < 5; ++i)
{
Fish *fish = NULL;
fish = new Fish(spriteManager->findByName("fish_blue"),
YPoint(100.f, 100.f),
YFrame(0, 0, 2, 10, 10, 15));
if (fish != NULL)
{
fish->pause(false);
fishes.push_back(fish);
}
}
YVector gravity(0, 15.0);
float ground = 410.f;
SDL_Rect islandRect;
islandRect.x = 150;
islandRect.y = ground;
islandRect.w = 230;
islandRect.h = 70;
/** creates crab **/
SDL_Texture* scuma = spriteManager->findByName("scuma");
Crab* crab = new Crab(spriteManager->findByName("crab_pink"),
YPoint(50.f, ground),
YFrame(0, 0, 2, 10, 11, 8),
ground,
scuma);
crab->pause(false);
crab->visible(false);
bool falling = true;
YMain::FunctionUpdate update = [&](SDL_Event* a_event)
{
if (falling == true)
{
YPoint position = penguin->position() + gravity;
if (position.y() < ground)
{
penguin->position(position);
penguin->currentFrame(8);
penguin->pause(true);
}
else
{
YPoint position(penguin->position().x(), ground);
penguin->position(position);
falling = false;
crab->start(islandRect);
}
}
else
{
penguin->pause(false);
if( a_event->type == SDL_MOUSEBUTTONDOWN )
{
penguin->startJump();
}
else if (a_event->type == SDL_MOUSEBUTTONUP)
{
penguin->endJump();
}
penguin->update();
crab->update();
}
};
YMain::FunctionRender render = [&](SDL_Renderer* a_renderer)
{
SDL_RenderCopy(a_renderer,
spriteManager->findByName("background"),
NULL,
NULL);
/** draw penguin **/
SDL_Rect nextFrameRect = penguin->nextFrame();
SDL_Rect dstRect = penguin->rect(4);
SDL_RenderCopy(a_renderer,
penguin->texture(),
&nextFrameRect,
&dstRect);
/** draw fish **/
Fish* fish = fishes.at(0);
if (fish != NULL)
{
SDL_Rect nextFishFrameRect = fish->nextFrame();
SDL_Rect dstFishRect = fish->rect(3);
SDL_RenderCopy(a_renderer,
fish->texture(),
&nextFishFrameRect,
&dstFishRect);
}
/** draw crab **/
nextFrameRect = crab->nextFrame();
dstRect = crab->rect(3);
SDL_RenderCopy(a_renderer,
crab->texture(),
&nextFrameRect,
&dstRect);
nextFrameRect = crab->scuma()->nextFrame();
dstRect = crab->scuma()->rect(3);
SDL_RenderCopy(a_renderer,
scuma,
&nextFrameRect,
&dstRect);
};
game->start(&update,
&render,
25,
5);
/** dealloc resources **/
for (Fish* fish: fishes)
{
if (fish != NULL)
{
delete fish;
}
}
delete game;
return 0;
}
<commit_msg>Choose separator based on OS Change updates of penguin position<commit_after>#include "YMain.h"
/** YDA **/
#include "YSpriteSheetManager.h"
#include "YPoint.h"
#include "YVector.h"
#include "YFileSystem.h"
/** Penguin **/
#include "Penguin.h"
#include "Fish.h"
#include "Crab.h"
/** C++ **/
#include <functional>
#include <vector>
#undef main
YSpriteSheetManager::kError loadResources(YSpriteSheetManager* a_manager)
{
typedef struct Sprites
{
std::string key;
std::string value;
} Sprite;
Sprite sprites[] = {
{"background", "tropical_island_day.png"},
{"penguin", "penguin.png"},
{"fish_blue", "fish_blue.png"},
{"fish_green", "fish_green.png"},
{"fish_red", "fish_red.png"},
{"crab_pink", "crab_pink.png"},
{"scuma", "scuma.png"}
};
int size = sizeof(sprites) / sizeof(Sprite);
bool success = true;
YSpriteSheetManager::kError result;
std::string kSeparator =
#ifdef _WIN32
"\\";
#else
"/";
#endif
for (int i = 0; i < size; ++i)
{
std::string key = sprites[i].key;
std::string value = YFileSystem::getCurrentDir() + kSeparator + sprites[i].value;
result = a_manager->add(key, value);
if (result != YSpriteSheetManager::NONE)
{
printf("Error on loading %s\n",
value.c_str());
success &= false;
}
}
return success == true ? YSpriteSheetManager::NONE : YSpriteSheetManager::LOADING_ERROR;
}
int main(int argc, char* argv[])
{
/** creates window **/
YMain* game = new YMain("Penguins - [email protected]",
640,
480);
/** loads resources **/
YSpriteSheetManager* spriteManager = new YSpriteSheetManager(game->renderer());
if (loadResources(spriteManager) != YSpriteSheetManager::NONE)
{
printf("Error on loading resources!\n");
return 1;
}
/** creates penguin **/
Penguin* penguin = new Penguin(spriteManager->findByName("penguin"),
YPoint(160.f, -10.f),
YFrame(0, 0, 8, 10, 10, 5));
penguin->firstFrame(0);
penguin->lastFrame(3);
/** creates fishes **/
std::vector<Fish*> fishes;
for (int i = 0; i < 5; ++i)
{
Fish *fish = NULL;
fish = new Fish(spriteManager->findByName("fish_blue"),
YPoint(100.f, 100.f),
YFrame(0, 0, 2, 10, 10, 15));
if (fish != NULL)
{
fish->pause(false);
fishes.push_back(fish);
}
}
YVector gravity(0, 15.0);
float ground = 410.f;
SDL_Rect islandRect;
islandRect.x = 150;
islandRect.y = ground;
islandRect.w = 230;
islandRect.h = 70;
/** creates crab **/
SDL_Texture* scuma = spriteManager->findByName("scuma");
Crab* crab = new Crab(spriteManager->findByName("crab_pink"),
YPoint(50.f, ground),
YFrame(0, 0, 2, 10, 11, 8),
ground,
scuma);
crab->pause(false);
crab->visible(false);
bool falling = true;
YMain::FunctionUpdate update = [&](SDL_Event* a_event)
{
if (falling == true)
{
YPoint position = penguin->position().add(gravity);
if (position.y() < ground)
{
penguin->position(position);
penguin->currentFrame(8);
penguin->pause(true);
}
else
{
YPoint position(penguin->position().x(), ground);
penguin->position(position);
crab->start(islandRect);
falling = false;
}
}
else
{
penguin->pause(false);
if( a_event->type == SDL_MOUSEBUTTONDOWN )
{
penguin->startJump();
}
else if (a_event->type == SDL_MOUSEBUTTONUP)
{
penguin->endJump();
}
penguin->update();
crab->update();
}
};
YMain::FunctionRender render = [&](SDL_Renderer* a_renderer)
{
SDL_RenderCopy(a_renderer,
spriteManager->findByName("background"),
NULL,
NULL);
/** draw penguin **/
SDL_Rect nextFrameRect = penguin->nextFrame();
SDL_Rect dstRect = penguin->rect(4);
SDL_RenderCopy(a_renderer,
penguin->texture(),
&nextFrameRect,
&dstRect);
/** draw fish **/
Fish* fish = fishes.at(0);
if (fish != NULL)
{
SDL_Rect nextFishFrameRect = fish->nextFrame();
SDL_Rect dstFishRect = fish->rect(3);
SDL_RenderCopy(a_renderer,
fish->texture(),
&nextFishFrameRect,
&dstFishRect);
}
/** draw crab **/
nextFrameRect = crab->nextFrame();
dstRect = crab->rect(3);
SDL_RenderCopy(a_renderer,
crab->texture(),
&nextFrameRect,
&dstRect);
nextFrameRect = crab->scuma()->nextFrame();
dstRect = crab->scuma()->rect(3);
SDL_RenderCopy(a_renderer,
scuma,
&nextFrameRect,
&dstRect);
};
game->start(&update,
&render,
25,
5);
/** dealloc resources **/
for (Fish* fish: fishes)
{
if (fish != NULL)
{
delete fish;
}
}
delete game;
return 0;
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else {
Node* cur;
if(data <= root->data) {
cur = insert(root->left, data);
root->left = cur;
} else {
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
/*The tree node has data, left child and right child
class Node {
int data;
Node* left;
Node* right;
};
*/
/*Node *lca(Node *root, int v1,int v2) {
if(root==NULL) // Corner case and base condition to check whether the root node is empty or not, if it returns NULL then it means that either the root node is empty or the nodes for which Lowest Common Ancestor are asked for are not there in the tree
return NULL;
if(v1<root->data && v2<root->data) // Recursive function to calculate the value of LCA of two nodes //
{
return lca(root->left,v1,v2); // Recursive call to the left subtree //
}
if(v1>root->data && v2>root->data)
{
return lca(root->right,v1,v2); // Recursive call to the right subtree//
}
return root;
}*/
/* Alternate way is to store the nodes encountered and check for node common in both path*/
Node *lca(Node *root, int v1, int v2){
if(!root){
return NULL;
}
auto copy = root;
vector<Node*> p1;
vector<Node*> p2;
while (v1 != copy->data) {
if (v1 > copy->data) {
p1.push_back(copy);
copy = copy->right;
}else {
p1.push_back(copy);
copy = copy->left;
}
}
p1.push_back(copy);
while (v2 != root->data) {
if (v2 > root->data) {
p2.push_back(root);
root = root->right;
}else {
p2.push_back(root);
root = root->left;
}
}
p2.push_back(root);
Node *low = NULL;
for (int i = 0; i < min((int)p1.size(), (int)p2.size()); i++) {
if(p1[i] == p2[i]){
low = p1[i];
}
}
return low;
}
void topView(Node*root){
if(!root){
return;
}
map<int, pair<int, int>> m;
fillMap(root, 0, 0, m);
for (auto i = m.begin(); i != i.end(); i++){
cout << i->second.first << " ";
}
}
void fillMap(Node *root, int lvl, int horizontalDistance, map<int, pair<int, int>> &m){
if(!root){
return;
}
if(!m.count(horizontalDistance)){
m[horizontalDistance] = make_pair(root->data, lvl);
}else if(m[d].second > lvl){
m[horizontalDistance] = make_pair(root->data, lvl);
}
fillMap(root->left, lvl+1, horizontalDistance-1, m);
fillMap(root->right, lvl+1, horizontalDistance+1, m);
}
};
/* int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
int v1, v2;
std::cin >> v1 >> v2;
Node *ans = myTree.lca(root, v1, v2);
std::cout << ans->data;
return 0;
}*/
// To run a test comment out the above main function and uncomment the following one//
int main() {
Solution myTree;
Node* root = NULL;
root = myTree.insert(root,4);
root = myTree.insert(root,2);
root = myTree.insert(root,3);
root = myTree.insert(root,1);
root = myTree.insert(root,7);
root = myTree.insert(root,6);
topView(root);
Node*ans = myTree.lca(root,1,7);
std::cout << ans->data;
return 0;
}
<commit_msg>Top view of binary tree<commit_after>#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else {
Node* cur;
if(data <= root->data) {
cur = insert(root->left, data);
root->left = cur;
} else {
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
/*The tree node has data, left child and right child
class Node {
int data;
Node* left;
Node* right;
};
*/
/*Node *lca(Node *root, int v1,int v2) {
if(root==NULL) // Corner case and base condition to check whether the root node is empty or not, if it returns NULL then it means that either the root node is empty or the nodes for which Lowest Common Ancestor are asked for are not there in the tree
return NULL;
if(v1<root->data && v2<root->data) // Recursive function to calculate the value of LCA of two nodes //
{
return lca(root->left,v1,v2); // Recursive call to the left subtree //
}
if(v1>root->data && v2>root->data)
{
return lca(root->right,v1,v2); // Recursive call to the right subtree//
}
return root;
}*/
/* Alternate way is to store the nodes encountered and check for node common in both path*/
Node *lca(Node *root, int v1, int v2){
if(!root){
return NULL;
}
auto copy = root;
vector<Node*> p1;
vector<Node*> p2;
while (v1 != copy->data) {
if (v1 > copy->data) {
p1.push_back(copy);
copy = copy->right;
}else {
p1.push_back(copy);
copy = copy->left;
}
}
p1.push_back(copy);
while (v2 != root->data) {
if (v2 > root->data) {
p2.push_back(root);
root = root->right;
}else {
p2.push_back(root);
root = root->left;
}
}
p2.push_back(root);
Node *low = NULL;
for (int i = 0; i < min((int)p1.size(), (int)p2.size()); i++) {
if(p1[i] == p2[i]){
low = p1[i];
}
}
return low;
}
};
void fillMap(Node *root, int lvl, int horizontalDistance, map<int, pair<int, int>> &m){
if(!root){
return;
}
if(!m.count(horizontalDistance)){
m[horizontalDistance] = make_pair(root->data, lvl);
}else if(m[horizontalDistance].second > lvl){
m[horizontalDistance] = make_pair(root->data, lvl);
}
fillMap(root->left, lvl+1, horizontalDistance-1, m);
fillMap(root->right, lvl+1, horizontalDistance+1, m);
}
void topView(Node*root){
if(!root){
return;
}
map<int, pair<int, int>> m;
fillMap(root, 0, 0, m);
for (auto i = m.begin(); i != m.end(); i++){
cout << i->second.first << " ";
}
}
/*
4
/ \
/ \
2 7
/ \ /
1 3 6
Nodes which are visible from top of the root node are considered for top view. In this 1 2 4 7 are visible
from top of root node.(Consider this as 3d model and nodes which are visible from top is our ans.)
*/
/* int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
int v1, v2;
std::cin >> v1 >> v2;
Node *ans = myTree.lca(root, v1, v2);
std::cout << ans->data;
return 0;
}*/
// To run a test comment out the above main function and uncomment the following one//
int main() {
Solution myTree;
Node* root = NULL;
root = myTree.insert(root,4);
root = myTree.insert(root,2);
root = myTree.insert(root,3);
root = myTree.insert(root,1);
root = myTree.insert(root,7);
root = myTree.insert(root,6);
topView(root);
// Node*ans = myTree.lca(root,1,7);
// std::cout << ans->data;
return 0;
}
<|endoftext|> |
<commit_before>// MenuTools.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "MenuTools.h"
#include "Startup.h"
#include "MenuCommon/Defines.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Single instance
Startup startup;
if(!startup.CreateJob())
{
return FALSE;
}
// Initialize global strings
LoadString(hInstance, BUILD(IDS_APP_TITLE), szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_MENUTOOLS, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable;
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MENUTOOLS));
// Main message loop:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MENUTOOLS));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MENUTOOLS);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
<commit_msg>Hide the main application window and removed unnecessary code.<commit_after>// MenuTools.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "MenuTools.h"
#include "Startup.h"
#include "MenuCommon/Defines.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
HWND hWnd; // current window handle
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Single instance
Startup startup;
if(!startup.CreateJob())
{
return FALSE;
}
// Initialize global strings
LoadString(hInstance, BUILD(IDS_APP_TITLE), szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_MENUTOOLS, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, SW_HIDE))
{
return FALSE;
}
// Main message loop:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MENUTOOLS));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, 0, 0, NULL, NULL, NULL, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "cast.h"
#include "database/schema.h"
#include "exception_xapian.h" // for CastError
#include "strings.hh" // for strings::format
MsgPack
Cast::cast(const MsgPack& obj)
{
if (obj.size() == 1) {
const auto str_key = obj.begin()->str();
switch (get_hash_type(str_key)) {
case HashType::INTEGER:
return integer(obj.at(str_key));
case HashType::POSITIVE:
return positive(obj.at(str_key));
case HashType::FLOAT:
return static_cast<double>(floating(obj.at(str_key)));
case HashType::BOOLEAN:
return boolean(obj.at(str_key));
case HashType::KEYWORD:
case HashType::TEXT:
case HashType::STRING:
return string(obj.at(str_key));
case HashType::UUID:
return uuid(obj.at(str_key));
case HashType::DATE:
case HashType::DATETIME:
return datetime(obj.at(str_key));
case HashType::TIME:
return time(obj.at(str_key));
case HashType::TIMEDELTA:
return timedelta(obj.at(str_key));
case HashType::EWKT:
return ewkt(obj.at(str_key));
case HashType::POINT:
case HashType::CIRCLE:
case HashType::CONVEX:
case HashType::POLYGON:
case HashType::CHULL:
case HashType::MULTIPOINT:
case HashType::MULTICIRCLE:
case HashType::MULTIPOLYGON:
case HashType::MULTICHULL:
case HashType::GEO_COLLECTION:
case HashType::GEO_INTERSECTION:
return obj;
default:
THROW(CastError, "Unknown cast type {}", str_key);
}
}
THROW(CastError, "Expected map with one element");
}
MsgPack
Cast::cast(FieldType type, const MsgPack& obj)
{
switch (type) {
case FieldType::integer:
return integer(obj);
case FieldType::positive:
return positive(obj);
case FieldType::floating:
return static_cast<double>(floating(obj));
case FieldType::boolean:
return boolean(obj);
case FieldType::keyword:
case FieldType::text:
case FieldType::string:
return string(obj);
case FieldType::uuid:
return uuid(obj);
case FieldType::date:
case FieldType::datetime:
return datetime(obj);
case FieldType::time:
return time(obj);
case FieldType::timedelta:
return timedelta(obj);
case FieldType::script:
if (obj.is_map()) {
return obj;
}
THROW(CastError, "Type {} cannot be cast to script", enum_name(obj.get_type()));
case FieldType::geo:
if (obj.is_map() || obj.is_string()) {
return obj;
}
THROW(CastError, "Type {} cannot be cast to geo", enum_name(obj.get_type()));
case FieldType::empty:
if (obj.is_string()) {
{
// Try like INTEGER.
int errno_save;
auto r = strict_stoll(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
{
// Try like POSITIVE.
int errno_save;
auto r = strict_stoull(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
{
// Try like FLOAT
int errno_save;
auto r = strict_stod(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
return obj;
}
[[fallthrough]];
default:
THROW(CastError, "Type {} cannot be cast", enum_name(obj.get_type()));
}
}
int64_t
Cast::integer(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stoll(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to integer", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<int64_t>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to integer", enum_name(obj.get_type()));
}
}
uint64_t
Cast::positive(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stoull(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to positive", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<uint64_t>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to positive", enum_name(obj.get_type()));
}
}
long double
Cast::floating(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stod(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to float", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<double>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to float", enum_name(obj.get_type()));
}
}
std::string
Cast::string(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return strings::format("{}", obj.u64());
case MsgPack::Type::NEGATIVE_INTEGER:
return strings::format("{}", obj.i64());
case MsgPack::Type::FLOAT:
return strings::format("{}", obj.f64());
case MsgPack::Type::STR:
return obj.str();
case MsgPack::Type::BOOLEAN:
return obj.boolean() ? "true" : "false";
default:
return obj.to_string();
}
}
bool
Cast::boolean(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64() != 0;
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64() != 0;
case MsgPack::Type::FLOAT:
return obj.f64() != 0;
case MsgPack::Type::STR: {
auto value = obj.str_view();
switch (value.size()) {
case 0:
return false;
case 1:
switch (value[0]) {
case '0':
case 'f':
case 'F':
return false;
// case '1':
// case 't':
// case 'T':
// return true;
}
break;
// case 4:
// switch (value[0]) {
// case 't':
// case 'T': {
// auto lower_value = strings::lower(value);
// if (lower_value == "true") {
// return true;
// }
// }
// }
// break;
case 5:
switch (value[0]) {
case 'f':
case 'F': {
auto lower_value = strings::lower(value);
if (lower_value == "false") {
return false;
}
}
}
break;
}
return true;
}
case MsgPack::Type::BOOLEAN:
return obj.boolean();
default:
THROW(CastError, "Type {} cannot be cast to boolean", enum_name(obj.get_type()));
}
}
std::string
Cast::uuid(const MsgPack& obj)
{
if (obj.is_string()) {
return obj.str();
}
THROW(CastError, "Type {} cannot be cast to uuid", enum_name(obj.get_type()));
}
MsgPack
Cast::datetime(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
case MsgPack::Type::MAP:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to datetime", enum_name(obj.get_type()));
}
}
MsgPack
Cast::time(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to time", enum_name(obj.get_type()));
}
}
MsgPack
Cast::timedelta(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to timedelta", enum_name(obj.get_type()));
}
}
std::string
Cast::ewkt(const MsgPack& obj)
{
if (obj.is_string()) {
return obj.str();
}
THROW(CastError, "Type {} cannot be cast to ewkt", enum_name(obj.get_type()));
}
Cast::HashType
Cast::get_hash_type(std::string_view cast_word)
{
static const auto _ = cast_hash;
return static_cast<HashType>(_.fhh(cast_word));
}
FieldType
Cast::get_field_type(std::string_view cast_word)
{
if (cast_word.empty() || cast_word[0] != reserved__) {
THROW(CastError, "Unknown cast type {}", repr(cast_word));
}
switch (get_hash_type(cast_word)) {
case HashType::INTEGER: return FieldType::integer;
case HashType::POSITIVE: return FieldType::positive;
case HashType::FLOAT: return FieldType::floating;
case HashType::BOOLEAN: return FieldType::boolean;
case HashType::KEYWORD: return FieldType::keyword;
case HashType::TEXT: return FieldType::text;
case HashType::STRING: return FieldType::string;
case HashType::UUID: return FieldType::uuid;
case HashType::DATETIME: return FieldType::datetime;
case HashType::TIME: return FieldType::time;
case HashType::TIMEDELTA: return FieldType::timedelta;
case HashType::EWKT: return FieldType::geo;
case HashType::POINT: return FieldType::geo;
case HashType::CIRCLE: return FieldType::geo;
case HashType::CONVEX: return FieldType::geo;
case HashType::POLYGON: return FieldType::geo;
case HashType::CHULL: return FieldType::geo;
case HashType::MULTIPOINT: return FieldType::geo;
case HashType::MULTICIRCLE: return FieldType::geo;
case HashType::MULTIPOLYGON: return FieldType::geo;
case HashType::MULTICHULL: return FieldType::geo;
case HashType::GEO_COLLECTION: return FieldType::geo;
case HashType::GEO_INTERSECTION: return FieldType::geo;
case HashType::CHAI: return FieldType::script;
default:
THROW(CastError, "Unknown cast type {}", repr(cast_word));
}
}
<commit_msg>Cast: Skip comments<commit_after>/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "cast.h"
#include "database/schema.h"
#include "exception_xapian.h" // for CastError
#include "reserved/reserved.h" // for is_comment
#include "strings.hh" // for strings::format
MsgPack
Cast::cast(const MsgPack& obj)
{
auto it = obj.begin();
auto it_e = obj.end();
for (; it != it_e; ++it) {
auto str_key = it->str_view();
if (is_comment(str_key)) {
continue;
}
switch (get_hash_type(str_key)) {
case HashType::INTEGER:
return integer(it.value());
case HashType::POSITIVE:
return positive(it.value());
case HashType::FLOAT:
return static_cast<double>(floating(it.value()));
case HashType::BOOLEAN:
return boolean(it.value());
case HashType::KEYWORD:
case HashType::TEXT:
case HashType::STRING:
return string(it.value());
case HashType::UUID:
return uuid(it.value());
case HashType::DATE:
case HashType::DATETIME:
return datetime(it.value());
case HashType::TIME:
return time(it.value());
case HashType::TIMEDELTA:
return timedelta(it.value());
case HashType::EWKT:
return ewkt(it.value());
case HashType::POINT:
case HashType::CIRCLE:
case HashType::CONVEX:
case HashType::POLYGON:
case HashType::CHULL:
case HashType::MULTIPOINT:
case HashType::MULTICIRCLE:
case HashType::MULTIPOLYGON:
case HashType::MULTICHULL:
case HashType::GEO_COLLECTION:
case HashType::GEO_INTERSECTION:
return obj;
default:
THROW(CastError, "Unknown cast type {}", str_key);
}
}
THROW(CastError, "Expected map with one valid cast");
}
MsgPack
Cast::cast(FieldType type, const MsgPack& obj)
{
switch (type) {
case FieldType::integer:
return integer(obj);
case FieldType::positive:
return positive(obj);
case FieldType::floating:
return static_cast<double>(floating(obj));
case FieldType::boolean:
return boolean(obj);
case FieldType::keyword:
case FieldType::text:
case FieldType::string:
return string(obj);
case FieldType::uuid:
return uuid(obj);
case FieldType::date:
case FieldType::datetime:
return datetime(obj);
case FieldType::time:
return time(obj);
case FieldType::timedelta:
return timedelta(obj);
case FieldType::script:
if (obj.is_map()) {
return obj;
}
THROW(CastError, "Type {} cannot be cast to script", enum_name(obj.get_type()));
case FieldType::geo:
if (obj.is_map() || obj.is_string()) {
return obj;
}
THROW(CastError, "Type {} cannot be cast to geo", enum_name(obj.get_type()));
case FieldType::empty:
if (obj.is_string()) {
{
// Try like INTEGER.
int errno_save;
auto r = strict_stoll(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
{
// Try like POSITIVE.
int errno_save;
auto r = strict_stoull(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
{
// Try like FLOAT
int errno_save;
auto r = strict_stod(&errno_save, obj.str_view());
if (errno_save == 0) {
return MsgPack(r);
}
}
return obj;
}
[[fallthrough]];
default:
THROW(CastError, "Type {} cannot be cast", enum_name(obj.get_type()));
}
}
int64_t
Cast::integer(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stoll(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to integer", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<int64_t>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to integer", enum_name(obj.get_type()));
}
}
uint64_t
Cast::positive(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stoull(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to positive", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<uint64_t>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to positive", enum_name(obj.get_type()));
}
}
long double
Cast::floating(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64();
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64();
case MsgPack::Type::FLOAT:
return obj.f64();
case MsgPack::Type::STR: {
int errno_save;
auto r = strict_stod(&errno_save, obj.str_view());
if (errno_save != 0) {
THROW(CastError, "Value {} cannot be cast to float", enum_name(obj.get_type()));
}
return r;
}
case MsgPack::Type::BOOLEAN:
return static_cast<double>(obj.boolean());
default:
THROW(CastError, "Type {} cannot be cast to float", enum_name(obj.get_type()));
}
}
std::string
Cast::string(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return strings::format("{}", obj.u64());
case MsgPack::Type::NEGATIVE_INTEGER:
return strings::format("{}", obj.i64());
case MsgPack::Type::FLOAT:
return strings::format("{}", obj.f64());
case MsgPack::Type::STR:
return obj.str();
case MsgPack::Type::BOOLEAN:
return obj.boolean() ? "true" : "false";
default:
return obj.to_string();
}
}
bool
Cast::boolean(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
return obj.u64() != 0;
case MsgPack::Type::NEGATIVE_INTEGER:
return obj.i64() != 0;
case MsgPack::Type::FLOAT:
return obj.f64() != 0;
case MsgPack::Type::STR: {
auto value = obj.str_view();
switch (value.size()) {
case 0:
return false;
case 1:
switch (value[0]) {
case '0':
case 'f':
case 'F':
return false;
// case '1':
// case 't':
// case 'T':
// return true;
}
break;
// case 4:
// switch (value[0]) {
// case 't':
// case 'T': {
// auto lower_value = strings::lower(value);
// if (lower_value == "true") {
// return true;
// }
// }
// }
// break;
case 5:
switch (value[0]) {
case 'f':
case 'F': {
auto lower_value = strings::lower(value);
if (lower_value == "false") {
return false;
}
}
}
break;
}
return true;
}
case MsgPack::Type::BOOLEAN:
return obj.boolean();
default:
THROW(CastError, "Type {} cannot be cast to boolean", enum_name(obj.get_type()));
}
}
std::string
Cast::uuid(const MsgPack& obj)
{
if (obj.is_string()) {
return obj.str();
}
THROW(CastError, "Type {} cannot be cast to uuid", enum_name(obj.get_type()));
}
MsgPack
Cast::datetime(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
case MsgPack::Type::MAP:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to datetime", enum_name(obj.get_type()));
}
}
MsgPack
Cast::time(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to time", enum_name(obj.get_type()));
}
}
MsgPack
Cast::timedelta(const MsgPack& obj)
{
switch (obj.get_type()) {
case MsgPack::Type::POSITIVE_INTEGER:
case MsgPack::Type::NEGATIVE_INTEGER:
case MsgPack::Type::FLOAT:
case MsgPack::Type::STR:
return obj;
default:
THROW(CastError, "Type {} cannot be cast to timedelta", enum_name(obj.get_type()));
}
}
std::string
Cast::ewkt(const MsgPack& obj)
{
if (obj.is_string()) {
return obj.str();
}
THROW(CastError, "Type {} cannot be cast to ewkt", enum_name(obj.get_type()));
}
Cast::HashType
Cast::get_hash_type(std::string_view cast_word)
{
static const auto _ = cast_hash;
return static_cast<HashType>(_.fhh(cast_word));
}
FieldType
Cast::get_field_type(std::string_view cast_word)
{
if (cast_word.empty() || cast_word[0] != reserved__) {
THROW(CastError, "Unknown cast type {}", repr(cast_word));
}
switch (get_hash_type(cast_word)) {
case HashType::INTEGER: return FieldType::integer;
case HashType::POSITIVE: return FieldType::positive;
case HashType::FLOAT: return FieldType::floating;
case HashType::BOOLEAN: return FieldType::boolean;
case HashType::KEYWORD: return FieldType::keyword;
case HashType::TEXT: return FieldType::text;
case HashType::STRING: return FieldType::string;
case HashType::UUID: return FieldType::uuid;
case HashType::DATETIME: return FieldType::datetime;
case HashType::TIME: return FieldType::time;
case HashType::TIMEDELTA: return FieldType::timedelta;
case HashType::EWKT: return FieldType::geo;
case HashType::POINT: return FieldType::geo;
case HashType::CIRCLE: return FieldType::geo;
case HashType::CONVEX: return FieldType::geo;
case HashType::POLYGON: return FieldType::geo;
case HashType::CHULL: return FieldType::geo;
case HashType::MULTIPOINT: return FieldType::geo;
case HashType::MULTICIRCLE: return FieldType::geo;
case HashType::MULTIPOLYGON: return FieldType::geo;
case HashType::MULTICHULL: return FieldType::geo;
case HashType::GEO_COLLECTION: return FieldType::geo;
case HashType::GEO_INTERSECTION: return FieldType::geo;
case HashType::CHAI: return FieldType::script;
default:
THROW(CastError, "Unknown cast type {}", repr(cast_word));
}
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* nested_loop_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/nested_loop_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/executor/nested_loop_join_executor.h"
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
assert(children_.size() == 2);
// Grab data from plan node.
const planner::NestedLoopJoinNode &node =
GetPlanNode<planner::NestedLoopJoinNode>();
// NOTE: predicate can be null for cartesian product
predicate_ = node.GetPredicate();
left_scan_start = true;
proj_info_ = node.GetProjInfo();
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_TRACE("********** Nested Loop Join executor :: 2 children \n");
bool right_scan_end = false;
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_TRACE("Did not get right tile \n");
right_scan_end = true;
}
if (right_scan_end == true) {
LOG_TRACE("Resetting scan for right tile \n");
children_[1]->Init();
if (children_[1]->Execute() == false) {
LOG_ERROR("Did not get right tile on second try\n");
return false;
}
}
LOG_TRACE("Got right tile \n");
if (left_scan_start == true || right_scan_end == true) {
left_scan_start = false;
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_TRACE("Did not get left tile \n");
return false;
}
LOG_TRACE("Got left tile \n");
} else {
LOG_TRACE("Already have left tile \n");
}
std::unique_ptr<LogicalTile> left_tile(children_[0]->GetOutput());
std::unique_ptr<LogicalTile> right_tile(children_[1]->GetOutput());
// Check the input logical tiles.
assert(left_tile.get() != nullptr);
assert(right_tile.get() != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile.get()->GetSchema();
auto right_tile_schema = right_tile.get()->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile.get()->GetPositionLists().size();
}
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile.get()->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile.get()->GetPositionLists();
auto right_tile_position_lists = right_tile.get()->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
size_t left_tile_row_count = left_tile_position_lists[0].size();
size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count);
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile.get()->GetColumnCount(), right_tile.get()->GetColumnCount());
LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count);
auto &direct_map_list = proj_info_->GetDirectMapList();
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = 0; left_tile_row_itr < left_tile_row_count;
left_tile_row_itr++) {
for (size_t right_tile_row_itr = 0;
right_tile_row_itr < right_tile_row_count; right_tile_row_itr++) {
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile.get(), left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile.get(), right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
continue;
}
}
// Insert a tuple into the output logical tile
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
position_lists[entry.first].push_back(
left_tile_position_lists[entry.second.second]
[left_tile_row_itr]);
} else {
position_lists[entry.first]
.push_back(right_tile_position_lists[entry.second.second]
[right_tile_row_itr]);
}
}
// First, copy the elements in left logical tile's tuple
}
}
for (auto col : position_lists) {
LOG_TRACE("col");
for (auto elm : col) {
(void)elm; // silent compiler
LOG_TRACE("elm: %u", elm);
}
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile.get()->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
std::vector<LogicalTile::ColumnInfo> NestedLoopJoinExecutor::BuildSchema(std::vector<LogicalTile::ColumnInfo> left,
std::vector<LogicalTile::ColumnInfo> right) {
assert(proj_info_->GetTargetList().size() == 0);
auto &direct_map_list = proj_info_->GetDirectMapList();
std::vector<LogicalTile::ColumnInfo> schema(direct_map_list.size());
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
assert(entry.second.second < left.size());
schema[entry.first] = left[entry.second.second];
} else {
assert(entry.second.second < right.size());
schema[entry.first] = right[entry.second.second];
}
}
return schema;
}
} // namespace executor
} // namespace peloton
<commit_msg>projection for join is working<commit_after>/*-------------------------------------------------------------------------
*
* nested_loop_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/nested_loop_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/executor/nested_loop_join_executor.h"
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
assert(children_.size() == 2);
// Grab data from plan node.
const planner::NestedLoopJoinNode &node =
GetPlanNode<planner::NestedLoopJoinNode>();
// NOTE: predicate can be null for cartesian product
predicate_ = node.GetPredicate();
left_scan_start = true;
proj_info_ = node.GetProjInfo();
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_INFO("********** Nested Loop Join executor :: 2 children \n");
bool right_scan_end = false;
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
right_scan_end = true;
}
if (right_scan_end == true) {
LOG_INFO("Resetting scan for right tile \n");
children_[1]->Init();
if (children_[1]->Execute() == false) {
LOG_ERROR("Did not get right tile on second try\n");
return false;
}
}
LOG_INFO("Got right tile \n");
if (left_scan_start == true || right_scan_end == true) {
left_scan_start = false;
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
LOG_INFO("Got left tile \n");
} else {
LOG_INFO("Already have left tile \n");
}
std::unique_ptr<LogicalTile> left_tile(children_[0]->GetOutput());
std::unique_ptr<LogicalTile> right_tile(children_[1]->GetOutput());
// Check the input logical tiles.
assert(left_tile.get() != nullptr);
assert(right_tile.get() != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile.get()->GetSchema();
auto right_tile_schema = right_tile.get()->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile.get()->GetPositionLists().size();
}
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile.get()->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile.get()->GetPositionLists();
auto right_tile_position_lists = right_tile.get()->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
size_t left_tile_row_count = left_tile_position_lists[0].size();
size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count);
LOG_INFO("left col count: %lu, right col count: %lu", left_tile.get()->GetColumnCount(), right_tile.get()->GetColumnCount());
LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count);
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = 0; left_tile_row_itr < left_tile_row_count;
left_tile_row_itr++) {
for (size_t right_tile_row_itr = 0;
right_tile_row_itr < right_tile_row_count; right_tile_row_itr++) {
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile.get(), left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile.get(), right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
continue;
}
}
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr]
[left_tile_row_itr]);
}
// Then, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(right_tile_position_lists[output_tile_column_itr]
[right_tile_row_itr]);
}
// First, copy the elements in left logical tile's tuple
}
}
for (auto col : position_lists) {
LOG_INFO("col");
for (auto elm : col) {
(void)elm; // silent compiler
LOG_INFO("elm: %u", elm);
}
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile.get()->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
std::vector<LogicalTile::ColumnInfo> NestedLoopJoinExecutor::BuildSchema(std::vector<LogicalTile::ColumnInfo> left,
std::vector<LogicalTile::ColumnInfo> right) {
assert(proj_info_->GetTargetList().size() == 0);
auto &direct_map_list = proj_info_->GetDirectMapList();
std::vector<LogicalTile::ColumnInfo> schema(direct_map_list.size());
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
assert(entry.second.second < left.size());
schema[entry.first] = left[entry.second.second];
} else {
assert(entry.second.second < right.size());
schema[entry.first] = right[entry.second.second];
}
}
return schema;
}
} // namespace executor
} // namespace peloton
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
//
// The goal of the program is to verify Burnside's lemma.
// Burnside's lemma is useful for counting things with symmetry.
//
// This program uses the lemma to compute the number of necklaces
// that can be formed by n = 5 beads with c = 10 colors such that
// all reflections and rotations of the same coloring is counted
// only once.
//
// Here is the key ingredient in the proof for the Burnside's lemma
//
// y in Orbit of x means y = g x, define a map from X to 2^G as follow:
//
// Map an element y to the set of group element g such that y = g x
// y = h x => y = g g^{-1} h x = g (g^{-1} h) x,
// Notice g^{-1} h x = g^{-1} g x = x, therefore for every group element
// y maps to, it is a coset element.
// On the other hand, every coset element is valid to be mapped to by y,
// Therefore we can map injectively an element in the orbit to a coset
// Therefore, the size of the orbit is the number of cosets = |G|/|Gx|
//
// Last but not least, if for each element, we add up the size its stablizer group,
// we get this:
//
// sum for each x, sum |Gx|
// = for each orbit, for each orbit element, sum |Gx|
// = for each orbit, sum |G|/|Gx| * |Gx|
// = for each orbit, sum |G|
// = number of orbit * |G|
//
// So this is the Burnside's lemma, you can calculate the number of orbits
// by summing the size of all the stablizer group and then divide it by the
// size of the group.
//
// Note that when we compute sum for each x, sum |Gx|, it is equivalent to
// flip to loop and ask, for each permutation, sum the number of configuration it fixes.
//
// This is where the Polya enumeration formula comes in. After we factor the
// permutation into disjoint cycles, we figure that in order for a configuration is to be fixed
// It must have the same color for all nodes within a cycle, therefore,
// for each cycle, we can make c choices for the color, and therefore we can count the number
// of configuration get fixed by a permutation without enumerating the configurations at all.
//
int main(int argc, char** argv)
{
vector<vector<int>> group_elements;
int n = 5;
int c = 10; // Polya's enumeration work much better when c is large - enumerating the configuration space is expensive
for (int offset = 0; offset < n; offset++)
{
vector<int> forward;
for (int i = 0; i < n; i++)
{
forward.push_back((i + offset) % n);
}
group_elements.push_back(forward);
vector<int> backward;
for (int i = 0; i < n; i++)
{
backward.push_back(((n - i) + offset) % n);
}
group_elements.push_back(backward);
}
bool burnside = true;
bool polya = true;
cout << "Begin Group" << endl;
for (size_t i = 0; i < group_elements.size(); i++)
{
for (size_t j = 0; j < group_elements[i].size(); j++)
{
cout << group_elements[i][j] << " ";
}
cout << endl;
}
cout << "End Group" << endl;
if (burnside)
{
cout << "Starting brute force verification of Burnside's lemma" << endl;
// This version of the code directly exercise the Burnside's lemma as is:
// This is inefficient because we have to go through all configurations
vector<int> config;
vector<int> mirror;
config.resize(n);
mirror.resize(n);
int all_stablizer_count = 0;
for (size_t k = 0; k < group_elements.size(); k++)
{
for (size_t j = 0; j < group_elements[k].size(); j++)
{
cout << group_elements[k][j] << " ";
}
int fixed_count = 0;
int seq = 0;
// A simple odometer to loop through all the config
while (true)
{
int cur = seq;
bool last = true;
for (int i = 0; i < n; i++)
{
config[i] = cur % c;
cur = cur / c;
last = last & (config[i] == c - 1);
}
// Here we have got a configuration - check if it is fixed by the current permutation
bool is_fixed = true;
for (int l = 0; is_fixed && l < n; l++)
{
is_fixed = is_fixed && (config[group_elements[k][l]] == config[l]);
}
if (is_fixed)
{
fixed_count++;
}
if (last)
{
break;
}
seq++;
}
cout << " fixes " << fixed_count << " configurations" << endl;
all_stablizer_count += fixed_count;
}
cout << all_stablizer_count << " " << group_elements.size() << endl;
}
if (polya)
{
cout << "Starting polya's enumeration formula" << endl;
int all_stablizer_count = 0;
for (size_t i = 0; i < group_elements.size(); i++)
{
vector<bool> used;
used.resize(group_elements[i].size());
for (size_t j = 0; j < used.size(); j++)
{
used[j] = false;
}
for (size_t j = 0; j < group_elements[i].size(); j++)
{
cout << group_elements[i][j] << " ";
}
int fixed_count = 1;
for (size_t j = 0; j < group_elements[i].size(); j++)
{
size_t k = j;
int element_in_cycle = 0;
cout << "(";
while (!used[k])
{
element_in_cycle++;
cout << k << " ";
used[k] = true;
k = group_elements[i][k];
}
cout << ") [" << element_in_cycle << "] ";
if (element_in_cycle != 0)
{
fixed_count *= c;
}
}
cout << " fixes " << fixed_count << " configurations" << endl;
all_stablizer_count += fixed_count;
}
cout << all_stablizer_count << " " << group_elements.size() << endl;
}
}<commit_msg>Tab to space<commit_after>#include <iostream>
#include <vector>
using namespace std;
//
// The goal of the program is to verify Burnside's lemma.
// Burnside's lemma is useful for counting things with symmetry.
//
// This program uses the lemma to compute the number of necklaces
// that can be formed by n = 5 beads with c = 10 colors such that
// all reflections and rotations of the same coloring is counted
// only once.
//
// Here is the key ingredient in the proof for the Burnside's lemma
//
// y in Orbit of x means y = g x, define a map from X to 2^G as follow:
//
// Map an element y to the set of group element g such that y = g x
// y = h x => y = g g^{-1} h x = g (g^{-1} h) x,
// Notice g^{-1} h x = g^{-1} g x = x, therefore for every group element
// y maps to, it is a coset element.
// On the other hand, every coset element is valid to be mapped to by y,
// Therefore we can map injectively an element in the orbit to a coset
// Therefore, the size of the orbit is the number of cosets = |G|/|Gx|
//
// Last but not least, if for each element, we add up the size its stablizer group,
// we get this:
//
// sum for each x, sum |Gx|
// = for each orbit, for each orbit element, sum |Gx|
// = for each orbit, sum |G|/|Gx| * |Gx|
// = for each orbit, sum |G|
// = number of orbit * |G|
//
// So this is the Burnside's lemma, you can calculate the number of orbits
// by summing the size of all the stablizer group and then divide it by the
// size of the group.
//
// Note that when we compute sum for each x, sum |Gx|, it is equivalent to
// flip to loop and ask, for each permutation, sum the number of configuration it fixes.
//
// This is where the Polya enumeration formula comes in. After we factor the
// permutation into disjoint cycles, we figure that in order for a configuration is to be fixed
// It must have the same color for all nodes within a cycle, therefore,
// for each cycle, we can make c choices for the color, and therefore we can count the number
// of configuration get fixed by a permutation without enumerating the configurations at all.
//
int main(int argc, char** argv)
{
vector<vector<int>> group_elements;
int n = 5;
int c = 10; // Polya's enumeration work much better when c is large - enumerating the configuration space is expensive
for (int offset = 0; offset < n; offset++)
{
vector<int> forward;
for (int i = 0; i < n; i++)
{
forward.push_back((i + offset) % n);
}
group_elements.push_back(forward);
vector<int> backward;
for (int i = 0; i < n; i++)
{
backward.push_back(((n - i) + offset) % n);
}
group_elements.push_back(backward);
}
bool burnside = true;
bool polya = true;
cout << "Begin Group" << endl;
for (size_t i = 0; i < group_elements.size(); i++)
{
for (size_t j = 0; j < group_elements[i].size(); j++)
{
cout << group_elements[i][j] << " ";
}
cout << endl;
}
cout << "End Group" << endl;
if (burnside)
{
cout << "Starting brute force verification of Burnside's lemma" << endl;
// This version of the code directly exercise the Burnside's lemma as is:
// This is inefficient because we have to go through all configurations
vector<int> config;
vector<int> mirror;
config.resize(n);
mirror.resize(n);
int all_stablizer_count = 0;
for (size_t k = 0; k < group_elements.size(); k++)
{
for (size_t j = 0; j < group_elements[k].size(); j++)
{
cout << group_elements[k][j] << " ";
}
int fixed_count = 0;
int seq = 0;
// A simple odometer to loop through all the config
while (true)
{
int cur = seq;
bool last = true;
for (int i = 0; i < n; i++)
{
config[i] = cur % c;
cur = cur / c;
last = last & (config[i] == c - 1);
}
// Here we have got a configuration - check if it is fixed by the current permutation
bool is_fixed = true;
for (int l = 0; is_fixed && l < n; l++)
{
is_fixed = is_fixed && (config[group_elements[k][l]] == config[l]);
}
if (is_fixed)
{
fixed_count++;
}
if (last)
{
break;
}
seq++;
}
cout << " fixes " << fixed_count << " configurations" << endl;
all_stablizer_count += fixed_count;
}
cout << all_stablizer_count << " " << group_elements.size() << endl;
}
if (polya)
{
cout << "Starting polya's enumeration formula" << endl;
int all_stablizer_count = 0;
for (size_t i = 0; i < group_elements.size(); i++)
{
vector<bool> used;
used.resize(group_elements[i].size());
for (size_t j = 0; j < used.size(); j++)
{
used[j] = false;
}
for (size_t j = 0; j < group_elements[i].size(); j++)
{
cout << group_elements[i][j] << " ";
}
int fixed_count = 1;
for (size_t j = 0; j < group_elements[i].size(); j++)
{
size_t k = j;
int element_in_cycle = 0;
cout << "(";
while (!used[k])
{
element_in_cycle++;
cout << k << " ";
used[k] = true;
k = group_elements[i][k];
}
cout << ") [" << element_in_cycle << "] ";
if (element_in_cycle != 0)
{
fixed_count *= c;
}
}
cout << " fixes " << fixed_count << " configurations" << endl;
all_stablizer_count += fixed_count;
}
cout << all_stablizer_count << " " << group_elements.size() << endl;
}
}<|endoftext|> |
<commit_before>// Time: O(max(r, c) * wlogw)
// Space: O(w^2)
class Solution {
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
priority_queue<node, vector<node>, greater<node>> heap;
unordered_set<int> visited;
heap.emplace(0, start);
while (!heap.empty()) {
int dist = 0;
vector<int> node;
tie(dist, node) = heap.top();
heap.pop();
if (visited.count(hash(maze, node))) {
continue;
}
if (node[0] == destination[0] &&
node[1] == destination[1]) {
return dist;
}
visited.emplace(hash(maze, node));
for (const auto& dir : dirs) {
int neighbor_dist = 0;
vector<int> neighbor;
tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);
heap.emplace(dist + neighbor_dist, neighbor);
}
}
return -1;
}
private:
using node = pair<int, vector<int>>;
node findNeighbor(const vector<vector<int>>& maze,
const vector<int>& node, const vector<int>& dir) {
vector<int> cur_node = node;
int dist = 0;
while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&
0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&
!maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {
cur_node[0] += dir[0];
cur_node[1] += dir[1];
++dist;
}
return {dist, cur_node};
}
int hash(const vector<vector<int>>& maze, const vector<int>& node) {
return node[0] * maze[0].size() + node[1];
}
};
<commit_msg>Update the-maze-ii.cpp<commit_after>// Time: O(max(r, c) * wlogw)
// Space: O(w)
class Solution {
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
priority_queue<node, vector<node>, greater<node>> heap;
unordered_set<int> visited;
heap.emplace(0, start);
while (!heap.empty()) {
int dist = 0;
vector<int> node;
tie(dist, node) = heap.top();
heap.pop();
if (visited.count(hash(maze, node))) {
continue;
}
if (node[0] == destination[0] &&
node[1] == destination[1]) {
return dist;
}
visited.emplace(hash(maze, node));
for (const auto& dir : dirs) {
int neighbor_dist = 0;
vector<int> neighbor;
tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);
heap.emplace(dist + neighbor_dist, neighbor);
}
}
return -1;
}
private:
using node = pair<int, vector<int>>;
node findNeighbor(const vector<vector<int>>& maze,
const vector<int>& node, const vector<int>& dir) {
vector<int> cur_node = node;
int dist = 0;
while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&
0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&
!maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {
cur_node[0] += dir[0];
cur_node[1] += dir[1];
++dist;
}
return {dist, cur_node};
}
int hash(const vector<vector<int>>& maze, const vector<int>& node) {
return node[0] * maze[0].size() + node[1];
}
};
<|endoftext|> |
<commit_before>// Time: O(logn)
// Space: O(1)
class Solution {
public:
/**
* @param num an integer
* @return true if num is an ugly number or false
*/
bool isUgly(int num) {
if (num == 0) {
return false;
}
for (const auto& i : {2, 3, 5}) {
while (num % i == 0) {
num /= i;
}
}
return num == 1;
}
};
<commit_msg>Update ugly-number.cpp<commit_after>// Time: O(logn) = O(1)
// Space: O(1)
class Solution {
public:
/**
* @param num an integer
* @return true if num is an ugly number or false
*/
bool isUgly(int num) {
if (num == 0) {
return false;
}
for (const auto& i : {2, 3, 5}) {
while (num % i == 0) {
num /= i;
}
}
return num == 1;
}
};
<|endoftext|> |
<commit_before>#include "mat4.h"
#include <memory.h>
#include <string.h>
namespace fd {
namespace core {
namespace math {
void mat4::LoadRows(__m128* rows) const {
rows[0] = _mm_set_ps(m[0 + 3 * 4], m[0 + 2 * 4], m[0 + 1 * 4], m[0 + 0 * 4]);
rows[1] = _mm_set_ps(m[1 + 3 * 4], m[1 + 2 * 4], m[1 + 1 * 4], m[1 + 0 * 4]);
rows[2] = _mm_set_ps(m[2 + 3 * 4], m[2 + 2 * 4], m[2 + 1 * 4], m[2 + 0 * 4]);
rows[3] = _mm_set_ps(m[3 + 3 * 4], m[3 + 2 * 4], m[3 + 1 * 4], m[3 + 0 * 4]);
}
void mat4::LoadColumns(__m128* columns) const {
columns[0] = _mm_loadu_ps(m);
columns[1] = _mm_loadu_ps(m+4);
columns[2] = _mm_loadu_ps(m+8);
columns[3] = _mm_loadu_ps(m+12);
}
mat4::mat4() {
memset(m, 0, sizeof(m));
}
mat4::mat4(float32 diagonal) : mat4() {
m[0 + 0 * 4] = diagonal;
m[1 + 1 * 4] = diagonal;
m[2 + 2 * 4] = diagonal;
m[3 + 3 * 4] = diagonal;
}
mat4 mat4::Scale(const vec3& v) {
mat4 m;
m.m[0 + 0 * 4] = v.x;
m.m[1 + 1 * 4] = v.y;
m.m[2 + 2 * 4] = v.z;
m.m[3 + 3 * 4] = 1;
return m;
}
mat4 mat4::Translate(const vec3& v) {
mat4 m(1);
m.m[3 + 0 * 4] = v.x;
m.m[3 + 1 * 4] = v.y;
m.m[3 + 2 * 4] = v.z;
return m;
}
mat4 mat4::Rotate(const vec3& v) {
mat4 x(1), y(1), z(1);
float32 xcos = cosf((float32)FD_TO_RADIANS_F(v.x));
float32 xsin = sinf((float32)FD_TO_RADIANS_F(v.x));
float32 ycos = cosf((float32)FD_TO_RADIANS_F(v.y));
float32 ysin = sinf((float32)FD_TO_RADIANS_F(v.y));
float32 zcos = cosf((float32)FD_TO_RADIANS_F(v.z));
float32 zsin = sinf((float32)FD_TO_RADIANS_F(v.z));
x.m[1 + 1 * 4] = xcos; x.m[1 + 2 * 4] = -xsin;
x.m[2 + 1 * 4] = xsin; x.m[2 + 2 * 4] = xcos;
y.m[0 + 0 * 4] = ycos; y.m[0 + 2 * 4] = -ysin;
y.m[2 + 0 * 4] = ysin; y.m[2 + 2 * 4] = ycos;
z.m[0 + 0 * 4] = zcos; z.m[0 + 1 * 4] = -zsin;
z.m[1 + 0 * 4] = zsin; z.m[1 + 1 * 4] = zcos;
return x * y * z;
}
mat4 mat4::Perspective(float32 aspect, float32 fov, float32 zNear, float32 zFar) {
mat4 m(1);
m.m[0 + 0 * 4] = 1.0f / (aspect * (tanh(fov * 0.5f)));
m.m[1 + 1 * 4] = 1.0f / (tanh(fov * 0.5f));
m.m[2 + 2 * 4] = zFar / (zFar - zNear);
m.m[3 + 2 * 4] = 1;
m.m[2 + 3 * 4] = -zNear * (zFar / (zFar - zNear));
m.m[3 + 3 * 4] = 0;
return m;
}
mat4 mat4::operator*(const mat4& r) const {
mat4 tmp;
__m128 row[4];
__m128 col[4];
r.LoadColumns(col);
LoadRows(row);
__m128 res;
for (uint_t y = 0; y < 4; y++) {
for (uint_t x = 0; x < 4; x++) {
res = _mm_mul_ps(row[x], col[y]);
tmp.m[x + y * 4] = M128(res, 0)+ M128(res, 1) + M128(res, 2) + M128(res, 3);
}
}
return tmp;
}
vec3 mat4::operator*(const vec3& v) const {
__m128 row[4];
__m128 col;
LoadRows(row);
col = _mm_set_ps(0, v.z, v.y, v.x);
__m128 res = _mm_mul_ps(row[0], col);
for (uint_t i = 1; i < 4; i++)
res = _mm_fmadd_ps(row[i], col, res);
return vec3(M128(res, 0), M128(res, 1), M128(res, 2));
}
vec4 mat4::operator*(const vec4& v) const {
__m128 row[4];
__m128 col;
LoadRows(row);
col = _mm_set_ps(v.w, v.z, v.y, v.x);
__m128 res = _mm_mul_ps(row[0], col);
for (uint_t i = 1; i < 4; i++)
res = _mm_fmadd_ps(row[i], col, res);
return vec4(M128(res, 0), M128(res, 1), M128(res, 2), M128(res, 3));
}
mat4 mat4::Transpose(mat4 m) {
float tmp[16];
memcpy(tmp, m.m, sizeof(m));
for (uint32 y = 0; y < 4; y++) {
for (uint32 x = 0; x < 4; x++) {
m.m[y + x * 4] = tmp[x + y * 4];
}
}
return m;
}
} } }<commit_msg>Fixed truncation warning<commit_after>#include "mat4.h"
#include <memory.h>
#include <string.h>
namespace fd {
namespace core {
namespace math {
void mat4::LoadRows(__m128* rows) const {
rows[0] = _mm_set_ps(m[0 + 3 * 4], m[0 + 2 * 4], m[0 + 1 * 4], m[0 + 0 * 4]);
rows[1] = _mm_set_ps(m[1 + 3 * 4], m[1 + 2 * 4], m[1 + 1 * 4], m[1 + 0 * 4]);
rows[2] = _mm_set_ps(m[2 + 3 * 4], m[2 + 2 * 4], m[2 + 1 * 4], m[2 + 0 * 4]);
rows[3] = _mm_set_ps(m[3 + 3 * 4], m[3 + 2 * 4], m[3 + 1 * 4], m[3 + 0 * 4]);
}
void mat4::LoadColumns(__m128* columns) const {
columns[0] = _mm_loadu_ps(m);
columns[1] = _mm_loadu_ps(m+4);
columns[2] = _mm_loadu_ps(m+8);
columns[3] = _mm_loadu_ps(m+12);
}
mat4::mat4() {
memset(m, 0, sizeof(m));
}
mat4::mat4(float32 diagonal) : mat4() {
m[0 + 0 * 4] = diagonal;
m[1 + 1 * 4] = diagonal;
m[2 + 2 * 4] = diagonal;
m[3 + 3 * 4] = diagonal;
}
mat4 mat4::Scale(const vec3& v) {
mat4 m;
m.m[0 + 0 * 4] = v.x;
m.m[1 + 1 * 4] = v.y;
m.m[2 + 2 * 4] = v.z;
m.m[3 + 3 * 4] = 1;
return m;
}
mat4 mat4::Translate(const vec3& v) {
mat4 m(1);
m.m[3 + 0 * 4] = v.x;
m.m[3 + 1 * 4] = v.y;
m.m[3 + 2 * 4] = v.z;
return m;
}
mat4 mat4::Rotate(const vec3& v) {
mat4 x(1), y(1), z(1);
float32 xcos = cosf((float32)FD_TO_RADIANS_F(v.x));
float32 xsin = sinf((float32)FD_TO_RADIANS_F(v.x));
float32 ycos = cosf((float32)FD_TO_RADIANS_F(v.y));
float32 ysin = sinf((float32)FD_TO_RADIANS_F(v.y));
float32 zcos = cosf((float32)FD_TO_RADIANS_F(v.z));
float32 zsin = sinf((float32)FD_TO_RADIANS_F(v.z));
x.m[1 + 1 * 4] = xcos; x.m[1 + 2 * 4] = -xsin;
x.m[2 + 1 * 4] = xsin; x.m[2 + 2 * 4] = xcos;
y.m[0 + 0 * 4] = ycos; y.m[0 + 2 * 4] = -ysin;
y.m[2 + 0 * 4] = ysin; y.m[2 + 2 * 4] = ycos;
z.m[0 + 0 * 4] = zcos; z.m[0 + 1 * 4] = -zsin;
z.m[1 + 0 * 4] = zsin; z.m[1 + 1 * 4] = zcos;
return x * y * z;
}
mat4 mat4::Perspective(float32 aspect, float32 fov, float32 zNear, float32 zFar) {
mat4 m(1);
m.m[0 + 0 * 4] = 1.0f / (aspect * ((float32)tanh(fov * 0.5f)));
m.m[1 + 1 * 4] = 1.0f / ((float32)tanh(fov * 0.5f));
m.m[2 + 2 * 4] = zFar / (zFar - zNear);
m.m[3 + 2 * 4] = 1;
m.m[2 + 3 * 4] = -zNear * (zFar / (zFar - zNear));
m.m[3 + 3 * 4] = 0;
return m;
}
mat4 mat4::operator*(const mat4& r) const {
mat4 tmp;
__m128 row[4];
__m128 col[4];
r.LoadColumns(col);
LoadRows(row);
__m128 res;
for (uint_t y = 0; y < 4; y++) {
for (uint_t x = 0; x < 4; x++) {
res = _mm_mul_ps(row[x], col[y]);
tmp.m[x + y * 4] = M128(res, 0)+ M128(res, 1) + M128(res, 2) + M128(res, 3);
}
}
return tmp;
}
vec3 mat4::operator*(const vec3& v) const {
__m128 row[4];
__m128 col;
LoadRows(row);
col = _mm_set_ps(0, v.z, v.y, v.x);
__m128 res = _mm_mul_ps(row[0], col);
for (uint_t i = 1; i < 4; i++)
res = _mm_fmadd_ps(row[i], col, res);
return vec3(M128(res, 0), M128(res, 1), M128(res, 2));
}
vec4 mat4::operator*(const vec4& v) const {
__m128 row[4];
__m128 col;
LoadRows(row);
col = _mm_set_ps(v.w, v.z, v.y, v.x);
__m128 res = _mm_mul_ps(row[0], col);
for (uint_t i = 1; i < 4; i++)
res = _mm_fmadd_ps(row[i], col, res);
return vec4(M128(res, 0), M128(res, 1), M128(res, 2), M128(res, 3));
}
mat4 mat4::Transpose(mat4 m) {
float tmp[16];
memcpy(tmp, m.m, sizeof(m));
for (uint32 y = 0; y < 4; y++) {
for (uint32 x = 0; x < 4; x++) {
m.m[y + x * 4] = tmp[x + y * 4];
}
}
return m;
}
} } }<|endoftext|> |
<commit_before><commit_msg>coverity#708715 unused member variable<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ActionMapTypesOOo.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:35:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_ACTIONMAPTYPESOOO_HXX
#define _XMLOFF_ACTIONMAPTYPESOOO_HXX
enum ActionMapTypesOOo
{
PROP_OOO_GRAPHIC_ATTR_ACTIONS,
PROP_OOO_GRAPHIC_ELEM_ACTIONS,
PROP_OOO_DRAWING_PAGE_ATTR_ACTIONS,
PROP_OOO_PAGE_LAYOUT_ATTR_ACTIONS,
PROP_OOO_HEADER_FOOTER_ATTR_ACTIONS,
PROP_OOO_TEXT_ATTR_ACTIONS,
PROP_OOO_TEXT_ELEM_ACTIONS,
PROP_OOO_PARAGRAPH_ATTR_ACTIONS,
PROP_OOO_PARAGRAPH_ELEM_ACTIONS,
PROP_OOO_SECTION_ATTR_ACTIONS,
PROP_OOO_TABLE_ATTR_ACTIONS,
PROP_OOO_TABLE_COLUMN_ATTR_ACTIONS,
PROP_OOO_TABLE_ROW_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ELEM_ACTIONS,
PROP_OOO_LIST_LEVEL_ATTR_ACTIONS,
PROP_OOO_CHART_ATTR_ACTIONS,
PROP_OOO_CHART_ELEM_ACTIONS,
MAX_OOO_PROP_ACTIONS,
OOO_STYLE_ACTIONS = MAX_OOO_PROP_ACTIONS,
OOO_FONT_DECL_ACTIONS,
OOO_SHAPE_ACTIONS,
OOO_CONNECTOR_ACTIONS,
OOO_INDEX_ENTRY_TAB_STOP_ACTIONS,
OOO_TAB_STOP_ACTIONS,
OOO_LINENUMBERING_ACTIONS,
OOO_FOOTNOTE_SEP_ACTIONS,
OOO_DROP_CAP_ACTIONS,
OOO_COLUMNS_ACTIONS,
OOO_TEXT_VALUE_TYPE_ACTIONS,
OOO_TABLE_VALUE_TYPE_ACTIONS,
OOO_PARA_ACTIONS,
OOO_STYLE_REF_ACTIONS,
OOO_MASTER_PAGE_ACTIONS,
OOO_ANNOTATION_ACTIONS,
OOO_CHANGE_INFO_ACTIONS,
OOO_FRAME_ELEM_ACTIONS,
OOO_FRAME_ATTR_ACTIONS,
OOO_BACKGROUND_IMAGE_ACTIONS,
OOO_DDE_CONNECTION_DECL_ACTIONS,
OOO_EVENT_ACTIONS,
OOO_FORM_CONTROL_ACTIONS,
OOO_FORM_COLUMN_ACTIONS,
OOO_FORM_PROP_ACTIONS,
OOO_XLINK_ACTIONS,
OOO_CONFIG_ITEM_SET_ACTIONS,
OOO_FORMULA_ACTIONS,
OOO_CHART_ACTIONS,
OOO_ERROR_MACRO_ACTIONS,
OOO_DDE_CONV_MODE_ACTIONS,
OOO_ALPHABETICAL_INDEX_MARK_ACTIONS,
OOO_DATAPILOT_MEMBER_ACTIONS,
OOO_DATAPILOT_LEVEL_ACTIONS,
OOO_SOURCE_SERVICE_ACTIONS,
OOO_DRAW_AREA_POLYGON_ACTIONS,
OOO_SCRIPT_ACTIONS,
MAX_OOO_ACTIONS
};
#endif // _XMLOFF_ACTIONMAPTYPESOOO_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.450); FILE MERGED 2008/03/31 16:28:48 rt 1.7.450.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: ActionMapTypesOOo.hxx,v $
* $Revision: 1.8 $
*
* 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 _XMLOFF_ACTIONMAPTYPESOOO_HXX
#define _XMLOFF_ACTIONMAPTYPESOOO_HXX
enum ActionMapTypesOOo
{
PROP_OOO_GRAPHIC_ATTR_ACTIONS,
PROP_OOO_GRAPHIC_ELEM_ACTIONS,
PROP_OOO_DRAWING_PAGE_ATTR_ACTIONS,
PROP_OOO_PAGE_LAYOUT_ATTR_ACTIONS,
PROP_OOO_HEADER_FOOTER_ATTR_ACTIONS,
PROP_OOO_TEXT_ATTR_ACTIONS,
PROP_OOO_TEXT_ELEM_ACTIONS,
PROP_OOO_PARAGRAPH_ATTR_ACTIONS,
PROP_OOO_PARAGRAPH_ELEM_ACTIONS,
PROP_OOO_SECTION_ATTR_ACTIONS,
PROP_OOO_TABLE_ATTR_ACTIONS,
PROP_OOO_TABLE_COLUMN_ATTR_ACTIONS,
PROP_OOO_TABLE_ROW_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ATTR_ACTIONS,
PROP_OOO_TABLE_CELL_ELEM_ACTIONS,
PROP_OOO_LIST_LEVEL_ATTR_ACTIONS,
PROP_OOO_CHART_ATTR_ACTIONS,
PROP_OOO_CHART_ELEM_ACTIONS,
MAX_OOO_PROP_ACTIONS,
OOO_STYLE_ACTIONS = MAX_OOO_PROP_ACTIONS,
OOO_FONT_DECL_ACTIONS,
OOO_SHAPE_ACTIONS,
OOO_CONNECTOR_ACTIONS,
OOO_INDEX_ENTRY_TAB_STOP_ACTIONS,
OOO_TAB_STOP_ACTIONS,
OOO_LINENUMBERING_ACTIONS,
OOO_FOOTNOTE_SEP_ACTIONS,
OOO_DROP_CAP_ACTIONS,
OOO_COLUMNS_ACTIONS,
OOO_TEXT_VALUE_TYPE_ACTIONS,
OOO_TABLE_VALUE_TYPE_ACTIONS,
OOO_PARA_ACTIONS,
OOO_STYLE_REF_ACTIONS,
OOO_MASTER_PAGE_ACTIONS,
OOO_ANNOTATION_ACTIONS,
OOO_CHANGE_INFO_ACTIONS,
OOO_FRAME_ELEM_ACTIONS,
OOO_FRAME_ATTR_ACTIONS,
OOO_BACKGROUND_IMAGE_ACTIONS,
OOO_DDE_CONNECTION_DECL_ACTIONS,
OOO_EVENT_ACTIONS,
OOO_FORM_CONTROL_ACTIONS,
OOO_FORM_COLUMN_ACTIONS,
OOO_FORM_PROP_ACTIONS,
OOO_XLINK_ACTIONS,
OOO_CONFIG_ITEM_SET_ACTIONS,
OOO_FORMULA_ACTIONS,
OOO_CHART_ACTIONS,
OOO_ERROR_MACRO_ACTIONS,
OOO_DDE_CONV_MODE_ACTIONS,
OOO_ALPHABETICAL_INDEX_MARK_ACTIONS,
OOO_DATAPILOT_MEMBER_ACTIONS,
OOO_DATAPILOT_LEVEL_ACTIONS,
OOO_SOURCE_SERVICE_ACTIONS,
OOO_DRAW_AREA_POLYGON_ACTIONS,
OOO_SCRIPT_ACTIONS,
MAX_OOO_ACTIONS
};
#endif // _XMLOFF_ACTIONMAPTYPESOOO_HXX
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.hpp>
#include <fclaw2d_partition.h>
#include <sc_statistics.h>
#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \
SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \
"Timer " #NAME " still running in amrreset"); \
sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \
(ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \
} while (0)
void amrreset(fclaw2d_domain_t **domain)
{
fclaw2d_domain_data_t *ddata = get_domain_data (*domain);
for(int i = 0; i < (*domain)->num_blocks; i++)
{
fclaw2d_block_t *block = (*domain)->blocks + i;
fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;
for(int j = 0; j < block->num_patches; j++)
{
fclaw2d_patch_t *patch = block->patches + j;
fclaw2d_patch_delete_cp(patch);
fclaw2d_patch_delete_data(patch);
#if 0
fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;
delete pdata->cp;
pdata->cp = NULL;
FCLAW2D_FREE (pdata);
patch->user = NULL;
#endif
++ddata->count_delete_clawpatch;
}
FCLAW2D_FREE (bd);
block->user = NULL;
}
fclaw2d_partition_delete(domain);
#if 0
// Free old parallel ghost patch data structure, must exist by construction.
delete_ghost_patches(*domain);
fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain);
fclaw2d_domain_free_after_exchange (*domain, e_old);
#endif
/* Output memory discrepancy for the ClawPatch */
if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {
printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n",
(*domain)->mpirank,
ddata->count_set_clawpatch, ddata->count_delete_clawpatch);
}
/* Evaluate timers if this domain has not been superseded yet. */
if (ddata->is_latest_domain) {
sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);
FCLAW2D_STATS_SET (stats, ddata, INIT);
FCLAW2D_STATS_SET (stats, ddata, REGRID);
FCLAW2D_STATS_SET (stats, ddata, OUTPUT);
FCLAW2D_STATS_SET (stats, ddata, CHECK);
FCLAW2D_STATS_SET (stats, ddata, ADVANCE);
FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);
FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);
FCLAW2D_STATS_SET (stats, ddata, WALLTIME);
sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],
ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -
(ddata->timers[FCLAW2D_TIMER_INIT].cumulative +
ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +
ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +
ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +
ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +
ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),
"UNACCOUNTED");
sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);
sc_stats_print (sc_package_id, SC_LP_PRODUCTION, FCLAW2D_TIMER_COUNT,
stats, 1, 0);
SC_GLOBAL_PRODUCTIONF ("Procs %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].average,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].average,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].average);
SC_GLOBAL_PRODUCTIONF ("Max/P %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].max,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].max,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].max);
}
delete_domain_data(*domain); // Delete allocated pointers to set of functions.
fclaw2d_domain_destroy(*domain);
*domain = NULL;
}
<commit_msg>Lowered log level for timing stats output at end of run<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.hpp>
#include <fclaw2d_partition.h>
#include <sc_statistics.h>
#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \
SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \
"Timer " #NAME " still running in amrreset"); \
sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \
(ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \
} while (0)
void amrreset(fclaw2d_domain_t **domain)
{
fclaw2d_domain_data_t *ddata = get_domain_data (*domain);
for(int i = 0; i < (*domain)->num_blocks; i++)
{
fclaw2d_block_t *block = (*domain)->blocks + i;
fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;
for(int j = 0; j < block->num_patches; j++)
{
fclaw2d_patch_t *patch = block->patches + j;
fclaw2d_patch_delete_cp(patch);
fclaw2d_patch_delete_data(patch);
#if 0
fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;
delete pdata->cp;
pdata->cp = NULL;
FCLAW2D_FREE (pdata);
patch->user = NULL;
#endif
++ddata->count_delete_clawpatch;
}
FCLAW2D_FREE (bd);
block->user = NULL;
}
fclaw2d_partition_delete(domain);
#if 0
// Free old parallel ghost patch data structure, must exist by construction.
delete_ghost_patches(*domain);
fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain);
fclaw2d_domain_free_after_exchange (*domain, e_old);
#endif
/* Output memory discrepancy for the ClawPatch */
if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {
printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n",
(*domain)->mpirank,
ddata->count_set_clawpatch, ddata->count_delete_clawpatch);
}
/* Evaluate timers if this domain has not been superseded yet. */
if (ddata->is_latest_domain) {
sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);
FCLAW2D_STATS_SET (stats, ddata, INIT);
FCLAW2D_STATS_SET (stats, ddata, REGRID);
FCLAW2D_STATS_SET (stats, ddata, OUTPUT);
FCLAW2D_STATS_SET (stats, ddata, CHECK);
FCLAW2D_STATS_SET (stats, ddata, ADVANCE);
FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);
FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);
FCLAW2D_STATS_SET (stats, ddata, WALLTIME);
sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],
ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -
(ddata->timers[FCLAW2D_TIMER_INIT].cumulative +
ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +
ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +
ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +
ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +
ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),
"UNACCOUNTED");
sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);
sc_stats_print (sc_package_id, SC_LP_ESSENTIAL, FCLAW2D_TIMER_COUNT,
stats, 1, 0);
SC_GLOBAL_ESSENTIALF ("Procs %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].average,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].average,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].average);
SC_GLOBAL_ESSENTIALF ("Max/P %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].max,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].max,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].max);
}
delete_domain_data(*domain); // Delete allocated pointers to set of functions.
fclaw2d_domain_destroy(*domain);
*domain = NULL;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.