text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Changed mail -> messages where appropriate. I didn't change the "mail"s in the DnD configuration as those will be removed anyway.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/arena.h"
#include "util/random.h"
#include "util/testharness.h"
namespace leveldb {
class ArenaTest { };
TEST(ArenaTest, Empty) {
Arena arena;
}
TEST(ArenaTest, Simple) {
std::vector<std::pair<size_t, char*> > allocated;
Arena arena;
const int N = 100000;
size_t bytes = 0;
Random rnd(301);
for (int i = 0; i < N; i++) {
size_t s;
if (i % (N / 10) == 0) {
s = i;
} else {
s = rnd.OneIn(4000) ? rnd.Uniform(6000) :
(rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20));
}
if (s == 0) {
// Our arena disallows size 0 allocations.
s = 1;
}
char* r;
if (rnd.OneIn(10)) {
r = arena.AllocateAligned(s);
} else {
r = arena.Allocate(s);
}
for (size_t b = 0; b < s; b++) {
// Fill the "i"th allocation with a known bit pattern
r[b] = i % 256;
}
bytes += s;
allocated.push_back(std::make_pair(s, r));
ASSERT_GE(arena.MemoryUsage(), bytes);
if (i > N/10) {
ASSERT_LE(arena.MemoryUsage(), bytes * 1.10);
}
}
for (size_t i = 0; i < allocated.size(); i++) {
size_t num_bytes = allocated[i].first;
const char* p = allocated[i].second;
for (size_t b = 0; b < num_bytes; b++) {
// Check the "i"th allocation for the known bit pattern
ASSERT_EQ(int(p[b]) & 0xff, i % 256);
}
}
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<commit_msg>Update arena_test.cc<commit_after>// Copyright (c) 2017 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/arena.h"
#include "util/random.h"
#include "util/testharness.h"
namespace leveldb {
class ArenaTest { };
TEST(ArenaTest, Empty) {
Arena arena;
}
TEST(ArenaTest, Simple) {
std::vector<std::pair<size_t, char*> > allocated;
Arena arena;
const int N = 100000;
size_t bytes = 0;
Random rnd(301);
for (int i = 0; i < N; i++) {
size_t s;
if (i % (N / 10) == 0) {
s = i;
} else {
s = rnd.OneIn(4000) ? rnd.Uniform(6000) :
(rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20));
}
if (s == 0) {
// Our arena disallows size 0 allocations.
s = 1;
}
char* r;
if (rnd.OneIn(10)) {
r = arena.AllocateAligned(s);
} else {
r = arena.Allocate(s);
}
for (size_t b = 0; b < s; b++) {
// Fill the "i"th allocation with a known bit pattern
r[b] = i % 256;
}
bytes += s;
allocated.push_back(std::make_pair(s, r));
ASSERT_GE(arena.MemoryUsage(), bytes);
if (i > N/10) {
ASSERT_LE(arena.MemoryUsage(), bytes * 1.10);
}
}
for (size_t i = 0; i < allocated.size(); i++) {
size_t num_bytes = allocated[i].first;
const char* p = allocated[i].second;
for (size_t b = 0; b < num_bytes; b++) {
// Check the "i"th allocation for the known bit pattern
ASSERT_EQ(int(p[b]) & 0xff, i % 256);
}
}
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<|endoftext|> |
<commit_before>#include "LiveMediaExtPch.h"
#include <LiveMediaExt/LiveH264Subsession.h>
#include <LiveMediaExt/LiveDeviceSource.h>
#include <LiveMediaExt/LiveH264VideoDeviceSource.h>
#include <H264VideoRTPSink.hh>
#include "Base64.hh"
#include "H264VideoStreamDiscreteFramer.hh"
namespace lme
{
LiveH264Subsession::LiveH264Subsession( UsageEnvironment& env, LiveRtspServer& rParent,
const unsigned uiChannelId, unsigned uiSourceId,
const std::string& sSessionName,
const std::string& sSps, const std::string& sPps,
IRateAdaptationFactory* pFactory,
IRateController* pGlobalRateControl)
:LiveMediaSubsession(env, rParent, uiChannelId, uiSourceId, sSessionName, true, 1, pFactory, pGlobalRateControl),
m_sSps(sSps),
m_sPps(sPps),
fAuxSDPLine(NULL),
fFmtpSDPLine(NULL)
{
VLOG(2) << "LiveH264Subsession() SPS: " << m_sSps << " PPS: " << m_sPps;
}
LiveH264Subsession::~LiveH264Subsession()
{
delete[] fAuxSDPLine;
delete[] fFmtpSDPLine;
}
FramedSource* LiveH264Subsession::createSubsessionSpecificSource(unsigned clientSessionId,
IMediaSampleBuffer* pMediaSampleBuffer,
IRateAdaptationFactory* pRateAdaptationFactory,
IRateController* pRateControl)
{
FramedSource* pLiveDeviceSource = LiveH264VideoDeviceSource::createNew(envir(), clientSessionId, this, m_sSps, m_sPps,
pMediaSampleBuffer, pRateAdaptationFactory, pRateControl);
// wrap framer around our device source
H264VideoStreamDiscreteFramer* pFramer = H264VideoStreamDiscreteFramer::createNew(envir(), pLiveDeviceSource);
return pFramer;
}
void LiveH264Subsession::setEstimatedBitRate(unsigned& estBitrate)
{
// Set estimated session band width
estBitrate = 1000;
}
RTPSink* LiveH264Subsession::createSubsessionSpecificRTPSink( Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource )
{
// HACKERY
std::string sPropParameterSets = m_sSps + "," + m_sPps;
H264VideoRTPSink* pSink = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, sPropParameterSets.c_str());
pSink->setPacketSizes(1000, 1400);
return pSink;
}
char const* LiveH264Subsession::getAuxSDPLine( RTPSink* rtpSink, FramedSource* inputSource )
{
const char* sps = m_sSps.c_str();
unsigned spsSize = m_sSps.length();
const char* pps = m_sPps.c_str();
unsigned ppsSize = m_sPps.length();
u_int32_t profile_level_id;
if (spsSize < 4) { // sanity check
profile_level_id = 0;
} else {
profile_level_id = (sps[1]<<16)|(sps[2]<<8)|sps[3]; // profile_idc|constraint_setN_flag|level_idc
}
// The parameter sets are base64 encoded already
// Set up the "a=fmtp:" SDP line for this stream:
char const* fmtpFmt =
"a=fmtp:%d packetization-mode=1"
";profile-level-id=%06X"
";sprop-parameter-sets=%s,%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt)
+ 3 /* max char len */
+ 6 /* 3 bytes in hex */
+ spsSize + ppsSize;
char* fmtp = new char[fmtpFmtSize];
sprintf(fmtp, fmtpFmt,
rtpSink->rtpPayloadType(),
profile_level_id,
sps, pps);
delete[] fFmtpSDPLine; fFmtpSDPLine = fmtp;
return fFmtpSDPLine;
}
} // lme
<commit_msg>Reduced est bitrate to 500kbps<commit_after>#include "LiveMediaExtPch.h"
#include <LiveMediaExt/LiveH264Subsession.h>
#include <LiveMediaExt/LiveDeviceSource.h>
#include <LiveMediaExt/LiveH264VideoDeviceSource.h>
#include <H264VideoRTPSink.hh>
#include "Base64.hh"
#include "H264VideoStreamDiscreteFramer.hh"
namespace lme
{
LiveH264Subsession::LiveH264Subsession( UsageEnvironment& env, LiveRtspServer& rParent,
const unsigned uiChannelId, unsigned uiSourceId,
const std::string& sSessionName,
const std::string& sSps, const std::string& sPps,
IRateAdaptationFactory* pFactory,
IRateController* pGlobalRateControl)
:LiveMediaSubsession(env, rParent, uiChannelId, uiSourceId, sSessionName, true, 1, pFactory, pGlobalRateControl),
m_sSps(sSps),
m_sPps(sPps),
fAuxSDPLine(NULL),
fFmtpSDPLine(NULL)
{
VLOG(2) << "LiveH264Subsession() SPS: " << m_sSps << " PPS: " << m_sPps;
}
LiveH264Subsession::~LiveH264Subsession()
{
delete[] fAuxSDPLine;
delete[] fFmtpSDPLine;
}
FramedSource* LiveH264Subsession::createSubsessionSpecificSource(unsigned clientSessionId,
IMediaSampleBuffer* pMediaSampleBuffer,
IRateAdaptationFactory* pRateAdaptationFactory,
IRateController* pRateControl)
{
FramedSource* pLiveDeviceSource = LiveH264VideoDeviceSource::createNew(envir(), clientSessionId, this, m_sSps, m_sPps,
pMediaSampleBuffer, pRateAdaptationFactory, pRateControl);
// wrap framer around our device source
H264VideoStreamDiscreteFramer* pFramer = H264VideoStreamDiscreteFramer::createNew(envir(), pLiveDeviceSource);
return pFramer;
}
void LiveH264Subsession::setEstimatedBitRate(unsigned& estBitrate)
{
// Set estimated bitrate in kbps
estBitrate = 500;
}
RTPSink* LiveH264Subsession::createSubsessionSpecificRTPSink( Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource )
{
// HACKERY
std::string sPropParameterSets = m_sSps + "," + m_sPps;
H264VideoRTPSink* pSink = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, sPropParameterSets.c_str());
pSink->setPacketSizes(1000, 1400);
return pSink;
}
char const* LiveH264Subsession::getAuxSDPLine( RTPSink* rtpSink, FramedSource* inputSource )
{
const char* sps = m_sSps.c_str();
unsigned spsSize = m_sSps.length();
const char* pps = m_sPps.c_str();
unsigned ppsSize = m_sPps.length();
u_int32_t profile_level_id;
if (spsSize < 4) { // sanity check
profile_level_id = 0;
} else {
profile_level_id = (sps[1]<<16)|(sps[2]<<8)|sps[3]; // profile_idc|constraint_setN_flag|level_idc
}
// The parameter sets are base64 encoded already
// Set up the "a=fmtp:" SDP line for this stream:
char const* fmtpFmt =
"a=fmtp:%d packetization-mode=1"
";profile-level-id=%06X"
";sprop-parameter-sets=%s,%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt)
+ 3 /* max char len */
+ 6 /* 3 bytes in hex */
+ spsSize + ppsSize;
char* fmtp = new char[fmtpFmtSize];
sprintf(fmtp, fmtpFmt,
rtpSink->rtpPayloadType(),
profile_level_id,
sps, pps);
delete[] fFmtpSDPLine; fFmtpSDPLine = fmtp;
return fFmtpSDPLine;
}
} // lme
<|endoftext|> |
<commit_before>/**
\file ll_translation_control.hpp
\brief Defines class LLTranslationControl and defines its methods.
\author Radek Vít
*/
#ifndef CTF_LL_TRANSLATION_CONTROL_H
#define CTF_LL_TRANSLATION_CONTROL_H
#include "translation_control.hpp"
namespace ctf {
/**
\brief Implements LL top down translation control.
*/
class LLTranslationControl : public TranslationControl {
protected:
/**
\brief Empty set for each nonterminal.
*/
vector<bool> empty_;
/**
\brief First set for each nonterminal.
*/
vector<vector<Symbol>> first_;
/**
\brief Follow set for each nonterminal.
*/
vector<vector<Symbol>> follow_;
/**
\brief Predict set for each nonterminal.
*/
vector<vector<Symbol>> predict_;
/**
\brief LL table used to control the translation.
*/
LLTable llTable_;
/**
\brief Error message string.
*/
string errorString_;
/**
\brief The last expanded nonterminal.
*/
Symbol lastNonterminal_ = Symbol::eof();
/**
Creates all predictive sets and creates a new LL table.
*/
void create_ll_table() {
create_empty();
create_first();
create_follow();
create_predict();
llTable_ = LLTable(*translationGrammar_, predict_);
}
/**
\brief Creates Empty set for each nonterminal.
Empty is true if a series of productions from the nonterminal can result in an
empty string.
*/
void create_empty() {
const TranslationGrammar &tg = *translationGrammar_;
empty_ = vector<bool>(tg.nonterminals().size(), false);
for (auto &r : tg.rules()) {
if (r.input().size() == 0) {
empty_[tg.nonterminal_index(r.nonterminal())] = true;
}
}
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
bool isempty = true;
for (auto &s : r.input()) {
switch (s.type()) {
case Symbol::Type::TERMINAL:
isempty = false;
break;
case Symbol::Type::NONTERMINAL:
if (empty_[tg.nonterminal_index(s)] == false) {
isempty = false;
}
break;
default:
break;
}
}
if (isempty) {
if (!empty_[tg.nonterminal_index(r.nonterminal())]) {
changed = true;
empty_[tg.nonterminal_index(r.nonterminal())] = true;
}
}
}
} while (changed);
}
/**
\brief Creates First set for each nonterminal.
First contains all characters that can be at the first position of any string
derived from this nonterminal.
*/
void create_first() {
const TranslationGrammar &tg = *translationGrammar_;
first_ = {tg.nonterminals().size(), vector<Symbol>{}};
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
size_t i = tg.nonterminal_index(r.nonterminal());
bool empty = true;
for (auto &symbol : r.input()) {
if (!empty)
break;
size_t nonterm_i;
switch (symbol.type()) {
case Symbol::Type::NONTERMINAL:
nonterm_i = tg.nonterminal_index(symbol);
if (modify_set(first_[i], first_[nonterm_i]))
changed = true;
empty = empty_[nonterm_i];
break;
case Symbol::Type::TERMINAL:
if (modify_set(first_[i], vector<Symbol>({symbol})))
changed = true;
empty = false;
break;
default:
break;
}
}
}
} while (changed);
}
/**
\brief Creates Follow set for each nonterminal.
Follow contains all characters that may follow that nonterminal in a
sentential form from the starting nonterminal.
*/
void create_follow() {
const TranslationGrammar &tg = *translationGrammar_;
follow_ = {tg.nonterminals().size(), vector<Symbol>{}};
follow_[tg.nonterminal_index(tg.starting_symbol())].push_back(
Symbol::eof());
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
// index of origin nonterminal
size_t i = tg.nonterminal_index(r.nonterminal());
/* empty set of all symbols to the right of the current one */
bool compoundEmpty = true;
/* first set of all symbols to the right of the current symbol */
vector<Symbol> compoundFirst;
/* track symbols from back */
for (auto &s : reverse(r.input())) {
// index of nonterminal in input string, only valid with
// nonterminal symbol
size_t ti = 0;
switch (s.type()) {
case Symbol::Type::NONTERMINAL:
ti = tg.nonterminal_index(s);
if (modify_set(follow_[ti], compoundFirst))
changed = true;
if (compoundEmpty && modify_set(follow_[ti], follow_[i]))
changed = true;
break;
default:
break;
}
/* if empty = false */
if (s.type() != Symbol::Type::NONTERMINAL ||
!empty_[tg.nonterminal_index(s)]) {
compoundEmpty = false;
switch (s.type()) {
case Symbol::Type::NONTERMINAL:
compoundFirst = first_[ti];
break;
case Symbol::Type::TERMINAL:
compoundFirst = {s};
break;
default:
break;
}
}
/* empty = true, nonterminal*/
else {
modify_set(compoundFirst, first_[ti]);
}
} // for all reverse input
} // for all rules
} while (changed);
}
/**
\brief Creates Predict set for each nonterminal.
Predict contains all Terminals that may be the first terminal read in a
sentential form from that nonterminal.
*/
void create_predict() {
predict_.clear();
const TranslationGrammar &tg = *translationGrammar_;
for (auto &r : tg.rules()) {
vector<Symbol> compoundFirst;
vector<Symbol> rfollow = follow_[tg.nonterminal_index(r.nonterminal())];
bool compoundEmpty = true;
for (auto &s : reverse(r.input())) {
size_t i;
switch (s.type()) {
case Symbol::Type::TERMINAL:
compoundEmpty = false;
compoundFirst = vector<Symbol>({s});
break;
case Symbol::Type::NONTERMINAL:
i = tg.nonterminal_index(s);
if (!empty_[i]) {
compoundEmpty = false;
compoundFirst = first_[i];
} else {
modify_set(compoundFirst, first_[i]);
}
default:
break;
}
}
predict_.push_back(compoundFirst);
if (compoundEmpty) {
modify_set(predict_.back(), rfollow);
}
} // for all rules
}
/**
\brief Creates iterator attribute actions for incoming terminals.
\param[in] obegin Iterator to the first Symbol of the output of the applied
Rule.
\param[in] targets Indices of the target actions for all input terminals.
\param[out] attributeActions Targets to append incoming terminal's attributes.
The added iterators point to input terminal attribute targets.
*/
void create_attibute_actions(
tstack<Symbol>::iterator obegin, const vector<set<size_t>> &targets,
tstack<vector<tstack<Symbol>::iterator>> &attributeActions) {
for (auto &target : reverse(targets)) {
vector<tstack<Symbol>::iterator> iterators;
for (auto &i : target) {
auto oit = obegin;
for (size_t x = 0; x < i; ++x)
++oit;
if (oit->type() == Symbol::Type::TERMINAL)
iterators.push_back(oit);
}
attributeActions.push(iterators);
}
}
public:
/**
\brief Constructs a LLTranslationControl.
*/
LLTranslationControl() = default;
/**
\brief Default destructor.
*/
virtual ~LLTranslationControl() = default;
/**
\brief Constructs LLTranslationControl with a LexicalAnalyzer and
TranslationGrammar.
\param[in] la A reference to the lexical analyzer to be used to get tokens.
\param[in] tg The translation grammar for this translation.
*/
LLTranslationControl(LexicalAnalyzer &la, TranslationGrammar &tg) {
set_grammar(tg);
set_lexical_analyzer(la);
}
/**
\brief Sets translation grammar.
\param[in] tg The translation grammar for this translation.
*/
virtual void set_grammar(const TranslationGrammar &tg) {
translationGrammar_ = &tg;
create_ll_table();
}
/**
\brief Runs the translation. Output symbols are stored in output_.
*/
virtual void run() {
using Type = Symbol::Type;
if (!lexicalAnalyzer_)
throw TranslationException("No lexical analyzer was attached.");
else if (!translationGrammar_)
throw TranslationException("No translation grammar was attached.");
input_.clear();
output_.clear();
tstack<vector<tstack<Symbol>::iterator>> attributeActions;
Symbol token = next_token();
input_.push(Symbol::eof());
output_.push(Symbol::eof());
input_.push(translationGrammar_->starting_symbol());
output_.push(translationGrammar_->starting_symbol());
// iterator to the first symbol of the last inserted string
// used to speed up output_ linear search
auto obegin = output_.begin();
while (1) {
Symbol &top = input_.top();
size_t ruleIndex;
switch (top.type()) {
case Type::EOI:
if (token == Symbol::eof()) {
return;
} else {
add_error(top, token);
return;
}
break;
case Type::TERMINAL:
if (top == token) {
for (auto it : attributeActions.pop()) {
it->set_attribute(token);
}
input_.pop();
token = next_token();
} else {
add_error(top, token);
if (!error_recovery(token))
return;
}
break;
case Type::NONTERMINAL:
lastNonterminal_ = top;
ruleIndex = llTable_.rule_index(top, token);
if (ruleIndex < translationGrammar_->rules().size()) {
auto &rule = translationGrammar_->rules()[ruleIndex];
obegin = output_.replace(top, rule.output(), obegin);
input_.replace(input_.begin(), rule.input());
create_attibute_actions(obegin, rule.actions(), attributeActions);
} else {
add_error(top, token);
if (!error_recovery(token))
return;
}
break;
default:
// unexpected symbol type on input stack
input_.pop();
break;
}
}
}
/**
\brief Adds error message caused by a top symbol and incoming token
combination.
\param[in] top The current top symbol.
\param[in] token The incoming token.
*/
virtual void add_error(const Symbol &top, const Symbol &token) {
using Type = Symbol::Type;
errorFlag_ = true;
errorString_ += token.location().to_string() + ": ";
switch (top.type()) {
case Type::EOI:
errorString_ += "Unexpected token '" + token.name() +
"' after translation has finished.";
break;
case Type::TERMINAL:
errorString_ += "Unexpected token '" + token.name() + "'; expected '" +
top.name() + "'";
break;
case Type::NONTERMINAL:
// TODO list expected tokens
errorString_ += "Unexpected token '" + token.name() +
"', nonterminal '" + top.name() + "'";
break;
default:
break;
}
errorString_ += "\n";
}
/**
\brief Hartmann error recovery.
\param[out] token The next valid token.
\returns True if the error recovery succeeded.
*/
virtual bool error_recovery(Symbol& token) {
size_t ruleIndex = 0;
size_t ntIndex = translationGrammar_.nonterminal_index(lastNonterminal_);
auto& ntFollow = follow_[ntIndex];
// get a token from follow(lastNonterminal_)
while(!is_in(ntFollow, token)) {
token = next_token();
}
// pop stack until a rule is applicable or the same token is on top
while(true) {
Symbol& top = input_.top();
switch(top.type()) {
case Type::EOI:
return true;
case Type::TERMINAL:
if (top == token)
return true;
break;
case Type::NONTERMINAL:
ruleIndex = llTable_.rule_index(top, token);
if (ruleIndex < translationGrammar_->rules().size()) {
return true;
}
break;
default:
break;
}
input_.pop();
}
}
/**
\brief Get error message.
\returns The error message string.
*/
string error_message() { return errorString_; }
};
} // namespace ctf
#endif
/*** End of file ll_translation_control.hpp ***/<commit_msg>fix compilation errors<commit_after>/**
\file ll_translation_control.hpp
\brief Defines class LLTranslationControl and defines its methods.
\author Radek Vít
*/
#ifndef CTF_LL_TRANSLATION_CONTROL_H
#define CTF_LL_TRANSLATION_CONTROL_H
#include "translation_control.hpp"
namespace ctf {
/**
\brief Implements LL top down translation control.
*/
class LLTranslationControl : public TranslationControl {
protected:
/**
\brief Empty set for each nonterminal.
*/
vector<bool> empty_;
/**
\brief First set for each nonterminal.
*/
vector<vector<Symbol>> first_;
/**
\brief Follow set for each nonterminal.
*/
vector<vector<Symbol>> follow_;
/**
\brief Predict set for each nonterminal.
*/
vector<vector<Symbol>> predict_;
/**
\brief LL table used to control the translation.
*/
LLTable llTable_;
/**
\brief Error message string.
*/
string errorString_;
/**
\brief The last expanded nonterminal.
*/
Symbol lastNonterminal_ = Symbol::eof();
/**
Creates all predictive sets and creates a new LL table.
*/
void create_ll_table() {
create_empty();
create_first();
create_follow();
create_predict();
llTable_ = LLTable(*translationGrammar_, predict_);
}
/**
\brief Creates Empty set for each nonterminal.
Empty is true if a series of productions from the nonterminal can result in an
empty string.
*/
void create_empty() {
const TranslationGrammar &tg = *translationGrammar_;
empty_ = vector<bool>(tg.nonterminals().size(), false);
for (auto &r : tg.rules()) {
if (r.input().size() == 0) {
empty_[tg.nonterminal_index(r.nonterminal())] = true;
}
}
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
bool isempty = true;
for (auto &s : r.input()) {
switch (s.type()) {
case Symbol::Type::TERMINAL:
isempty = false;
break;
case Symbol::Type::NONTERMINAL:
if (empty_[tg.nonterminal_index(s)] == false) {
isempty = false;
}
break;
default:
break;
}
}
if (isempty) {
if (!empty_[tg.nonterminal_index(r.nonterminal())]) {
changed = true;
empty_[tg.nonterminal_index(r.nonterminal())] = true;
}
}
}
} while (changed);
}
/**
\brief Creates First set for each nonterminal.
First contains all characters that can be at the first position of any string
derived from this nonterminal.
*/
void create_first() {
const TranslationGrammar &tg = *translationGrammar_;
first_ = {tg.nonterminals().size(), vector<Symbol>{}};
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
size_t i = tg.nonterminal_index(r.nonterminal());
bool empty = true;
for (auto &symbol : r.input()) {
if (!empty)
break;
size_t nonterm_i;
switch (symbol.type()) {
case Symbol::Type::NONTERMINAL:
nonterm_i = tg.nonterminal_index(symbol);
if (modify_set(first_[i], first_[nonterm_i]))
changed = true;
empty = empty_[nonterm_i];
break;
case Symbol::Type::TERMINAL:
if (modify_set(first_[i], vector<Symbol>({symbol})))
changed = true;
empty = false;
break;
default:
break;
}
}
}
} while (changed);
}
/**
\brief Creates Follow set for each nonterminal.
Follow contains all characters that may follow that nonterminal in a
sentential form from the starting nonterminal.
*/
void create_follow() {
const TranslationGrammar &tg = *translationGrammar_;
follow_ = {tg.nonterminals().size(), vector<Symbol>{}};
follow_[tg.nonterminal_index(tg.starting_symbol())].push_back(
Symbol::eof());
bool changed = false;
do {
changed = false;
for (auto &r : tg.rules()) {
// index of origin nonterminal
size_t i = tg.nonterminal_index(r.nonterminal());
/* empty set of all symbols to the right of the current one */
bool compoundEmpty = true;
/* first set of all symbols to the right of the current symbol */
vector<Symbol> compoundFirst;
/* track symbols from back */
for (auto &s : reverse(r.input())) {
// index of nonterminal in input string, only valid with
// nonterminal symbol
size_t ti = 0;
switch (s.type()) {
case Symbol::Type::NONTERMINAL:
ti = tg.nonterminal_index(s);
if (modify_set(follow_[ti], compoundFirst))
changed = true;
if (compoundEmpty && modify_set(follow_[ti], follow_[i]))
changed = true;
break;
default:
break;
}
/* if empty = false */
if (s.type() != Symbol::Type::NONTERMINAL ||
!empty_[tg.nonterminal_index(s)]) {
compoundEmpty = false;
switch (s.type()) {
case Symbol::Type::NONTERMINAL:
compoundFirst = first_[ti];
break;
case Symbol::Type::TERMINAL:
compoundFirst = {s};
break;
default:
break;
}
}
/* empty = true, nonterminal*/
else {
modify_set(compoundFirst, first_[ti]);
}
} // for all reverse input
} // for all rules
} while (changed);
}
/**
\brief Creates Predict set for each nonterminal.
Predict contains all Terminals that may be the first terminal read in a
sentential form from that nonterminal.
*/
void create_predict() {
predict_.clear();
const TranslationGrammar &tg = *translationGrammar_;
for (auto &r : tg.rules()) {
vector<Symbol> compoundFirst;
vector<Symbol> rfollow = follow_[tg.nonterminal_index(r.nonterminal())];
bool compoundEmpty = true;
for (auto &s : reverse(r.input())) {
size_t i;
switch (s.type()) {
case Symbol::Type::TERMINAL:
compoundEmpty = false;
compoundFirst = vector<Symbol>({s});
break;
case Symbol::Type::NONTERMINAL:
i = tg.nonterminal_index(s);
if (!empty_[i]) {
compoundEmpty = false;
compoundFirst = first_[i];
} else {
modify_set(compoundFirst, first_[i]);
}
default:
break;
}
}
predict_.push_back(compoundFirst);
if (compoundEmpty) {
modify_set(predict_.back(), rfollow);
}
} // for all rules
}
/**
\brief Creates iterator attribute actions for incoming terminals.
\param[in] obegin Iterator to the first Symbol of the output of the applied
Rule.
\param[in] targets Indices of the target actions for all input terminals.
\param[out] attributeActions Targets to append incoming terminal's attributes.
The added iterators point to input terminal attribute targets.
*/
void create_attibute_actions(
tstack<Symbol>::iterator obegin, const vector<set<size_t>> &targets,
tstack<vector<tstack<Symbol>::iterator>> &attributeActions) {
for (auto &target : reverse(targets)) {
vector<tstack<Symbol>::iterator> iterators;
for (auto &i : target) {
auto oit = obegin;
for (size_t x = 0; x < i; ++x)
++oit;
if (oit->type() == Symbol::Type::TERMINAL)
iterators.push_back(oit);
}
attributeActions.push(iterators);
}
}
public:
/**
\brief Constructs a LLTranslationControl.
*/
LLTranslationControl() = default;
/**
\brief Default destructor.
*/
virtual ~LLTranslationControl() = default;
/**
\brief Constructs LLTranslationControl with a LexicalAnalyzer and
TranslationGrammar.
\param[in] la A reference to the lexical analyzer to be used to get tokens.
\param[in] tg The translation grammar for this translation.
*/
LLTranslationControl(LexicalAnalyzer &la, TranslationGrammar &tg) {
set_grammar(tg);
set_lexical_analyzer(la);
}
/**
\brief Sets translation grammar.
\param[in] tg The translation grammar for this translation.
*/
virtual void set_grammar(const TranslationGrammar &tg) {
translationGrammar_ = &tg;
create_ll_table();
}
/**
\brief Runs the translation. Output symbols are stored in output_.
*/
virtual void run() {
using Type = Symbol::Type;
if (!lexicalAnalyzer_)
throw TranslationException("No lexical analyzer was attached.");
else if (!translationGrammar_)
throw TranslationException("No translation grammar was attached.");
input_.clear();
output_.clear();
tstack<vector<tstack<Symbol>::iterator>> attributeActions;
Symbol token = next_token();
input_.push(Symbol::eof());
output_.push(Symbol::eof());
input_.push(translationGrammar_->starting_symbol());
output_.push(translationGrammar_->starting_symbol());
// iterator to the first symbol of the last inserted string
// used to speed up output_ linear search
auto obegin = output_.begin();
while (1) {
Symbol &top = input_.top();
size_t ruleIndex;
switch (top.type()) {
case Symbol::Type::EOI:
if (token == Symbol::eof()) {
return;
} else {
add_error(top, token);
return;
}
break;
case Symbol::Type::TERMINAL:
if (top == token) {
for (auto it : attributeActions.pop()) {
it->set_attribute(token);
}
input_.pop();
token = next_token();
} else {
add_error(top, token);
if (!error_recovery(token))
return;
}
break;
case Symbol::Type::NONTERMINAL:
lastNonterminal_ = top;
ruleIndex = llTable_.rule_index(top, token);
if (ruleIndex < translationGrammar_->rules().size()) {
auto &rule = translationGrammar_->rules()[ruleIndex];
obegin = output_.replace(top, rule.output(), obegin);
input_.replace(input_.begin(), rule.input());
create_attibute_actions(obegin, rule.actions(), attributeActions);
} else {
add_error(top, token);
if (!error_recovery(token))
return;
}
break;
default:
// unexpected symbol type on input stack
input_.pop();
break;
}
}
}
/**
\brief Adds error message caused by a top symbol and incoming token
combination.
\param[in] top The current top symbol.
\param[in] token The incoming token.
*/
virtual void add_error(const Symbol &top, const Symbol &token) {
using Type = Symbol::Type;
errorFlag_ = true;
errorString_ += token.location().to_string() + ": ";
switch (top.type()) {
case Type::EOI:
errorString_ += "Unexpected token '" + token.name() +
"' after translation has finished.";
break;
case Type::TERMINAL:
errorString_ += "Unexpected token '" + token.name() + "'; expected '" +
top.name() + "'";
break;
case Type::NONTERMINAL:
// TODO list expected tokens
errorString_ += "Unexpected token '" + token.name() +
"', nonterminal '" + top.name() + "'";
break;
default:
break;
}
errorString_ += "\n";
}
/**
\brief Hartmann error recovery.
\param[out] token The next valid token.
\returns True if the error recovery succeeded.
*/
virtual bool error_recovery(Symbol& token) {
size_t ruleIndex = 0;
size_t ntIndex = translationGrammar_->nonterminal_index(lastNonterminal_);
auto& ntFollow = follow_[ntIndex];
// get a token from follow(lastNonterminal_)
while(!is_in(ntFollow, token)) {
token = next_token();
}
// pop stack until a rule is applicable or the same token is on top
while(true) {
Symbol& top = input_.top();
switch(top.type()) {
case Type::EOI:
return true;
case Type::TERMINAL:
if (top == token)
return true;
break;
case Type::NONTERMINAL:
ruleIndex = llTable_.rule_index(top, token);
if (ruleIndex < translationGrammar_->rules().size()) {
return true;
}
break;
default:
break;
}
input_.pop();
}
}
/**
\brief Get error message.
\returns The error message string.
*/
string error_message() { return errorString_; }
};
} // namespace ctf
#endif
/*** End of file ll_translation_control.hpp ***/<|endoftext|> |
<commit_before><commit_msg>layers: Fix incorrect feature protect for KHX ext<commit_after><|endoftext|> |
<commit_before>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_
#define _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_
#include <odreex/ppmpf/base.hh>
#include <odreex/ppmpf/core.hh>
#include <odreex/ppmpf/tupseq.hh>
#include <odreex/ppmpf/fold.hh>
#include <odreex/ppmpf/tuple/atpos.hh>
/* NOTE: PPMPF_TUP2SEQ: convert a ppmpf tuple to a ppmpf sequence, preserving
* the original order of elements. */
#define PPMPF_TUP2SEQ(tup) \
PPMPF_DREF( \
PPMPF_TUP_FOLDL( PPMPF_T2S_ \
, (PPMPF_TUP_GET(tup)) \
, PPMPF_TUP_POP(tup) ) )
/* NOTE: PPMPF_TUP_JOIN: Join two ppmpf tuples together.*/
#define PPMPF_TUP_JOIN(z,x) \
(PPMPF_DREF(z)PPMPF_IFELSE( PPMPF_NOR( PPMPF_TUP_EMPTY(z) \
, PPMPF_TUP_EMPTY(x)) \
, PPMPF_COMMA \
, PPMPF_EMPTY)()PPMPF_DREF(x))
/* NOTE: PPMPF_TUP_SPLIT: Split a ppmpf tuple into pair of two tuples at a
* given position n */
#define PPMPF_TUP_SPLIT(n,tup) \
PPMPF_COMPOSE( ((), PPMPF_DREF(tup)) \
, (PPMPF_TUP_SPLIT_) \
(PPMPF_CAT(PPMPF_TUP_A0,PPMPF_DIGIT(0,n))) \
(PPMPF_CAT(PPMPF_TUP_A1,PPMPF_PNX(PPMPF_DIGIT(1,n)))) \
(PPMPF_CAT(PPMPF_TUP_A2,PPMPF_PNX(PPMPF_DIGIT(2,n)))) \
(PPMPF_CAT(PPMPF_TUP_A3,PPMPF_PNX(PPMPF_DIGIT(3,n)))))
/* NOTE: PPMPF_TUP_ATPOS: return ppmpf element at position n */
#define PPMPF_TUP_ATPOS(n,tup) \
PPMPF_COMPOSE( PPMPF_TUP_SPLIT(PPMPF_PREV(n),tup) \
, (PPMPF_DPAR) \
PPMPF_IFELSE( PPMPF_IEQL(n,PPMPF_IMINV()) \
, (PPMPF_DPAR) \
(PPMPF_TUP_GET) \
, (PPMPF_TUP_GET) \
(PPMPF_DPAR) \
(PPMPF_TUP_POP) ) \
(PPMPF_ENCLOSE))
#endif /* _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_ */
<commit_msg>Added PPMPF_TUP_SPLITL, PPMPF_TUP_SPLITR.<commit_after>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_
#define _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_
#include <odreex/ppmpf/base.hh>
#include <odreex/ppmpf/core.hh>
#include <odreex/ppmpf/tupseq.hh>
#include <odreex/ppmpf/fold.hh>
#include <odreex/ppmpf/tuple/atpos.hh>
/* NOTE: PPMPF_TUP2SEQ: convert a ppmpf tuple to a ppmpf sequence, preserving
* the original order of elements. */
#define PPMPF_TUP2SEQ(tup) \
PPMPF_DREF( \
PPMPF_TUP_FOLDL( PPMPF_T2S_ \
, (PPMPF_TUP_GET(tup)) \
, PPMPF_TUP_POP(tup) ) )
/* NOTE: PPMPF_TUP_JOIN: Join two ppmpf tuples together.*/
#define PPMPF_TUP_JOIN(z,x) \
(PPMPF_DREF(z)PPMPF_IFELSE( PPMPF_NOR( PPMPF_TUP_EMPTY(z) \
, PPMPF_TUP_EMPTY(x)) \
, PPMPF_COMMA \
, PPMPF_EMPTY)()PPMPF_DREF(x))
/* NOTE: PPMPF_TUP_SPLIT: Split a ppmpf tuple into pair of two tuples at a
* given position n */
#define PPMPF_TUP_SPLIT(n,tup) \
PPMPF_COMPOSE( ((), PPMPF_DREF(tup)) \
, (PPMPF_TUP_SPLIT_) \
(PPMPF_CAT(PPMPF_TUP_A0,PPMPF_DIGIT(0,n))) \
(PPMPF_CAT(PPMPF_TUP_A1,PPMPF_PNX(PPMPF_DIGIT(1,n)))) \
(PPMPF_CAT(PPMPF_TUP_A2,PPMPF_PNX(PPMPF_DIGIT(2,n)))) \
(PPMPF_CAT(PPMPF_TUP_A3,PPMPF_PNX(PPMPF_DIGIT(3,n)))))
/* NOTE: PPMPF_TUP_SPLITL: Split a ppmpf tuple into pair of two tuples at a
* given position n and return the first of the two (left) */
#define PPMPF_TUP_SPLITL(n,tup) \
PPMPF_COMPOSE( PPMPF_TUP_SPLIT(PPMPF_PREV(n),tup) \
, (PPMPF_DPAR) \
(PPMPF_DPAR) \
(PPMPF_TUP_GET) \
(PPMPF_ENCLOSE) )
/* NOTE: PPMPF_TUP_SPLITR: Split a ppmpf tuple into pair of two tuples at a
* given position n and return the second of the two (right) */
#define PPMPF_TUP_SPLITR(n,tup) \
PPMPF_COMPOSE( PPMPF_TUP_SPLIT(PPMPF_PREV(n),tup) \
, (PPMPF_DPAR) \
(PPMPF_DPAR) \
(PPMPF_TUP_POP) \
(PPMPF_ENCLOSE) )
/* NOTE: PPMPF_TUP_ATPOS: return ppmpf element at position n */
#define PPMPF_TUP_ATPOS(n,tup) \
PPMPF_COMPOSE( PPMPF_TUP_SPLIT(PPMPF_PREV(n),tup) \
, (PPMPF_DPAR) \
PPMPF_IFELSE( PPMPF_IEQL(n,PPMPF_IMINV()) \
, (PPMPF_DPAR) \
(PPMPF_TUP_GET) \
, (PPMPF_TUP_GET) \
(PPMPF_DPAR) \
(PPMPF_TUP_POP) ) \
(PPMPF_ENCLOSE))
#endif /* _ODREEX_PPMPF_TUPLE_FUNCTIONS_HH_ */
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include "SoftwareSerial.h"
#include "A6lib.h"
#ifdef DEBUG
#define log(msg) Serial.print(msg)
#define logln(msg) Serial.println(msg)
#else
#define log(msg)
#define logln(msg)
#endif
#define OK 1
#define NOTOK 2
#define TIMEOUT 3
#define A6_CMD_TIMEOUT 2000
/////////////////////////////////////////////
// Public methods.
//
A6::A6(int transmitPin, int receivePin) {
A6conn = new SoftwareSerial(receivePin, transmitPin, false, 1024);
A6conn->setTimeout(100);
}
A6::~A6() {
delete A6conn;
}
// Initialize the software serial connection and change the baud rate from the
// default (autodetected) to the desired speed.
void A6::begin(long baudRate) {
// Give the module some time to settle.
logln("Waiting for the module to initialize...");
delay(20000);
logln("Done.");
A6conn->flush();
setRate(baudRate);
// Factory reset.
A6command("AT&F", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Echo off.
A6command("ATE0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Set caller ID on.
A6command("AT+CLIP=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Set SMS to text mode.
A6command("AT+CMGF=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Switch audio to headset.
enableSpeaker(0);
}
// Reboot the module by setting the specified pin HIGH, then LOW. The pin should
// be connected to a P-MOSFET, not the A6's POWER pin.
void A6::powerCycle(int pin) {
logln("Power-cycling module...");
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(1000);
digitalWrite(pin, HIGH);
// Give the module some time to settle.
logln("Power-cycle done.");
A6conn->flush();
}
// Dial a number.
void A6::dial(String number) {
char buffer[50];
logln("Dialing number...");
sprintf(buffer, "ATD%s;", number.c_str());
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Redial the last number.
void A6::redial() {
logln("Redialing last number...");
A6command("AT+DLST", "OK", "CONNECT", A6_CMD_TIMEOUT, 2, NULL);
}
// Answer a call.
void A6::answer() {
A6command("ATA", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Hang up the phone.
void A6::hangUp() {
A6command("ATH", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Check whether there is an active call.
callInfo A6::checkCallStatus() {
char number[50];
String response = "";
int respStart = 0, matched = 0;
callInfo cinfo = (const struct callInfo){ 0 };
// Issue the command and wait for the response.
A6command("AT+CLCC", "OK", "+CLCC", A6_CMD_TIMEOUT, 2, &response);
// Parse the response if it contains a valid +CLCC.
respStart = response.indexOf("+CLCC");
if (respStart >= 0) {
matched = sscanf(response.substring(respStart).c_str(), "+CLCC: %d,%d,%d,%d,%d,\"%s\",%d", &cinfo.index, &cinfo.direction, &cinfo.state, &cinfo.mode, &cinfo.multiparty, number, &cinfo.type);
cinfo.number = String(number);
}
return cinfo;
}
// Send an SMS.
byte A6::sendSMS(String number, String text) {
char ctrlZ[2] = { 0x1a, 0x00 };
char buffer[100];
if (text.length() > 159) {
// We can't send messages longer than 160 characters.
return NOTOK;
}
log("Sending SMS to ");
log(number);
logln("...");
sprintf(buffer, "AT+CMGS=\"%s\"", number.c_str());
A6command(buffer, ">", "yy", A6_CMD_TIMEOUT, 2, NULL);
delay(100);
A6conn->println(text.c_str());
A6conn->println(ctrlZ);
A6conn->println();
return OK;
}
// Set the volume for the speaker. level should be a number between 5 and
// 8 inclusive.
void A6::setVol(byte level) {
char buffer[30];
// level should be between 5 and 8.
level = min(max(level, 5), 8);
sprintf(buffer, "AT+CLVL=%d", level);
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Enable the speaker, rather than the headphones. Pass 0 to route audio through
// headphones, 1 through speaker.
void A6::enableSpeaker(byte enable) {
char buffer[30];
// enable should be between 0 and 1.
enable = min(max(enable, 0), 1);
sprintf(buffer, "AT+SNFS=%d", enable);
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
/////////////////////////////////////////////
// Private methods.
//
// Autodetect the connection rate.
int A6::detectRate() {
int rate = 0;
int rates[] = {115200, 9600, 1200, 2400, 4800, 19200, 38400, 57600};
// Try to autodetect the rate.
logln("Autodetecting connection rate...");
for (int i = 0; i < 8; i++) {
rate = rates[i];
A6conn->begin(rate);
log("Trying rate ");
log(rate);
logln("...");
delay(100);
if (A6command("\rAT", "OK", "+CME", 3000, 2, NULL) == OK) {
return rate;
}
}
// Return a default rate.
return 9600;
}
// Set the A6 baud rate.
void A6::setRate(long baudRate) {
int rate = detectRate();
// The rate is already the desired rate, return.
if (rate == baudRate) return;
logln("Setting baud rate on the module...");
// Change the rate to the requested.
char buffer[30];
sprintf(buffer, "AT+IPR=%d", baudRate);
A6command(buffer, "OK", "+IPR=", A6_CMD_TIMEOUT, 3, NULL);
logln("Switching to the new rate...");
// Begin the connection again at the requested rate.
A6conn->begin(baudRate);
logln("Rate set.");
}
// Read some data from the A6 in a non-blocking manner.
String A6::read() {
String reply = "";
if (A6conn->available()) reply = A6conn->readString();
return reply;
}
// Issue a command.
byte A6::A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response) {
byte returnValue = NOTOK;
byte count = 0;
// Get rid of any buffered output.
A6conn->flush();
while (count < repetitions && returnValue != OK) {
log("Issuing command: ");
logln(command);
A6conn->print(command);
A6conn->print("\r");
if (A6waitFor(resp1, resp2, timeout, response) == OK) {
returnValue = OK;
} else {
returnValue = NOTOK;
}
count++;
}
return returnValue;
}
// Wait for responses.
byte A6::A6waitFor(const char *resp1, const char *resp2, int timeout, String *response) {
unsigned long entry = millis();
int count = 0;
String reply = "";
byte retVal = 99;
do {
reply += read();
yield();
} while ((reply.indexOf(resp1) + reply.indexOf(resp2) == -2) && millis() - entry < timeout);
if (reply != "") {
log("Reply in ");
log((millis() - entry));
log(" ms: ");
logln(reply);
}
if (response != NULL) *response = reply;
if ((millis() - entry) >= timeout) {
retVal = TIMEOUT;
logln("Timed out.");
} else {
if (reply.indexOf(resp1) + reply.indexOf(resp2) > -2) {
logln("Reply OK.");
retVal = OK;
} else {
logln("Reply NOT OK.");
retVal = NOTOK;
}
}
return retVal;
}
<commit_msg>Improve rate looping.<commit_after>#include <Arduino.h>
#include "SoftwareSerial.h"
#include "A6lib.h"
#ifdef DEBUG
#define log(msg) Serial.print(msg)
#define logln(msg) Serial.println(msg)
#else
#define log(msg)
#define logln(msg)
#endif
#define countof(a) (sizeof(a) / sizeof(a[0]))
#define OK 1
#define NOTOK 2
#define TIMEOUT 3
#define A6_CMD_TIMEOUT 2000
/////////////////////////////////////////////
// Public methods.
//
A6::A6(int transmitPin, int receivePin) {
A6conn = new SoftwareSerial(receivePin, transmitPin, false, 1024);
A6conn->setTimeout(100);
}
A6::~A6() {
delete A6conn;
}
// Initialize the software serial connection and change the baud rate from the
// default (autodetected) to the desired speed.
void A6::begin(long baudRate) {
// Give the module some time to settle.
logln("Waiting for the module to initialize...");
delay(20000);
logln("Done.");
A6conn->flush();
setRate(baudRate);
// Factory reset.
A6command("AT&F", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Echo off.
A6command("ATE0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Set caller ID on.
A6command("AT+CLIP=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Set SMS to text mode.
A6command("AT+CMGF=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
// Switch audio to headset.
enableSpeaker(0);
}
// Reboot the module by setting the specified pin HIGH, then LOW. The pin should
// be connected to a P-MOSFET, not the A6's POWER pin.
void A6::powerCycle(int pin) {
logln("Power-cycling module...");
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(1000);
digitalWrite(pin, HIGH);
// Give the module some time to settle.
logln("Power-cycle done.");
A6conn->flush();
}
// Dial a number.
void A6::dial(String number) {
char buffer[50];
logln("Dialing number...");
sprintf(buffer, "ATD%s;", number.c_str());
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Redial the last number.
void A6::redial() {
logln("Redialing last number...");
A6command("AT+DLST", "OK", "CONNECT", A6_CMD_TIMEOUT, 2, NULL);
}
// Answer a call.
void A6::answer() {
A6command("ATA", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Hang up the phone.
void A6::hangUp() {
A6command("ATH", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Check whether there is an active call.
callInfo A6::checkCallStatus() {
char number[50];
String response = "";
int respStart = 0, matched = 0;
callInfo cinfo = (const struct callInfo){ 0 };
// Issue the command and wait for the response.
A6command("AT+CLCC", "OK", "+CLCC", A6_CMD_TIMEOUT, 2, &response);
// Parse the response if it contains a valid +CLCC.
respStart = response.indexOf("+CLCC");
if (respStart >= 0) {
matched = sscanf(response.substring(respStart).c_str(), "+CLCC: %d,%d,%d,%d,%d,\"%s\",%d", &cinfo.index, &cinfo.direction, &cinfo.state, &cinfo.mode, &cinfo.multiparty, number, &cinfo.type);
cinfo.number = String(number);
}
return cinfo;
}
// Send an SMS.
byte A6::sendSMS(String number, String text) {
char ctrlZ[2] = { 0x1a, 0x00 };
char buffer[100];
if (text.length() > 159) {
// We can't send messages longer than 160 characters.
return NOTOK;
}
log("Sending SMS to ");
log(number);
logln("...");
sprintf(buffer, "AT+CMGS=\"%s\"", number.c_str());
A6command(buffer, ">", "yy", A6_CMD_TIMEOUT, 2, NULL);
delay(100);
A6conn->println(text.c_str());
A6conn->println(ctrlZ);
A6conn->println();
return OK;
}
// Set the volume for the speaker. level should be a number between 5 and
// 8 inclusive.
void A6::setVol(byte level) {
char buffer[30];
// level should be between 5 and 8.
level = min(max(level, 5), 8);
sprintf(buffer, "AT+CLVL=%d", level);
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
// Enable the speaker, rather than the headphones. Pass 0 to route audio through
// headphones, 1 through speaker.
void A6::enableSpeaker(byte enable) {
char buffer[30];
// enable should be between 0 and 1.
enable = min(max(enable, 0), 1);
sprintf(buffer, "AT+SNFS=%d", enable);
A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL);
}
/////////////////////////////////////////////
// Private methods.
//
// Autodetect the connection rate.
int A6::detectRate() {
int rate = 0;
int rates[] = {115200, 9600, 1200, 2400, 4800, 19200, 38400, 57600};
// Try to autodetect the rate.
logln("Autodetecting connection rate...");
for (int i = 0; i < countof(rates); i++) {
rate = rates[i];
A6conn->begin(rate);
log("Trying rate ");
log(rate);
logln("...");
delay(100);
if (A6command("\r\r\rAT", "OK", "+CME", 2000, 2, NULL) == OK) {
return rate;
}
}
// Return a default rate.
return 9600;
}
// Set the A6 baud rate.
void A6::setRate(long baudRate) {
int rate = detectRate();
// The rate is already the desired rate, return.
if (rate == baudRate) return;
logln("Setting baud rate on the module...");
// Change the rate to the requested.
char buffer[30];
sprintf(buffer, "AT+IPR=%d", baudRate);
A6command(buffer, "OK", "+IPR=", A6_CMD_TIMEOUT, 3, NULL);
logln("Switching to the new rate...");
// Begin the connection again at the requested rate.
A6conn->begin(baudRate);
logln("Rate set.");
}
// Read some data from the A6 in a non-blocking manner.
String A6::read() {
String reply = "";
if (A6conn->available()) reply = A6conn->readString();
return reply;
}
// Issue a command.
byte A6::A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response) {
byte returnValue = NOTOK;
byte count = 0;
// Get rid of any buffered output.
A6conn->flush();
while (count < repetitions && returnValue != OK) {
log("Issuing command: ");
logln(command);
A6conn->print(command);
A6conn->print("\r");
if (A6waitFor(resp1, resp2, timeout, response) == OK) {
returnValue = OK;
} else {
returnValue = NOTOK;
}
count++;
}
return returnValue;
}
// Wait for responses.
byte A6::A6waitFor(const char *resp1, const char *resp2, int timeout, String *response) {
unsigned long entry = millis();
int count = 0;
String reply = "";
byte retVal = 99;
do {
reply += read();
yield();
} while ((reply.indexOf(resp1) + reply.indexOf(resp2) == -2) && millis() - entry < timeout);
if (reply != "") {
log("Reply in ");
log((millis() - entry));
log(" ms: ");
logln(reply);
}
if (response != NULL) *response = reply;
if ((millis() - entry) >= timeout) {
retVal = TIMEOUT;
logln("Timed out.");
} else {
if (reply.indexOf(resp1) + reply.indexOf(resp2) > -2) {
logln("Reply OK.");
retVal = OK;
} else {
logln("Reply NOT OK.");
retVal = NOTOK;
}
}
return retVal;
}
<|endoftext|> |
<commit_before>#include <Common/config.h>
#include <Common/task.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "p2k.h"
using namespace P2KConfig;
#define TICK_FREQ 250
#define PIN_OPEN 5
const byte SOLUTION1[5] = { 3, 2, 1, 4, 4 };
const byte SOLUTION2[5] = { 3, 2, 2, 2, 1 };
enum {
FLAG_SECOND,
FLAG_BLINK,
FLAG_OPEN,
FLAG_CLOSE
};
enum {
STATE_INIT,
STATE_OPEN
};
volatile byte gFlags;
volatile byte gState;
P2K panel;
bool gSolved1;
bool gSolved2;
bool gSolvedAll;
bool gCashOpen;
byte gCount;
void taskRestart() {
gSolvedAll = false;
gCashOpen = false;
gCount = 0;
panel.clear();
}
void taskComplete() {
gSolvedAll = true;
gCount++;
bit_set(gFlags, FLAG_OPEN);
gCashOpen = true;
}
byte taskIsDone() {
return gSolvedAll;
}
byte taskCallback(byte cmd, byte nParams, byte *nResults, byte *busParams)
{
switch (cmd) {
case CMD_COUNT:
{
*nResults = 1;
busParams[0] = gCount;
}
}
return 0;
}
void setup() {
gState = STATE_INIT;
pinMode(PIN_OPEN, OUTPUT);
// Setup Timer0
// Set CTC mode, TOP = OCRA, prescaler 1024
// Overflow 125Hz (8ms)
TIMER0_SETUP(TIMER0_FAST_PWM, TIMER0_PRESCALER(TICK_FREQ));
//TCCR0A = (1 << WGM01) | (1 << WGM00);
//TCCR0B = (1 << CS02) | (1 << CS00) | (1 << WGM02);
TIMSK0 = (1 << TOIE0);
//OCR0A = (byte)(F_CPU / (1024UL * TICK_FREQ)) - 1;
OCR0A = TIMER0_COUNTS(TICK_FREQ) - 1;
panel.setup();
taskRestart();
taskSetup(BUS_ADDRESS);
}
void loop() {
static byte led = 0;
static bool phase = true;
if (bit_check(gFlags, FLAG_BLINK))
{
bit_clear(gFlags, FLAG_BLINK);
bool ok1 = true;
bool ok2 = true;
for (byte idx = 0; idx < 5; idx++) {
byte state = panel.getButtons(idx);
byte state1 = state & 0x0F;
byte state2 = state & 0xF0;
byte mask1 = 1 << (4 - SOLUTION1[idx]);
byte mask2 = 1 << (8 - SOLUTION2[idx]);
if (state1 != mask1) {
ok1 = false;
}
if (state2 != mask2) {
ok2 = false;
}
//if (!gTaskDone) {
// panel.setLED(idx, (state1 == mask1));
// panel.setLED(idx + 5, (state2 == mask2));
//}
}
bool wasDone = taskIsDone();
if (!gSolved1 && ok1) {
for (byte idx = 0; idx < 5; idx++) panel.setLED(idx, true);
gSolved1 = ok1;
}
if (!gSolved2 && ok2) {
for (byte idx = 0; idx < 5; idx++) panel.setLED(idx + 5, true);
gSolved2 = ok2;
}
if (gSolved1 && !ok1) {
for (byte idx = 0; idx < 5; idx++) panel.setLED(idx, false);
gSolved1 = ok1;
}
if (gSolved2 && !ok2) {
for (byte idx = 0; idx < 5; idx++) panel.setLED(idx + 5, false);
gSolved2 = ok2;
}
gSolvedAll = gSolved1 && gSolved2;
if (taskIsDone()) {
if (!wasDone) {
led = 0;
phase = true;
taskComplete();
}
panel.setLED(led, phase);
if (++led >= 10) {
led = 0;
phase = !phase;
}
}
}
taskLoop();
}
ISR(TIMER0_OVF_vect) {
static word millis = 0;
static word millis2 = 0;
static word millis3 = 0;
static word millis4 = 0;
millis += (1000UL / TICK_FREQ);
millis2 += (1000UL / TICK_FREQ);
if (millis >= 1000) {
millis -= 1000;
bit_set(gFlags, FLAG_SECOND);
}
if (millis2 >= 200) {
millis2 -= 200;
bit_set(gFlags, FLAG_BLINK);
}
panel.update();
if (bit_check(gFlags, FLAG_OPEN)) {
millis3 += (1000UL / TICK_FREQ);
if (millis3 > 500) {
bit_clear(gFlags, FLAG_OPEN);
pinWrite(PIN_OPEN, HIGH);
millis4 = 0;
bit_set(gFlags, FLAG_CLOSE);
}
}
if (bit_check(gFlags, FLAG_CLOSE)) {
millis4 += (1000UL / TICK_FREQ);
if (millis4 > 100) {
bit_clear(gFlags, FLAG_CLOSE);
pinWrite(PIN_OPEN, LOW);
millis3 = 0;
}
}
}
<commit_msg>Fix task completion<commit_after>#include <Common/config.h>
#include <Common/task.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "p2k.h"
using namespace P2KConfig;
#define TICK_FREQ 250
#define PIN_OPEN 5
const byte SOLUTION1[5] = { 3, 2, 1, 4, 4 };
const byte SOLUTION2[5] = { 3, 2, 2, 2, 1 };
enum {
FLAG_SECOND, FLAG_BLINK, FLAG_OPEN, FLAG_CLOSE
};
enum {
STATE_INIT, STATE_OPEN
};
volatile byte gFlags;
volatile byte gState;
P2K panel;
bool gSolved1;
bool gSolved2;
bool gSolvedAll;
bool gCashOpen;
byte gCount;
void taskRestart() {
gSolvedAll = false;
gCashOpen = false;
gCount = 0;
panel.clear();
}
void taskComplete() {
gSolvedAll = true;
gCount++;
bit_set(gFlags, FLAG_OPEN);
gCashOpen = true;
}
byte taskIsDone() {
return gSolvedAll;
}
byte taskCallback(byte cmd, byte nParams, byte *nResults, byte *busParams) {
switch (cmd) {
case CMD_COUNT: {
*nResults = 1;
busParams[0] = gCount;
}
}
return 0;
}
void setup() {
gState = STATE_INIT;
pinMode(PIN_OPEN, OUTPUT);
// Setup Timer0
// Set CTC mode, TOP = OCRA, prescaler 1024
// Overflow 125Hz (8ms)
TIMER0_SETUP(TIMER0_FAST_PWM, TIMER0_PRESCALER(TICK_FREQ));
//TCCR0A = (1 << WGM01) | (1 << WGM00);
//TCCR0B = (1 << CS02) | (1 << CS00) | (1 << WGM02);
TIMSK0 = (1 << TOIE0);
//OCR0A = (byte)(F_CPU / (1024UL * TICK_FREQ)) - 1;
OCR0A = TIMER0_COUNTS(TICK_FREQ) - 1;
panel.setup();
taskRestart();
taskSetup(BUS_ADDRESS);
}
void loop() {
static byte led = 0;
static bool phase = true;
bool ok1 = true;
bool ok2 = true;
for (byte idx = 0; idx < 5; idx++) {
byte state = panel.getButtons(idx);
byte state1 = state & 0x0F;
byte state2 = state & 0xF0;
byte mask1 = 1 << (4 - SOLUTION1[idx]);
byte mask2 = 1 << (8 - SOLUTION2[idx]);
if (state1 != mask1) {
ok1 = false;
}
if (state2 != mask2) {
ok2 = false;
}
}
if (!gSolved1 && ok1) {
for (byte idx = 0; idx < 5; idx++)
panel.setLED(idx, true);
}
if (!gSolved2 && ok2) {
for (byte idx = 0; idx < 5; idx++)
panel.setLED(idx + 5, true);
}
if (gSolved1 && !ok1) {
for (byte idx = 0; idx < 5; idx++)
panel.setLED(idx, false);
}
if (gSolved2 && !ok2) {
for (byte idx = 0; idx < 5; idx++)
panel.setLED(idx + 5, false);
}
if (ok1 && ok2 && (!gSolved1 || !gSolved2)) {
led = 0;
phase = true;
taskComplete();
}
gSolved1 = ok1;
gSolved2 = ok2;
gSolvedAll = gSolved1 && gSolved2;
if (taskIsDone()) {
panel.setLED(led, phase);
if (++led >= 10) {
led = 0;
phase = !phase;
}
}
taskLoop();
}
ISR(TIMER0_OVF_vect) {
static word millis = 0;
static word millis2 = 0;
static word millis3 = 0;
static word millis4 = 0;
millis += (1000UL / TICK_FREQ);
millis2 += (1000UL / TICK_FREQ);
if (millis >= 1000) {
millis -= 1000;
bit_set(gFlags, FLAG_SECOND);
}
if (millis2 >= 200) {
millis2 -= 200;
bit_set(gFlags, FLAG_BLINK);
}
panel.update();
if (bit_check(gFlags, FLAG_OPEN)) {
millis3 += (1000UL / TICK_FREQ);
if (millis3 > 500) {
bit_clear(gFlags, FLAG_OPEN);
pinWrite(PIN_OPEN, HIGH);
millis4 = 0;
bit_set(gFlags, FLAG_CLOSE);
}
}
if (bit_check(gFlags, FLAG_CLOSE)) {
millis4 += (1000UL / TICK_FREQ);
if (millis4 > 100) {
bit_clear(gFlags, FLAG_CLOSE);
pinWrite(PIN_OPEN, LOW);
millis3 = 0;
}
}
}
<|endoftext|> |
<commit_before>
#ifndef __PICKABLE_HPP__
#define __PICKABLE_HPP__
#include <vector>
#include "allocore/ui/al_Gnomon.hpp"
#include "allocore/ui/al_BoundingBox.hpp"
namespace al {
struct PickableState {
bool hover, selected;
Pose pose;
Vec3f scale;
PickableState(){
pose = Pose();
scale = Vec3f(1);
hover = selected = false;
}
};
struct PickableBase : virtual PickableState {
PickableBase *parent = 0;
std::vector<PickableBase *> children;
bool alwaysTestChildren = true;
// initial values, and previous values
Pose pose0, prevPose;
Vec3f scale0, prevScale;
/// intersection test must be specified
virtual double intersect(Rayd &r) = 0;
/// override these callbacks
virtual bool onPoint(Rayd &r, double t, bool child){return false;}
virtual bool onPick(Rayd &r, double t, bool child){return false;}
virtual bool onDrag(Rayd &r, double t, bool child){return false;}
virtual bool onUnpick(Rayd &r, double t, bool child){return false;}
/// do interaction on self and children, call onPoint callbacks
virtual bool point(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->point(ray);
}
}
return onPoint(r,t,child);
}
/// do interaction on self and children, call onPick callbacks
virtual bool pick(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->pick(ray);
}
}
return onPick(r,t,child);
}
/// do interaction on self and children, call onDrag callbacks
virtual bool drag(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->drag(ray);
}
}
return onDrag(r,t,child);
}
/// do interaction on self and children, call onUnpick callbacks
virtual bool unpick(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->unpick(ray);
}
}
return onUnpick(r,t,child);
}
virtual void draw(Graphics &g){}
virtual void drawChildren(Graphics &g){
pushMatrix(g);
for(int i=0; i < children.size(); i++){
children[i]->draw(g);
}
popMatrix(g);
}
bool intersects(Rayd &r){ return intersect(r) > 0.0; }
bool intersectsChild(Rayd &r){
bool child = false;
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->intersects(ray);
}
return child;
}
void addChild(PickableBase &pickable){
pickable.parent = this;
children.push_back(&pickable);
}
/// apply pickable pose transforms
inline void pushMatrix(Graphics &g){
g.pushMatrix();
g.translate(pose.pos());
g.rotate(pose.quat());
g.scale(scale);
}
/// pop matrix.
inline void popMatrix(Graphics &g){
g.popMatrix();
}
/// transform a ray in world space to local space
Rayd transformRayLocal(const Rayd &ray){
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Matrix4d invModel = Matrix4d::inverse(model);
Vec4d o = invModel.transform(Vec4d(ray.o, 1));
Vec4d d = invModel.transform(Vec4d(ray.d, 0));
return Rayd(o.sub<3>(0), d.sub<3>(0));
}
/// transfrom a vector in local space to world space
Vec3f transformVecWorld(const Vec3f &v, float w=1){
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Vec4d o = model.transform(Vec4d(v, w));
return Vec3f(o.sub<3>(0));
}
};
/// Bounding Box Pickable
struct Pickable : PickableBase {
Mesh *mesh; // pointer to mesh that is wrapped
BoundingBox bb; // original bounding box
BoundingBox aabb; // axis aligned bounding box (after pose/scale transforms)
// used for moving pickable naturally
Vec3f selectOffset;
float selectDist;
Pickable(){}
Pickable(Mesh &m){set(m);}
/// initialize bounding box;
void set(Mesh &m){
mesh = &m;
bb.set(*mesh);
}
/// override base methods
double intersect(Rayd &r){
return intersectBB(r);
}
bool onPoint(Rayd &r, double t, bool child){
if(t > 0.0){
if(child){
hover = false;
} else {
hover = true;
}
} else hover = false;
return hover || child;
}
bool onPick(Rayd &r, double t, bool child){
if(t > 0.0){
if(child){
selected = false;
} else {
prevPose.set(pose);
selectDist = t;
selectOffset = pose.pos() - r(t);
selected = true;
}
} else selected = false;
return selected || child;
}
bool onDrag(Rayd &r, double t, bool child){
if(t > 0.0){
if(child){
return true;
} else if(selected){
Vec3f newPos = r(selectDist) + selectOffset;
pose.pos().set(newPos);
return true;
}
}
return false;
}
bool onUnpick(Rayd &r, double t, bool child){
if(!hover) selected = false;
return false;
}
// draw
void draw(Graphics &g){
pushMatrix(g);
glPushAttrib(GL_CURRENT_BIT);
if(mesh) g.draw(*mesh);
if(selected) g.color(0,1,1);
else if(hover) g.color(1,1,1);
g.draw(bb.mesh);
g.draw(bb.tics);
// drawLabels(g);
drawChildren(g);
glPopAttrib();
popMatrix(g);
}
void drawMesh(Graphics &g){
if(!mesh) return;
pushMatrix(g);
g.draw(*mesh);
popMatrix(g);
}
void drawBB(Graphics &g){
if(!selected && !hover) return;
pushMatrix(g);
glPushAttrib(GL_CURRENT_BIT);
if(selected) g.color(0,1,1);
else if(hover) g.color(1,1,1);
g.draw(bb.mesh);
g.draw(bb.tics);
glPopAttrib();
popMatrix(g);
}
void drawGrid(Graphics &g){
pushMatrix(g);
if(selected || hover){
g.lineWidth(2);
g.draw(bb.gridMesh[1]);
g.lineWidth(1);
g.draw(bb.gridMesh[0]);
} else {}
popMatrix(g);
}
void drawLabels(Graphics &g, Font& font, Pose &cam_pose){
if(!selected && !hover) return;
g.pushMatrix();
bb.drawLabels(g, font, cam_pose, pose, scale.x);
g.popMatrix();
}
void drawOrigin(Graphics &g){
Gnomon gnomon;
pushMatrix(g);
gnomon.draw(g);
popMatrix(g);
}
////////////////////////////////////////////////////////////////////////////
/// set the pickable's center position
void setCenter(Vec3f& pos){
updateAABB();
Vec3f offset = aabb.cen - pose.pos();
pose.pos().set(pos - offset);
}
/// set pickable's orientation maintaining same center position
void setQuat(Quatf& q){
updateAABB();
Vec3f cen;
cen.set(aabb.cen);
pose.quat().set(q);
setCenter(cen);
}
/// intersect ray with pickable BoundingBox
double intersectBB(Rayd &ray){
Rayd r = transformRayLocal(ray);
return r.intersectBox(bb.cen, bb.dim);
}
/// intersect ray with pickable AxisAlignedBoundingBox
double intersectAABB(Rayd &ray){
return ray.intersectBox(aabb.cen, aabb.dim);
}
/// intersect ray with bounding sphere
float intersectBoundingSphere(Rayd &ray){
return ray.intersectSphere( transformVecWorld(bb.cen), (bb.dim*scale).mag()/2.0);
}
/// calculate Axis aligned bounding box from mesh bounding box and current transforms
void updateAABB(){
// thanks to http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Matrix4d absModel(model);
for(int i=0; i<16; i++) absModel[i] = abs(absModel[i]);
Vec4d cen = model.transform(Vec4d(bb.cen, 1));
Vec4d dim = absModel.transform(Vec4d(bb.dim, 0));
aabb.setCenterDim(cen.sub<3>(0),dim.sub<3>(0));
}
};
} // ::al
#endif
<commit_msg>don't need to intersect on drag and selected<commit_after>
#ifndef __PICKABLE_HPP__
#define __PICKABLE_HPP__
#include <vector>
#include "allocore/ui/al_Gnomon.hpp"
#include "allocore/ui/al_BoundingBox.hpp"
namespace al {
struct PickableState {
bool hover, selected;
Pose pose;
Vec3f scale;
PickableState(){
pose = Pose();
scale = Vec3f(1);
hover = selected = false;
}
};
struct PickableBase : virtual PickableState {
PickableBase *parent = 0;
std::vector<PickableBase *> children;
bool alwaysTestChildren = true;
// initial values, and previous values
Pose pose0, prevPose;
Vec3f scale0, prevScale;
/// intersection test must be specified
virtual double intersect(Rayd &r) = 0;
/// override these callbacks
virtual bool onPoint(Rayd &r, double t, bool child){return false;}
virtual bool onPick(Rayd &r, double t, bool child){return false;}
virtual bool onDrag(Rayd &r, double t, bool child){return false;}
virtual bool onUnpick(Rayd &r, double t, bool child){return false;}
/// do interaction on self and children, call onPoint callbacks
virtual bool point(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->point(ray);
}
}
return onPoint(r,t,child);
}
/// do interaction on self and children, call onPick callbacks
virtual bool pick(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->pick(ray);
}
}
return onPick(r,t,child);
}
/// do interaction on self and children, call onDrag callbacks
virtual bool drag(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->drag(ray);
}
}
return onDrag(r,t,child);
}
/// do interaction on self and children, call onUnpick callbacks
virtual bool unpick(Rayd &r){
bool child = false;
double t = intersect(r);
if(t > 0.0 || alwaysTestChildren){
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->unpick(ray);
}
}
return onUnpick(r,t,child);
}
virtual void draw(Graphics &g){}
virtual void drawChildren(Graphics &g){
pushMatrix(g);
for(int i=0; i < children.size(); i++){
children[i]->draw(g);
}
popMatrix(g);
}
bool intersects(Rayd &r){ return intersect(r) > 0.0; }
bool intersectsChild(Rayd &r){
bool child = false;
for(int i=0; i < children.size(); i++){
Rayd ray = transformRayLocal(r);
child |= children[i]->intersects(ray);
}
return child;
}
void addChild(PickableBase &pickable){
pickable.parent = this;
children.push_back(&pickable);
}
/// apply pickable pose transforms
inline void pushMatrix(Graphics &g){
g.pushMatrix();
g.translate(pose.pos());
g.rotate(pose.quat());
g.scale(scale);
}
/// pop matrix.
inline void popMatrix(Graphics &g){
g.popMatrix();
}
/// transform a ray in world space to local space
Rayd transformRayLocal(const Rayd &ray){
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Matrix4d invModel = Matrix4d::inverse(model);
Vec4d o = invModel.transform(Vec4d(ray.o, 1));
Vec4d d = invModel.transform(Vec4d(ray.d, 0));
return Rayd(o.sub<3>(0), d.sub<3>(0));
}
/// transfrom a vector in local space to world space
Vec3f transformVecWorld(const Vec3f &v, float w=1){
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Vec4d o = model.transform(Vec4d(v, w));
return Vec3f(o.sub<3>(0));
}
/// transfrom a vector in world space to local space
Vec3f transformVecLocal(const Vec3f &v, float w=1){
Matrix4d t,r,s;
Matrix4d invModel = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Vec4d o = invModel.transform(Vec4d(v, w));
return Vec3f(o.sub<3>(0));
}
};
/// Bounding Box Pickable
struct Pickable : PickableBase {
Mesh *mesh; // pointer to mesh that is wrapped
BoundingBox bb; // original bounding box
BoundingBox aabb; // axis aligned bounding box (after pose/scale transforms)
// used for moving pickable naturally
Vec3f selectOffset;
float selectDist;
Pickable(){}
Pickable(Mesh &m){set(m);}
/// initialize bounding box;
void set(Mesh &m){
mesh = &m;
bb.set(*mesh);
}
/// override base methods
double intersect(Rayd &r){
return intersectBB(r);
}
bool onPoint(Rayd &r, double t, bool child){
if(t > 0.0){
if(child){
hover = false;
} else {
hover = true;
}
} else hover = false;
return hover || child;
}
bool onPick(Rayd &r, double t, bool child){
if(t > 0.0){
if(child){
selected = false;
} else {
prevPose.set(pose);
selectDist = t;
selectOffset = pose.pos() - r(t);
selected = true;
}
} else selected = false;
return selected || child;
}
bool onDrag(Rayd &r, double t, bool child){
// if(t > 0.0){
if(child){
return true;
} else if(selected){
Vec3f newPos = r(selectDist) + selectOffset;
pose.pos().set(newPos);
return true;
}
// }
return false;
}
bool onUnpick(Rayd &r, double t, bool child){
if(!hover) selected = false;
return false;
}
// draw
void draw(Graphics &g){
pushMatrix(g);
glPushAttrib(GL_CURRENT_BIT);
if(mesh) g.draw(*mesh);
if(selected) g.color(0,1,1);
else if(hover) g.color(1,1,1);
g.draw(bb.mesh);
g.draw(bb.tics);
// drawLabels(g);
glPopAttrib();
popMatrix(g);
drawChildren(g);
}
void drawMesh(Graphics &g){
if(!mesh) return;
pushMatrix(g);
g.draw(*mesh);
popMatrix(g);
}
void drawBB(Graphics &g){
if(!selected && !hover) return;
pushMatrix(g);
glPushAttrib(GL_CURRENT_BIT);
if(selected) g.color(0,1,1);
else if(hover) g.color(1,1,1);
g.draw(bb.mesh);
g.draw(bb.tics);
glPopAttrib();
popMatrix(g);
}
void drawGrid(Graphics &g){
pushMatrix(g);
if(selected || hover){
g.lineWidth(2);
g.draw(bb.gridMesh[1]);
g.lineWidth(1);
g.draw(bb.gridMesh[0]);
} else {}
popMatrix(g);
}
void drawLabels(Graphics &g, Font& font, Pose &cam_pose){
if(!selected && !hover) return;
g.pushMatrix();
bb.drawLabels(g, font, cam_pose, pose, scale.x);
g.popMatrix();
}
void drawOrigin(Graphics &g){
Gnomon gnomon;
pushMatrix(g);
gnomon.draw(g);
popMatrix(g);
}
////////////////////////////////////////////////////////////////////////////
/// set the pickable's center position
void setCenter(Vec3f& pos){
updateAABB();
Vec3f offset = aabb.cen - pose.pos();
pose.pos().set(pos - offset);
}
/// set pickable's orientation maintaining same center position
void setQuat(Quatf& q){
updateAABB();
Vec3f cen;
cen.set(aabb.cen);
pose.quat().set(q);
setCenter(cen);
}
/// intersect ray with pickable BoundingBox
double intersectBB(Rayd &ray){
Rayd r = transformRayLocal(ray);
return r.intersectBox(bb.cen, bb.dim);
}
/// intersect ray with pickable AxisAlignedBoundingBox
double intersectAABB(Rayd &ray){
return ray.intersectBox(aabb.cen, aabb.dim);
}
/// intersect ray with bounding sphere
float intersectBoundingSphere(Rayd &ray){
return ray.intersectSphere( transformVecWorld(bb.cen), (bb.dim*scale).mag()/2.0);
}
/// calculate Axis aligned bounding box from mesh bounding box and current transforms
void updateAABB(){
// thanks to http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
Matrix4d t,r,s;
Matrix4d model = t.translate(pose.pos()) * r.fromQuat(pose.quat()) * s.scale(scale);
Matrix4d absModel(model);
for(int i=0; i<16; i++) absModel[i] = abs(absModel[i]);
Vec4d cen = model.transform(Vec4d(bb.cen, 1));
Vec4d dim = absModel.transform(Vec4d(bb.dim, 0));
aabb.setCenterDim(cen.sub<3>(0),dim.sub<3>(0));
}
};
} // ::al
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************/
/* CascRootFile_SC1.cpp Copyright (c) Ladislav Zezula 2017 */
/*---------------------------------------------------------------------------*/
/* Support for loading Starcraft 1 ROOT file */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 28.10.15 1.00 Lad The first version of CascRootFile_SC1.cpp */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "CascLib.h"
#include "CascCommon.h"
//-----------------------------------------------------------------------------
// Structure definitions for Overwatch root file
typedef struct _CASC_FILE_ENTRY
{
ENCODING_KEY EncodingKey; // Encoding key
ULONGLONG FileNameHash; // File name hash
DWORD dwFileName; // Offset of the file name in the name cache
} CASC_FILE_ENTRY, *PCASC_FILE_ENTRY;
struct TRootHandler_SC1 : public TRootHandler
{
// Linear global list of file entries
DYNAMIC_ARRAY FileTable;
// Linear global list of names
DYNAMIC_ARRAY FileNames;
// Global map of FileName -> FileEntry
PCASC_MAP pRootMap;
};
//-----------------------------------------------------------------------------
// Local functions
static int InsertFileEntry(
TRootHandler_SC1 * pRootHandler,
const char * szFileName,
LPBYTE pbEncodingKey)
{
PCASC_FILE_ENTRY pFileEntry;
size_t nLength = strlen(szFileName);
// Attempt to insert the file name to the global buffer
szFileName = (char *)Array_Insert(&pRootHandler->FileNames, szFileName, nLength + 1);
if(szFileName == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Attempt to insert the entry to the array of file entries
pFileEntry = (PCASC_FILE_ENTRY)Array_Insert(&pRootHandler->FileTable, NULL, 1);
if(pFileEntry == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Fill the file entry
pFileEntry->EncodingKey = *(PENCODING_KEY)pbEncodingKey;
pFileEntry->FileNameHash = CalcFileNameHash(szFileName);
pFileEntry->dwFileName = (DWORD)Array_IndexOf(&pRootHandler->FileNames, szFileName);
// Insert the file entry to the map
assert(Map_FindObject(pRootHandler->pRootMap, &pFileEntry->FileNameHash, NULL) == NULL);
Map_InsertObject(pRootHandler->pRootMap, pFileEntry, &pFileEntry->FileNameHash);
return ERROR_SUCCESS;
}
//-----------------------------------------------------------------------------
// Implementation of Overwatch root file
static int SC1Handler_Insert(
TRootHandler_SC1 * pRootHandler,
const char * szFileName,
LPBYTE pbEncodingKey)
{
return InsertFileEntry(pRootHandler, szFileName, pbEncodingKey);
}
static LPBYTE SC1Handler_Search(TRootHandler_SC1 * pRootHandler, TCascSearch * pSearch, PDWORD /* PtrFileSize */, PDWORD /* PtrLocaleFlags */, PDWORD /* PtrFileDataId */)
{
PCASC_FILE_ENTRY pFileEntry;
// Are we still inside the root directory range?
while(pSearch->IndexLevel1 < pRootHandler->FileTable.ItemCount)
{
// Retrieve the file item
pFileEntry = (PCASC_FILE_ENTRY)Array_ItemAt(&pRootHandler->FileTable, pSearch->IndexLevel1);
// Prepare the pointer to the next search
pSearch->IndexLevel1++;
char *filename = (char *)Array_ItemAt(&pRootHandler->FileNames, pFileEntry->dwFileName);
if (CheckWildCard(filename, pSearch->szMask)) {
strcpy(pSearch->szFileName, filename);
return pFileEntry->EncodingKey.Value;
}
}
// No more entries
return NULL;
}
static void SC1Handler_EndSearch(TRootHandler_SC1 * /* pRootHandler */, TCascSearch * /* pSearch */)
{
// Do nothing
}
static LPBYTE SC1Handler_GetKey(TRootHandler_SC1 * pRootHandler, const char * szFileName)
{
ULONGLONG FileNameHash = CalcFileNameHash(szFileName);
return (LPBYTE)Map_FindObject(pRootHandler->pRootMap, &FileNameHash, NULL);
}
static DWORD SC1Handler_GetFileId(TRootHandler_SC1 * /* pRootHandler */, const char * /* szFileName */)
{
// Not implemented for Overwatch
return 0;
}
static void SC1Handler_Close(TRootHandler_SC1 * pRootHandler)
{
if(pRootHandler != NULL)
{
// Free the file map
if(pRootHandler->pRootMap)
Map_Free(pRootHandler->pRootMap);
pRootHandler->pRootMap = NULL;
// Free the array of the file names and file items
Array_Free(&pRootHandler->FileTable);
Array_Free(&pRootHandler->FileNames);
// Free the root file itself
CASC_FREE(pRootHandler);
}
}
//-----------------------------------------------------------------------------
// Public functions
int RootHandler_CreateSC1(TCascStorage * hs, LPBYTE pbRootFile, DWORD cbRootFile)
{
TRootHandler_SC1 * pRootHandler;
ENCODING_KEY KeyBuffer;
QUERY_KEY EncodingKey = {KeyBuffer.Value, MD5_HASH_SIZE};
void * pTextFile;
size_t nLength;
char szOneLine[0x200];
char szFileName[MAX_PATH+1];
DWORD dwFileCountMax = (DWORD)hs->pEncodingMap->TableSize;
int nFileNameIndex;
int nError = ERROR_SUCCESS;
// Allocate the root handler object
hs->pRootHandler = pRootHandler = CASC_ALLOC(TRootHandler_SC1, 1);
if(pRootHandler == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Fill-in the handler functions
memset(pRootHandler, 0, sizeof(TRootHandler_SC1));
pRootHandler->Insert = (ROOT_INSERT)SC1Handler_Insert;
pRootHandler->Search = (ROOT_SEARCH)SC1Handler_Search;
pRootHandler->EndSearch = (ROOT_ENDSEARCH)SC1Handler_EndSearch;
pRootHandler->GetKey = (ROOT_GETKEY)SC1Handler_GetKey;
pRootHandler->Close = (ROOT_CLOSE)SC1Handler_Close;
pRootHandler->GetFileId = (ROOT_GETFILEID)SC1Handler_GetFileId;
// Fill-in the flags
pRootHandler->dwRootFlags |= ROOT_FLAG_HAS_NAMES;
// Allocate the linear array of file entries
nError = Array_Create(&pRootHandler->FileTable, CASC_FILE_ENTRY, 0x10000);
if(nError != ERROR_SUCCESS)
return nError;
// Allocate the buffer for the file names
nError = Array_Create(&pRootHandler->FileNames, char, 0x10000);
if(nError != ERROR_SUCCESS)
return nError;
// Create map of ROOT_ENTRY -> FileEntry
pRootHandler->pRootMap = Map_Create(dwFileCountMax, sizeof(ULONGLONG), FIELD_OFFSET(CASC_FILE_ENTRY, FileNameHash));
if(pRootHandler->pRootMap == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Parse the ROOT file
pTextFile = ListFile_FromBuffer(pbRootFile, cbRootFile);
if(pTextFile != NULL)
{
// Parse the next lines
while((nLength = ListFile_GetNextLine(pTextFile, szOneLine, _maxchars(szOneLine))) > 0)
{
LPSTR szEncodingKey;
BYTE EncodingKey[MD5_HASH_SIZE];
szEncodingKey = strchr(szOneLine, _T('|'));
if(szEncodingKey != NULL)
{
// Split the name and encoding key
*szEncodingKey++ = 0;
// Insert the entry to the map
ConvertStringToBinary(szEncodingKey, MD5_STRING_SIZE, EncodingKey);
InsertFileEntry(pRootHandler, szOneLine, EncodingKey);
}
}
// Free the listfile
ListFile_Free(pTextFile);
}
// Succeeded
return nError;
}
<commit_msg>Remove compilation warnings<commit_after>/*****************************************************************************/
/* CascRootFile_SC1.cpp Copyright (c) Ladislav Zezula 2017 */
/*---------------------------------------------------------------------------*/
/* Support for loading Starcraft 1 ROOT file */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 28.10.15 1.00 Lad The first version of CascRootFile_SC1.cpp */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "CascLib.h"
#include "CascCommon.h"
//-----------------------------------------------------------------------------
// Structure definitions for Overwatch root file
typedef struct _CASC_FILE_ENTRY
{
ENCODING_KEY EncodingKey; // Encoding key
ULONGLONG FileNameHash; // File name hash
DWORD dwFileName; // Offset of the file name in the name cache
} CASC_FILE_ENTRY, *PCASC_FILE_ENTRY;
struct TRootHandler_SC1 : public TRootHandler
{
// Linear global list of file entries
DYNAMIC_ARRAY FileTable;
// Linear global list of names
DYNAMIC_ARRAY FileNames;
// Global map of FileName -> FileEntry
PCASC_MAP pRootMap;
};
//-----------------------------------------------------------------------------
// Local functions
static int InsertFileEntry(
TRootHandler_SC1 * pRootHandler,
const char * szFileName,
LPBYTE pbEncodingKey)
{
PCASC_FILE_ENTRY pFileEntry;
size_t nLength = strlen(szFileName);
// Attempt to insert the file name to the global buffer
szFileName = (char *)Array_Insert(&pRootHandler->FileNames, szFileName, nLength + 1);
if(szFileName == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Attempt to insert the entry to the array of file entries
pFileEntry = (PCASC_FILE_ENTRY)Array_Insert(&pRootHandler->FileTable, NULL, 1);
if(pFileEntry == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Fill the file entry
pFileEntry->EncodingKey = *(PENCODING_KEY)pbEncodingKey;
pFileEntry->FileNameHash = CalcFileNameHash(szFileName);
pFileEntry->dwFileName = (DWORD)Array_IndexOf(&pRootHandler->FileNames, szFileName);
// Insert the file entry to the map
assert(Map_FindObject(pRootHandler->pRootMap, &pFileEntry->FileNameHash, NULL) == NULL);
Map_InsertObject(pRootHandler->pRootMap, pFileEntry, &pFileEntry->FileNameHash);
return ERROR_SUCCESS;
}
//-----------------------------------------------------------------------------
// Implementation of Overwatch root file
static int SC1Handler_Insert(
TRootHandler_SC1 * pRootHandler,
const char * szFileName,
LPBYTE pbEncodingKey)
{
return InsertFileEntry(pRootHandler, szFileName, pbEncodingKey);
}
static LPBYTE SC1Handler_Search(TRootHandler_SC1 * pRootHandler, TCascSearch * pSearch, PDWORD /* PtrFileSize */, PDWORD /* PtrLocaleFlags */, PDWORD /* PtrFileDataId */)
{
PCASC_FILE_ENTRY pFileEntry;
// Are we still inside the root directory range?
while(pSearch->IndexLevel1 < pRootHandler->FileTable.ItemCount)
{
// Retrieve the file item
pFileEntry = (PCASC_FILE_ENTRY)Array_ItemAt(&pRootHandler->FileTable, pSearch->IndexLevel1);
// Prepare the pointer to the next search
pSearch->IndexLevel1++;
char *filename = (char *)Array_ItemAt(&pRootHandler->FileNames, pFileEntry->dwFileName);
if (CheckWildCard(filename, pSearch->szMask)) {
strcpy(pSearch->szFileName, filename);
return pFileEntry->EncodingKey.Value;
}
}
// No more entries
return NULL;
}
static void SC1Handler_EndSearch(TRootHandler_SC1 * /* pRootHandler */, TCascSearch * /* pSearch */)
{
// Do nothing
}
static LPBYTE SC1Handler_GetKey(TRootHandler_SC1 * pRootHandler, const char * szFileName)
{
ULONGLONG FileNameHash = CalcFileNameHash(szFileName);
return (LPBYTE)Map_FindObject(pRootHandler->pRootMap, &FileNameHash, NULL);
}
static DWORD SC1Handler_GetFileId(TRootHandler_SC1 * /* pRootHandler */, const char * /* szFileName */)
{
// Not implemented for Overwatch
return 0;
}
static void SC1Handler_Close(TRootHandler_SC1 * pRootHandler)
{
if(pRootHandler != NULL)
{
// Free the file map
if(pRootHandler->pRootMap)
Map_Free(pRootHandler->pRootMap);
pRootHandler->pRootMap = NULL;
// Free the array of the file names and file items
Array_Free(&pRootHandler->FileTable);
Array_Free(&pRootHandler->FileNames);
// Free the root file itself
CASC_FREE(pRootHandler);
}
}
//-----------------------------------------------------------------------------
// Public functions
int RootHandler_CreateSC1(TCascStorage * hs, LPBYTE pbRootFile, DWORD cbRootFile)
{
TRootHandler_SC1 * pRootHandler;
ENCODING_KEY KeyBuffer;
QUERY_KEY EncodingKey = {KeyBuffer.Value, MD5_HASH_SIZE};
void * pTextFile;
size_t nLength;
char szOneLine[0x200];
DWORD dwFileCountMax = (DWORD)hs->pEncodingMap->TableSize;
int nError = ERROR_SUCCESS;
// Allocate the root handler object
hs->pRootHandler = pRootHandler = CASC_ALLOC(TRootHandler_SC1, 1);
if(pRootHandler == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Fill-in the handler functions
memset(pRootHandler, 0, sizeof(TRootHandler_SC1));
pRootHandler->Insert = (ROOT_INSERT)SC1Handler_Insert;
pRootHandler->Search = (ROOT_SEARCH)SC1Handler_Search;
pRootHandler->EndSearch = (ROOT_ENDSEARCH)SC1Handler_EndSearch;
pRootHandler->GetKey = (ROOT_GETKEY)SC1Handler_GetKey;
pRootHandler->Close = (ROOT_CLOSE)SC1Handler_Close;
pRootHandler->GetFileId = (ROOT_GETFILEID)SC1Handler_GetFileId;
// Fill-in the flags
pRootHandler->dwRootFlags |= ROOT_FLAG_HAS_NAMES;
// Allocate the linear array of file entries
nError = Array_Create(&pRootHandler->FileTable, CASC_FILE_ENTRY, 0x10000);
if(nError != ERROR_SUCCESS)
return nError;
// Allocate the buffer for the file names
nError = Array_Create(&pRootHandler->FileNames, char, 0x10000);
if(nError != ERROR_SUCCESS)
return nError;
// Create map of ROOT_ENTRY -> FileEntry
pRootHandler->pRootMap = Map_Create(dwFileCountMax, sizeof(ULONGLONG), FIELD_OFFSET(CASC_FILE_ENTRY, FileNameHash));
if(pRootHandler->pRootMap == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Parse the ROOT file
pTextFile = ListFile_FromBuffer(pbRootFile, cbRootFile);
if(pTextFile != NULL)
{
// Parse the next lines
while((nLength = ListFile_GetNextLine(pTextFile, szOneLine, _maxchars(szOneLine))) > 0)
{
LPSTR szEncodingKey;
BYTE EncodingKey[MD5_HASH_SIZE];
szEncodingKey = strchr(szOneLine, _T('|'));
if(szEncodingKey != NULL)
{
// Split the name and encoding key
*szEncodingKey++ = 0;
// Insert the entry to the map
ConvertStringToBinary(szEncodingKey, MD5_STRING_SIZE, EncodingKey);
InsertFileEntry(pRootHandler, szOneLine, EncodingKey);
}
}
// Free the listfile
ListFile_Free(pTextFile);
}
// Succeeded
return nError;
}
<|endoftext|> |
<commit_before>/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit3(boost::thread_group& threadGroup) {
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#if defined (__SVR4) && defined (__sun)
// ignore SIGPIPE on Solaris
signal(SIGPIPE, SIG_IGN);
#endif
// ********************************************************* Step 2: parameter interactions
// Make sure enough file descriptors are available
int nBind = 1;
nMaxConnections = 125;
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS) {
return InitError(_("Not enough file descriptors available."));
}
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) {
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
}
// ********************************************************* Step 3: parameter-to-internal-flags
// Checkmempool defaults to true in regtest mode
mempool.setSanityCheck(Params().DefaultCheckMemPool());
Checkpoints::fEnabled = true;
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = DEFAULT_SCRIPTCHECK_THREADS;
if (nScriptCheckThreads <= 0) {
nScriptCheckThreads += boost::thread::hardware_concurrency();
}
if (nScriptCheckThreads <= 1) {
nScriptCheckThreads = 0;
} else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) {
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
}
fServer = true;
fPrintToConsole = false;
fLogTimestamps = true;
fLogIPs = false;
setvbuf(stdout, NULL, _IOLBF, 0);
#ifdef ENABLE_WALLET
bool fDisableWallet = false;
#endif
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
#ifdef ENABLE_WALLET
std::string strWalletFile = "wallet.dat";
#endif
// *********************************************************
// Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Sanity check
if (!InitSanityCheck()) {
return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
}
std::string strDataDir = GetDataDir().string();
#ifdef ENABLE_WALLET
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) {
return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
}
#endif
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock()) {
return InitError(strprintf(_(
"Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
}
if (nScriptCheckThreads) {
for (int i = 0; i < nScriptCheckThreads - 1; i++) {
threadGroup.create_thread(&ThreadScriptCheck);
}
}
int64_t nStart;
// ********************************************************* Step 5: verify wallet database integrity
#ifdef ENABLE_WALLET
if (!fDisableWallet) {
if (!bitdb.Open(GetDataDir())) {
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
return InitError(msg);
}
}
if (filesystem::exists(GetDataDir() / strWalletFile)) {
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK) {
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir);
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL) {
return InitError(_("wallet.dat corrupt, salvage failed"));
}
}
}
#endif // ENABLE_WALLET
// ********************************************************* Step 6: network initialization
RegisterNodeSignals(GetNodeSignals());
bool fBound = false;
if (fListen) {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
if (!fBound) {
return InitError(_("Failed to listen on any port."));
}
}
// ********************************************************* Step 7: load block chain
fReindex = false;
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
break;
}
}
if (linked) {
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = nDefaultDbCache << 20;
if (nTotalCache < (nMinDbCache << 20)) {
nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache
} else if (nTotalCache > (nMaxDbCache << 20)) {
nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache
}
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21)) {
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
}
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex) {
pblocktree->WriteReindexing(true);
}
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != false) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
if (!CVerifyDB().VerifyDB(3, 288)) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
if (!fReset) {
// reindex or return
fReindex = true;
fRequestShutdown = false;
// return false;
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown) {
return false;
}
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein = CAutoFile(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (est_filein) {
mempool.ReadFeeEstimates(est_filein);
}
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
if (fDisableWallet) {
pwalletMain = NULL;
} else {
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFile);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK) {
if (nLoadWalletRet == DB_CORRUPT) {
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
} else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) {
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
} else if (nLoadWalletRet == DB_TOO_NEW) {
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
} else if (nLoadWalletRet == DB_NEED_REWRITE) {
strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
return InitError(strErrors.str());
} else {
strErrors << _("Error loading wallet.dat") << "\n";
}
}
if (fFirstRun) {
int nMaxVersion = 0;
if (nMaxVersion == 0) {
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
} else {
if (nMaxVersion < pwalletMain->GetVersion()) {
strErrors << _("Cannot downgrade wallet") << "\n";
}
}
pwalletMain->SetMaxVersion(nMaxVersion);
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) {
strErrors << _("Cannot write default address") << "\n";
}
}
pwalletMain->SetBestChain(chainActive.GetLocator());
}
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = chainActive.Tip();
CWalletDB walletdb(strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator)) {
pindexRescan = chainActive.FindFork(locator);
} else {
pindexRescan = chainActive.Genesis();
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan) {
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
pwalletMain->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
}
}
#endif
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state)) {
strErrors << "Failed to connect best block";
}
std::vector<boost::filesystem::path> vImportFiles;
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
nStart = GetTimeMillis();
{
CAddrDB adb;
adb.Read(addrman);
}
// ********************************************************* Step 11: start node
if (!CheckDiskSpace()) {
return false;
}
if (!strErrors.str().empty()) {
return InitError(strErrors.str());
}
RandAddSeedPerfmon();
StartNode(threadGroup);
if (fServer) {
StartRPCThreads();
}
#ifdef ENABLE_WALLET
// Generate coins in the background
if (pwalletMain) {
GenerateBitcoins(false, pwalletMain, -1);
}
#endif
// ********************************************************* Step 12: finished
#ifdef ENABLE_WALLET
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
#endif
return !fRequestShutdown;
}
<commit_msg>drop warnings.<commit_after>/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit3(boost::thread_group& threadGroup) {
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#if defined (__SVR4) && defined (__sun)
// ignore SIGPIPE on Solaris
signal(SIGPIPE, SIG_IGN);
#endif
// ********************************************************* Step 2: parameter interactions
// Make sure enough file descriptors are available
int nBind = 1;
nMaxConnections = 125;
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS) {
return InitError(_("Not enough file descriptors available."));
}
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) {
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
}
// ********************************************************* Step 3: parameter-to-internal-flags
// Checkmempool defaults to true in regtest mode
mempool.setSanityCheck(Params().DefaultCheckMemPool());
Checkpoints::fEnabled = true;
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = DEFAULT_SCRIPTCHECK_THREADS;
if (nScriptCheckThreads <= 0) {
nScriptCheckThreads += boost::thread::hardware_concurrency();
}
if (nScriptCheckThreads <= 1) {
nScriptCheckThreads = 0;
} else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) {
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
}
fServer = true;
fPrintToConsole = false;
fLogTimestamps = true;
fLogIPs = false;
setvbuf(stdout, NULL, _IOLBF, 0);
#ifdef ENABLE_WALLET
bool fDisableWallet = false;
#endif
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
#ifdef ENABLE_WALLET
std::string strWalletFile = "wallet.dat";
#endif
// *********************************************************
// Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Sanity check
if (!InitSanityCheck()) {
return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
}
std::string strDataDir = GetDataDir().string();
#ifdef ENABLE_WALLET
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) {
return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
}
#endif
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock()) {
return InitError(strprintf(_(
"Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
}
if (nScriptCheckThreads) {
for (int i = 0; i < nScriptCheckThreads - 1; i++) {
threadGroup.create_thread(&ThreadScriptCheck);
}
}
int64_t nStart;
// ********************************************************* Step 5: verify wallet database integrity
#ifdef ENABLE_WALLET
if (!fDisableWallet) {
if (!bitdb.Open(GetDataDir())) {
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
return InitError(msg);
}
}
if (filesystem::exists(GetDataDir() / strWalletFile)) {
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK) {
// Warning: wallet.dat corrupt, data salvaged!
// Original wallet.dat saved as wallet.{timestamp}.bak in data dir; if
// your balance or transactions are incorrect you should
// restore from a backup.
}
if (r == CDBEnv::RECOVER_FAIL) {
return InitError(_("wallet.dat corrupt, salvage failed"));
}
}
}
#endif // ENABLE_WALLET
// ********************************************************* Step 6: network initialization
RegisterNodeSignals(GetNodeSignals());
bool fBound = false;
if (fListen) {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
if (!fBound) {
return InitError(_("Failed to listen on any port."));
}
}
// ********************************************************* Step 7: load block chain
fReindex = false;
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
break;
}
}
if (linked) {
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = nDefaultDbCache << 20;
if (nTotalCache < (nMinDbCache << 20)) {
nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache
} else if (nTotalCache > (nMaxDbCache << 20)) {
nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache
}
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21)) {
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
}
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex) {
pblocktree->WriteReindexing(true);
}
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL) {
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
}
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != false) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
if (!CVerifyDB().VerifyDB(3, 288)) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
if (!fReset) {
// reindex or return
fReindex = true;
fRequestShutdown = false;
// return false;
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown) {
return false;
}
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein = CAutoFile(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (est_filein) {
mempool.ReadFeeEstimates(est_filein);
}
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
if (fDisableWallet) {
pwalletMain = NULL;
} else {
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFile);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK) {
if (nLoadWalletRet == DB_CORRUPT) {
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
} else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) {
// Warning: error reading wallet.dat! All keys read correctly, but transaction data
// or address book entries might be missing or incorrect.
} else if (nLoadWalletRet == DB_TOO_NEW) {
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
} else if (nLoadWalletRet == DB_NEED_REWRITE) {
strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
return InitError(strErrors.str());
} else {
strErrors << _("Error loading wallet.dat") << "\n";
}
}
if (fFirstRun) {
int nMaxVersion = 0;
if (nMaxVersion == 0) {
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
} else {
if (nMaxVersion < pwalletMain->GetVersion()) {
strErrors << _("Cannot downgrade wallet") << "\n";
}
}
pwalletMain->SetMaxVersion(nMaxVersion);
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) {
strErrors << _("Cannot write default address") << "\n";
}
}
pwalletMain->SetBestChain(chainActive.GetLocator());
}
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = chainActive.Tip();
CWalletDB walletdb(strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator)) {
pindexRescan = chainActive.FindFork(locator);
} else {
pindexRescan = chainActive.Genesis();
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan) {
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
pwalletMain->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
}
}
#endif
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state)) {
strErrors << "Failed to connect best block";
}
std::vector<boost::filesystem::path> vImportFiles;
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
nStart = GetTimeMillis();
{
CAddrDB adb;
adb.Read(addrman);
}
// ********************************************************* Step 11: start node
if (!CheckDiskSpace()) {
return false;
}
if (!strErrors.str().empty()) {
return InitError(strErrors.str());
}
RandAddSeedPerfmon();
StartNode(threadGroup);
if (fServer) {
StartRPCThreads();
}
#ifdef ENABLE_WALLET
// Generate coins in the background
if (pwalletMain) {
GenerateBitcoins(false, pwalletMain, -1);
}
#endif
// ********************************************************* Step 12: finished
#ifdef ENABLE_WALLET
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
#endif
return !fRequestShutdown;
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <map>
#include <set>
#include "bandit/bandit.h"
using std::map;
using std::set;
static bool _enabled = false;
static size_t _allocation_count = 0;
static map<void *, size_t> _outstanding_allocations;
namespace record_alloc {
void start() {
_enabled = true;
_allocation_count = 0;
_outstanding_allocations.clear();
}
void stop() {
_enabled = false;
}
set<size_t> outstanding_allocation_indices() {
set<size_t> result;
for (const auto &entry : _outstanding_allocations) {
result.insert(entry.second);
}
return result;
}
size_t allocation_count() {
return _allocation_count;
}
} // namespace record_alloc
extern "C" {
static void *record_allocation(void *result) {
if (!_enabled)
return result;
_outstanding_allocations[result] = _allocation_count;
_allocation_count++;
return result;
}
static void record_deallocation(void *pointer) {
if (!_enabled)
return;
auto entry = _outstanding_allocations.find(pointer);
if (entry != _outstanding_allocations.end()) {
_outstanding_allocations.erase(entry);
}
}
void *ts_record_malloc(size_t size) {
return record_allocation(malloc(size));
}
void *ts_record_realloc(void *pointer, size_t size) {
record_deallocation(pointer);
return record_allocation(realloc(pointer, size));
}
void *ts_record_calloc(size_t count, size_t size) {
return record_allocation(calloc(count, size));
}
void ts_record_free(void *pointer) {
free(pointer);
record_deallocation(pointer);
}
bool ts_record_allocations_toggle(bool value) {
bool previous_value = _enabled;
_enabled = value;
return previous_value;
}
}
<commit_msg>Silence false-positive warning in ts_record_free<commit_after>#include <stdlib.h>
#include <map>
#include <set>
#include "bandit/bandit.h"
using std::map;
using std::set;
static bool _enabled = false;
static size_t _allocation_count = 0;
static map<void *, size_t> _outstanding_allocations;
namespace record_alloc {
void start() {
_enabled = true;
_allocation_count = 0;
_outstanding_allocations.clear();
}
void stop() {
_enabled = false;
}
set<size_t> outstanding_allocation_indices() {
set<size_t> result;
for (const auto &entry : _outstanding_allocations) {
result.insert(entry.second);
}
return result;
}
size_t allocation_count() {
return _allocation_count;
}
} // namespace record_alloc
extern "C" {
static void *record_allocation(void *result) {
if (!_enabled)
return result;
_outstanding_allocations[result] = _allocation_count;
_allocation_count++;
return result;
}
static void record_deallocation(void *pointer) {
if (!_enabled)
return;
auto entry = _outstanding_allocations.find(pointer);
if (entry != _outstanding_allocations.end()) {
_outstanding_allocations.erase(entry);
}
}
void *ts_record_malloc(size_t size) {
return record_allocation(malloc(size));
}
void *ts_record_realloc(void *pointer, size_t size) {
record_deallocation(pointer);
return record_allocation(realloc(pointer, size));
}
void *ts_record_calloc(size_t count, size_t size) {
return record_allocation(calloc(count, size));
}
void ts_record_free(void *pointer) {
record_deallocation(pointer);
free(pointer);
}
bool ts_record_allocations_toggle(bool value) {
bool previous_value = _enabled;
_enabled = value;
return previous_value;
}
}
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "main.hxx"
#include <dune/stuff/common/timedlogging.hh>
using namespace Dune;
using namespace Dune::Stuff;
using namespace Dune::Stuff::Common;
void before_create()
{
TimedLogger().get("before_create").info() << "this info should not be visible" << std::endl;
TimedLogger().get("before_create").debug() << "this debug should not be visible" << std::endl;
TimedLogger().get("before_create").warn() << "this warning should be visible in red" << std::endl;
}
void after_create_inner()
{
TimedLogger().get("after_create_inner").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("after_create_inner").debug() << "this debug should not be visible" << std::endl;
TimedLogger().get("after_create_inner").warn() << "this warning should not be visible" << std::endl;
}
void after_create()
{
auto logger = TimedLogger().get("after_create");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
after_create_inner();
}
void fool_level_tracking_inner()
{
TimedLogger().get("fool_level_tracking_inner").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("fool_level_tracking_inner").debug() << "this debug should be visible in yellow" << std::endl;
TimedLogger().get("fool_level_tracking_inner").warn() << "this warning should not be visible" << std::endl;
}
void fool_level_tracking()
{
TimedLogger().get("fool_level_tracking").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("fool_level_tracking").debug() << "this debug should be visible in yellow" << std::endl;
TimedLogger().get("fool_level_tracking").warn() << "this warning should not be visible" << std::endl;
fool_level_tracking_inner();
}
TEST(TimedPrefixedLogStream, all)
{
Timer timer;
TimedPrefixedLogStream out(timer, "prefix: ", std::cout);
out << "sample\nline" << std::flush;
busywait(2000);
out << "\n" << 3 << "\n\nend" << std::endl;
} // TEST(TimedPrefixedLogStream, all)
TEST(TimedLogger, before_create)
{
auto logger = TimedLogger().get("main");
auto& info = logger.info();
info << "this info should be visible in " << TimedLogging::default_info_color() << std::endl;
logger.debug() << "this debug should not be visible" << std::endl;
logger.warn() << "this warning should be visible in " << TimedLogging::default_warning_color() << std::endl;
before_create();
}
TEST(TimedLogger, after_create)
{
TimedLogger().create(10, 1, false, true, "blue", "yellow");
auto logger = TimedLogger().get("main");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
after_create();
}
TEST(TimedLogger, fool_level_tracking)
{
auto logger = TimedLogger().get("");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
fool_level_tracking();
}
<commit_msg>[test.common_timedlogging] do not use man.hxx<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 0
#endif
#include "config.h"
#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/common/timedlogging.hh>
#include "common.hh"
using namespace Dune;
using namespace Dune::Stuff;
using namespace Dune::Stuff::Common;
void before_create()
{
TimedLogger().get("before_create").info() << "this info should not be visible" << std::endl;
TimedLogger().get("before_create").debug() << "this debug should not be visible" << std::endl;
TimedLogger().get("before_create").warn() << "this warning should be visible in red" << std::endl;
}
void after_create_inner()
{
TimedLogger().get("after_create_inner").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("after_create_inner").debug() << "this debug should not be visible" << std::endl;
TimedLogger().get("after_create_inner").warn() << "this warning should not be visible" << std::endl;
}
void after_create()
{
auto logger = TimedLogger().get("after_create");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
after_create_inner();
}
void fool_level_tracking_inner()
{
TimedLogger().get("fool_level_tracking_inner").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("fool_level_tracking_inner").debug() << "this debug should be visible in yellow" << std::endl;
TimedLogger().get("fool_level_tracking_inner").warn() << "this warning should not be visible" << std::endl;
}
void fool_level_tracking()
{
TimedLogger().get("fool_level_tracking").info() << "this info should be visible in blue" << std::endl;
TimedLogger().get("fool_level_tracking").debug() << "this debug should be visible in yellow" << std::endl;
TimedLogger().get("fool_level_tracking").warn() << "this warning should not be visible" << std::endl;
fool_level_tracking_inner();
}
TEST(TimedPrefixedLogStream, all)
{
Timer timer;
TimedPrefixedLogStream out(timer, "prefix: ", std::cout);
out << "sample\nline" << std::flush;
busywait(2000);
out << "\n" << 3 << "\n\nend" << std::endl;
} // TEST(TimedPrefixedLogStream, all)
TEST(TimedLogger, before_create)
{
auto logger = TimedLogger().get("main");
auto& info = logger.info();
info << "this info should be visible in " << TimedLogging::default_info_color() << std::endl;
logger.debug() << "this debug should not be visible" << std::endl;
logger.warn() << "this warning should be visible in " << TimedLogging::default_warning_color() << std::endl;
before_create();
}
TEST(TimedLogger, after_create)
{
TimedLogger().create(10, 1, false, true, "blue", "yellow");
auto logger = TimedLogger().get("main");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
after_create();
}
TEST(TimedLogger, fool_level_tracking)
{
auto logger = TimedLogger().get("");
logger.info() << "this info should be visible in blue" << std::endl;
logger.debug() << "this debug should be visible in yellow" << std::endl;
logger.warn() << "this warning should not be visible" << std::endl;
fool_level_tracking();
}
int main(int argc, char** argv)
{
#if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
try {
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
#if DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
#endif // DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
} // ... main(...)
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fblocks -emit-llvm %s -o - -cxx-abi microsoft -triple=i386-pc-win32 | FileCheck %s
// RUN: %clang_cc1 -fblocks -emit-llvm %s -o - -cxx-abi microsoft -triple=x86_64-pc-win32 | FileCheck -check-prefix X64 %s
// CHECK: @"\01?a@@3HA"
// CHECK: @"\01?b@N@@3HA"
// CHECK: @"\01?anonymous@?A@N@@3HA"
// CHECK: @c
// CHECK: @"\01?d@foo@@0FB"
// CHECK: @"\01?e@foo@@1JC"
// CHECK: @"\01?f@foo@@2DD"
// CHECK: @"\01?g@bar@@2HA"
// CHECK: @"\01?h1@@3QAHA"
// CHECK: @"\01?h2@@3QBHB"
// CHECK: @"\01?i@@3PAY0BE@HA"
// CHECK: @"\01?j@@3P6GHCE@ZA"
// X64: @"\01?k@@3PETfoo@@DET1@"
// CHECK: @"\01?l@@3P8foo@@AEHH@ZQ1@"
// CHECK: @"\01?color1@@3PANA"
// CHECK: @"\01?color2@@3QBNB"
// CHECK: @"\01?color3@@3QAY02$$CBNA"
// CHECK: @"\01?color4@@3QAY02$$CBNA"
// X64: @"\01?memptr1@@3RESB@@HES1@"
// X64: @"\01?memptr2@@3PESB@@HES1@"
// X64: @"\01?memptr3@@3REQB@@HEQ1@"
// X64: @"\01?funmemptr1@@3RESB@@R6AHXZES1@"
// X64: @"\01?funmemptr2@@3PESB@@R6AHXZES1@"
// X64: @"\01?funmemptr3@@3REQB@@P6AHXZEQ1@"
// X64: @"\01?memptrtofun1@@3R8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun2@@3P8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun3@@3P8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun4@@3R8B@@EAAHXZEQ1@"
// X64: @"\01?memptrtofun5@@3P8B@@EAA?CHXZEQ1@"
// X64: @"\01?memptrtofun6@@3P8B@@EAA?BHXZEQ1@"
// X64: @"\01?memptrtofun7@@3R8B@@EAAP6AHXZXZEQ1@"
// X64: @"\01?memptrtofun8@@3P8B@@EAAR6AHXZXZEQ1@"
// X64: @"\01?memptrtofun9@@3P8B@@EAAQ6AHXZXZEQ1@"
int a;
namespace N {
int b;
namespace {
int anonymous;
}
}
static int c;
int _c(void) {return N::anonymous + c;}
// CHECK: @"\01?_c@@YAHXZ"
// X64: @"\01?_c@@YAHXZ"
class foo {
static const short d;
protected:
static volatile long e;
public:
static const volatile char f;
int operator+(int a);
foo(){}
//CHECK: @"\01??0foo@@QAE@XZ"
//X64: @"\01??0foo@@QEAA@XZ"
~foo(){}
//CHECK: @"\01??1foo@@QAE@XZ"
//X64: @"\01??1foo@@QEAA@XZ
foo(int i){}
//CHECK: @"\01??0foo@@QAE@H@Z"
//X64: @"\01??0foo@@QEAA@H@Z"
foo(char *q){}
//CHECK: @"\01??0foo@@QAE@PAD@Z"
//X64: @"\01??0foo@@QEAA@PEAD@Z"
static foo* static_method() { return 0; }
}f,s1(1),s2((char*)0);
typedef foo (foo2);
struct bar {
static int g;
};
union baz {
int a;
char b;
double c;
};
enum quux {
qone,
qtwo,
qthree
};
foo bar() { return foo(); }
//CHECK: @"\01?bar@@YA?AVfoo@@XZ"
//X64: @"\01?bar@@YA?AVfoo@@XZ"
int foo::operator+(int a) {
//CHECK: @"\01??Hfoo@@QAEHH@Z"
//X64: @"\01??Hfoo@@QEAAHH@Z"
foo::static_method();
//CHECK: @"\01?static_method@foo@@SAPAV1@XZ"
//X64: @"\01?static_method@foo@@SAPEAV1@XZ"
bar();
return a;
}
const short foo::d = 0;
volatile long foo::e;
const volatile char foo::f = 'C';
int bar::g;
extern int * const h1 = &a;
extern const int * const h2 = &a;
int i[10][20];
int (__stdcall *j)(signed char, unsigned char);
const volatile char foo2::*k;
int (foo2::*l)(int);
// Static functions are mangled, too.
// Also make sure calling conventions, arglists, and throw specs work.
static void __stdcall alpha(float a, double b) throw() {}
bool __fastcall beta(long long a, wchar_t b) throw(signed char, unsigned char) {
// CHECK: @"\01?beta@@YI_N_J_W@Z"
// X64: @"\01?beta@@YA_N_J_W@Z"
alpha(0.f, 0.0);
return false;
}
// CHECK: @"\01?alpha@@YGXMN@Z"
// X64: @"\01?alpha@@YAXMN@Z"
// Make sure tag-type mangling works.
void gamma(class foo, struct bar, union baz, enum quux) {}
// CHECK: @"\01?gamma@@YAXVfoo@@Ubar@@Tbaz@@W4quux@@@Z"
// X64: @"\01?gamma@@YAXVfoo@@Ubar@@Tbaz@@W4quux@@@Z"
// Make sure pointer/reference-type mangling works.
void delta(int * const a, const long &) {}
// CHECK: @"\01?delta@@YAXQAHABJ@Z"
// X64: @"\01?delta@@YAXQEAHAEBJ@Z"
// Array mangling.
void epsilon(int a[][10][20]) {}
// CHECK: @"\01?epsilon@@YAXQAY19BE@H@Z"
// X64: @"\01?epsilon@@YAXQEAY19BE@H@Z"
void zeta(int (*)(int, int)) {}
// CHECK: @"\01?zeta@@YAXP6AHHH@Z@Z"
// X64: @"\01?zeta@@YAXP6AHHH@Z@Z"
// Blocks mangling (Clang extension). A block should be mangled slightly
// differently from a similar function pointer.
void eta(int (^)(int, int)) {}
// CHECK: @"\01?eta@@YAXP_EAHHH@Z@Z"
typedef int theta_arg(int,int);
void theta(theta_arg^ block) {}
// CHECK: @"\01?theta@@YAXP_EAHHH@Z@Z"
void operator_new_delete() {
char *ptr = new char;
// CHECK: @"\01??2@YAPAXI@Z"
delete ptr;
// CHECK: @"\01??3@YAXPAX@Z"
char *array = new char[42];
// CHECK: @"\01??_U@YAPAXI@Z"
delete [] array;
// CHECK: @"\01??_V@YAXPAX@Z"
}
// PR13022
void (redundant_parens)();
void redundant_parens_use() { redundant_parens(); }
// CHECK: @"\01?redundant_parens@@YAXXZ"
// X64: @"\01?redundant_parens@@YAXXZ"
// PR13047
typedef double RGB[3];
RGB color1;
extern const RGB color2 = {};
extern RGB const color3[5] = {};
extern RGB const ((color4)[5]) = {};
struct B;
volatile int B::* volatile memptr1;
volatile int B::* memptr2;
int B::* volatile memptr3;
typedef int (*fun)();
volatile fun B::* volatile funmemptr1;
volatile fun B::* funmemptr2;
fun B::* volatile funmemptr3;
void (B::* volatile memptrtofun1)();
const void (B::* memptrtofun2)();
volatile void (B::* memptrtofun3)();
int (B::* volatile memptrtofun4)();
volatile int (B::* memptrtofun5)();
const int (B::* memptrtofun6)();
fun (B::* volatile memptrtofun7)();
volatile fun (B::* memptrtofun8)();
const fun (B::* memptrtofun9)();
// PR12603
enum E {};
// CHECK: "\01?fooE@@YA?AW4E@@XZ"
// X64: "\01?fooE@@YA?AW4E@@XZ"
E fooE() { return E(); }
class X {};
// CHECK: "\01?fooX@@YA?AVX@@XZ"
// X64: "\01?fooX@@YA?AVX@@XZ"
X fooX() { return X(); }
namespace PR13182 {
extern char s0[];
// CHECK: @"\01?s0@PR13182@@3PADA"
extern char s1[42];
// CHECK: @"\01?s1@PR13182@@3PADA"
extern const char s2[];
// CHECK: @"\01?s2@PR13182@@3QBDB"
extern const char s3[42];
// CHECK: @"\01?s3@PR13182@@3QBDB"
extern volatile char s4[];
// CHECK: @"\01?s4@PR13182@@3RCDC"
extern const volatile char s5[];
// CHECK: @"\01?s5@PR13182@@3SDDD"
extern const char* const* s6;
// CHECK: @"\01?s6@PR13182@@3PBQBDB"
char foo() {
return s0[0] + s1[0] + s2[0] + s3[0] + s4[0] + s5[0] + s6[0][0];
}
}
<commit_msg>Add back a test that was removed in r188450<commit_after>// RUN: %clang_cc1 -fblocks -emit-llvm %s -o - -cxx-abi microsoft -triple=i386-pc-win32 | FileCheck %s
// RUN: %clang_cc1 -fblocks -emit-llvm %s -o - -cxx-abi microsoft -triple=x86_64-pc-win32 | FileCheck -check-prefix X64 %s
// CHECK: @"\01?a@@3HA"
// CHECK: @"\01?b@N@@3HA"
// CHECK: @"\01?anonymous@?A@N@@3HA"
// CHECK: @c
// CHECK: @"\01?d@foo@@0FB"
// CHECK: @"\01?e@foo@@1JC"
// CHECK: @"\01?f@foo@@2DD"
// CHECK: @"\01?g@bar@@2HA"
// CHECK: @"\01?h1@@3QAHA"
// CHECK: @"\01?h2@@3QBHB"
// CHECK: @"\01?i@@3PAY0BE@HA"
// CHECK: @"\01?j@@3P6GHCE@ZA"
// CHECK: @"\01?k@@3PTfoo@@DT1@"
// X64: @"\01?k@@3PETfoo@@DET1@"
// CHECK: @"\01?l@@3P8foo@@AEHH@ZQ1@"
// CHECK: @"\01?color1@@3PANA"
// CHECK: @"\01?color2@@3QBNB"
// CHECK: @"\01?color3@@3QAY02$$CBNA"
// CHECK: @"\01?color4@@3QAY02$$CBNA"
// X64: @"\01?memptr1@@3RESB@@HES1@"
// X64: @"\01?memptr2@@3PESB@@HES1@"
// X64: @"\01?memptr3@@3REQB@@HEQ1@"
// X64: @"\01?funmemptr1@@3RESB@@R6AHXZES1@"
// X64: @"\01?funmemptr2@@3PESB@@R6AHXZES1@"
// X64: @"\01?funmemptr3@@3REQB@@P6AHXZEQ1@"
// X64: @"\01?memptrtofun1@@3R8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun2@@3P8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun3@@3P8B@@EAAXXZEQ1@"
// X64: @"\01?memptrtofun4@@3R8B@@EAAHXZEQ1@"
// X64: @"\01?memptrtofun5@@3P8B@@EAA?CHXZEQ1@"
// X64: @"\01?memptrtofun6@@3P8B@@EAA?BHXZEQ1@"
// X64: @"\01?memptrtofun7@@3R8B@@EAAP6AHXZXZEQ1@"
// X64: @"\01?memptrtofun8@@3P8B@@EAAR6AHXZXZEQ1@"
// X64: @"\01?memptrtofun9@@3P8B@@EAAQ6AHXZXZEQ1@"
int a;
namespace N {
int b;
namespace {
int anonymous;
}
}
static int c;
int _c(void) {return N::anonymous + c;}
// CHECK: @"\01?_c@@YAHXZ"
// X64: @"\01?_c@@YAHXZ"
class foo {
static const short d;
protected:
static volatile long e;
public:
static const volatile char f;
int operator+(int a);
foo(){}
//CHECK: @"\01??0foo@@QAE@XZ"
//X64: @"\01??0foo@@QEAA@XZ"
~foo(){}
//CHECK: @"\01??1foo@@QAE@XZ"
//X64: @"\01??1foo@@QEAA@XZ
foo(int i){}
//CHECK: @"\01??0foo@@QAE@H@Z"
//X64: @"\01??0foo@@QEAA@H@Z"
foo(char *q){}
//CHECK: @"\01??0foo@@QAE@PAD@Z"
//X64: @"\01??0foo@@QEAA@PEAD@Z"
static foo* static_method() { return 0; }
}f,s1(1),s2((char*)0);
typedef foo (foo2);
struct bar {
static int g;
};
union baz {
int a;
char b;
double c;
};
enum quux {
qone,
qtwo,
qthree
};
foo bar() { return foo(); }
//CHECK: @"\01?bar@@YA?AVfoo@@XZ"
//X64: @"\01?bar@@YA?AVfoo@@XZ"
int foo::operator+(int a) {
//CHECK: @"\01??Hfoo@@QAEHH@Z"
//X64: @"\01??Hfoo@@QEAAHH@Z"
foo::static_method();
//CHECK: @"\01?static_method@foo@@SAPAV1@XZ"
//X64: @"\01?static_method@foo@@SAPEAV1@XZ"
bar();
return a;
}
const short foo::d = 0;
volatile long foo::e;
const volatile char foo::f = 'C';
int bar::g;
extern int * const h1 = &a;
extern const int * const h2 = &a;
int i[10][20];
int (__stdcall *j)(signed char, unsigned char);
const volatile char foo2::*k;
int (foo2::*l)(int);
// Static functions are mangled, too.
// Also make sure calling conventions, arglists, and throw specs work.
static void __stdcall alpha(float a, double b) throw() {}
bool __fastcall beta(long long a, wchar_t b) throw(signed char, unsigned char) {
// CHECK: @"\01?beta@@YI_N_J_W@Z"
// X64: @"\01?beta@@YA_N_J_W@Z"
alpha(0.f, 0.0);
return false;
}
// CHECK: @"\01?alpha@@YGXMN@Z"
// X64: @"\01?alpha@@YAXMN@Z"
// Make sure tag-type mangling works.
void gamma(class foo, struct bar, union baz, enum quux) {}
// CHECK: @"\01?gamma@@YAXVfoo@@Ubar@@Tbaz@@W4quux@@@Z"
// X64: @"\01?gamma@@YAXVfoo@@Ubar@@Tbaz@@W4quux@@@Z"
// Make sure pointer/reference-type mangling works.
void delta(int * const a, const long &) {}
// CHECK: @"\01?delta@@YAXQAHABJ@Z"
// X64: @"\01?delta@@YAXQEAHAEBJ@Z"
// Array mangling.
void epsilon(int a[][10][20]) {}
// CHECK: @"\01?epsilon@@YAXQAY19BE@H@Z"
// X64: @"\01?epsilon@@YAXQEAY19BE@H@Z"
void zeta(int (*)(int, int)) {}
// CHECK: @"\01?zeta@@YAXP6AHHH@Z@Z"
// X64: @"\01?zeta@@YAXP6AHHH@Z@Z"
// Blocks mangling (Clang extension). A block should be mangled slightly
// differently from a similar function pointer.
void eta(int (^)(int, int)) {}
// CHECK: @"\01?eta@@YAXP_EAHHH@Z@Z"
typedef int theta_arg(int,int);
void theta(theta_arg^ block) {}
// CHECK: @"\01?theta@@YAXP_EAHHH@Z@Z"
void operator_new_delete() {
char *ptr = new char;
// CHECK: @"\01??2@YAPAXI@Z"
delete ptr;
// CHECK: @"\01??3@YAXPAX@Z"
char *array = new char[42];
// CHECK: @"\01??_U@YAPAXI@Z"
delete [] array;
// CHECK: @"\01??_V@YAXPAX@Z"
}
// PR13022
void (redundant_parens)();
void redundant_parens_use() { redundant_parens(); }
// CHECK: @"\01?redundant_parens@@YAXXZ"
// X64: @"\01?redundant_parens@@YAXXZ"
// PR13047
typedef double RGB[3];
RGB color1;
extern const RGB color2 = {};
extern RGB const color3[5] = {};
extern RGB const ((color4)[5]) = {};
struct B;
volatile int B::* volatile memptr1;
volatile int B::* memptr2;
int B::* volatile memptr3;
typedef int (*fun)();
volatile fun B::* volatile funmemptr1;
volatile fun B::* funmemptr2;
fun B::* volatile funmemptr3;
void (B::* volatile memptrtofun1)();
const void (B::* memptrtofun2)();
volatile void (B::* memptrtofun3)();
int (B::* volatile memptrtofun4)();
volatile int (B::* memptrtofun5)();
const int (B::* memptrtofun6)();
fun (B::* volatile memptrtofun7)();
volatile fun (B::* memptrtofun8)();
const fun (B::* memptrtofun9)();
// PR12603
enum E {};
// CHECK: "\01?fooE@@YA?AW4E@@XZ"
// X64: "\01?fooE@@YA?AW4E@@XZ"
E fooE() { return E(); }
class X {};
// CHECK: "\01?fooX@@YA?AVX@@XZ"
// X64: "\01?fooX@@YA?AVX@@XZ"
X fooX() { return X(); }
namespace PR13182 {
extern char s0[];
// CHECK: @"\01?s0@PR13182@@3PADA"
extern char s1[42];
// CHECK: @"\01?s1@PR13182@@3PADA"
extern const char s2[];
// CHECK: @"\01?s2@PR13182@@3QBDB"
extern const char s3[42];
// CHECK: @"\01?s3@PR13182@@3QBDB"
extern volatile char s4[];
// CHECK: @"\01?s4@PR13182@@3RCDC"
extern const volatile char s5[];
// CHECK: @"\01?s5@PR13182@@3SDDD"
extern const char* const* s6;
// CHECK: @"\01?s6@PR13182@@3PBQBDB"
char foo() {
return s0[0] + s1[0] + s2[0] + s3[0] + s4[0] + s5[0] + s6[0][0];
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <vector>
#include "Runtime/Particle/IElement.hpp"
/* Documentation at: https://wiki.axiodl.com/w/Particle_Script#Int_Elements */
namespace urde {
class CIEKeyframeEmitter : public CIntElement {
u32 x4_percent;
u32 x8_unk1;
bool xc_loop;
bool xd_unk2;
u32 x10_loopEnd;
u32 x14_loopStart;
std::vector<int> x18_keys;
public:
explicit CIEKeyframeEmitter(CInputStream& in);
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEDeath : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEDeath(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEClamp : public CIntElement {
std::unique_ptr<CIntElement> x4_min;
std::unique_ptr<CIntElement> x8_max;
std::unique_ptr<CIntElement> xc_val;
public:
CIEClamp(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_min(std::move(a)), x8_max(std::move(b)), xc_val(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIETimeChain : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
std::unique_ptr<CIntElement> xc_swFrame;
public:
CIETimeChain(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_a(std::move(a)), x8_b(std::move(b)), xc_swFrame(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEAdd : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEAdd(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b) : x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEConstant : public CIntElement {
int x4_val;
public:
explicit CIEConstant(int val) : x4_val(val) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEImpulse : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
public:
explicit CIEImpulse(std::unique_ptr<CIntElement>&& a) : x4_a(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIELifetimePercent : public CIntElement {
std::unique_ptr<CIntElement> x4_percentVal;
public:
explicit CIELifetimePercent(std::unique_ptr<CIntElement>&& a) : x4_percentVal(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEInitialRandom : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEInitialRandom(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEPulse : public CIntElement {
std::unique_ptr<CIntElement> x4_aDuration;
std::unique_ptr<CIntElement> x8_bDuration;
std::unique_ptr<CIntElement> xc_aVal;
std::unique_ptr<CIntElement> x10_bVal;
public:
CIEPulse(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c,
std::unique_ptr<CIntElement>&& d)
: x4_aDuration(std::move(a)), x8_bDuration(std::move(b)), xc_aVal(std::move(c)), x10_bVal(std::move(d)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEMultiply : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEMultiply(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIESampleAndHold : public CIntElement {
std::unique_ptr<CIntElement> x4_sampleSource;
mutable int x8_nextSampleFrame = 0;
std::unique_ptr<CIntElement> xc_waitFramesMin;
std::unique_ptr<CIntElement> x10_waitFramesMax;
mutable int x14_holdVal;
public:
CIESampleAndHold(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_sampleSource(std::move(a)), xc_waitFramesMin(std::move(b)), x10_waitFramesMax(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIERandom : public CIntElement {
std::unique_ptr<CIntElement> x4_min;
std::unique_ptr<CIntElement> x8_max;
public:
CIERandom(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_min(std::move(a)), x8_max(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIETimeScale : public CIntElement {
std::unique_ptr<CRealElement> x4_a;
public:
explicit CIETimeScale(std::unique_ptr<CRealElement>&& a) : x4_a(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetCumulativeParticleCount : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetActiveParticleCount : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetEmitterTime : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEModulo : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEModulo(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIESubtract : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIESubtract(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIERealToInt final : public CIntElement {
std::unique_ptr<CRealElement> x4_a;
std::unique_ptr<CRealElement> x8_b;
public:
explicit CIERealToInt(std::unique_ptr<CRealElement>&& a, std::unique_ptr<CRealElement>&& b)
: x4_a{std::move(a)}, x8_b{std::move(b)} {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
} // namespace urde
<commit_msg>CIntElement: Initialize x14_holdVal in CIESampleAndHold<commit_after>#pragma once
#include <memory>
#include <vector>
#include "Runtime/Particle/IElement.hpp"
/* Documentation at: https://wiki.axiodl.com/w/Particle_Script#Int_Elements */
namespace urde {
class CIEKeyframeEmitter : public CIntElement {
u32 x4_percent;
u32 x8_unk1;
bool xc_loop;
bool xd_unk2;
u32 x10_loopEnd;
u32 x14_loopStart;
std::vector<int> x18_keys;
public:
explicit CIEKeyframeEmitter(CInputStream& in);
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEDeath : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEDeath(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEClamp : public CIntElement {
std::unique_ptr<CIntElement> x4_min;
std::unique_ptr<CIntElement> x8_max;
std::unique_ptr<CIntElement> xc_val;
public:
CIEClamp(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_min(std::move(a)), x8_max(std::move(b)), xc_val(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIETimeChain : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
std::unique_ptr<CIntElement> xc_swFrame;
public:
CIETimeChain(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_a(std::move(a)), x8_b(std::move(b)), xc_swFrame(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEAdd : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEAdd(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b) : x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEConstant : public CIntElement {
int x4_val;
public:
explicit CIEConstant(int val) : x4_val(val) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEImpulse : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
public:
explicit CIEImpulse(std::unique_ptr<CIntElement>&& a) : x4_a(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIELifetimePercent : public CIntElement {
std::unique_ptr<CIntElement> x4_percentVal;
public:
explicit CIELifetimePercent(std::unique_ptr<CIntElement>&& a) : x4_percentVal(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEInitialRandom : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEInitialRandom(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEPulse : public CIntElement {
std::unique_ptr<CIntElement> x4_aDuration;
std::unique_ptr<CIntElement> x8_bDuration;
std::unique_ptr<CIntElement> xc_aVal;
std::unique_ptr<CIntElement> x10_bVal;
public:
CIEPulse(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c,
std::unique_ptr<CIntElement>&& d)
: x4_aDuration(std::move(a)), x8_bDuration(std::move(b)), xc_aVal(std::move(c)), x10_bVal(std::move(d)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEMultiply : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEMultiply(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIESampleAndHold : public CIntElement {
std::unique_ptr<CIntElement> x4_sampleSource;
mutable int x8_nextSampleFrame = 0;
std::unique_ptr<CIntElement> xc_waitFramesMin;
std::unique_ptr<CIntElement> x10_waitFramesMax;
mutable int x14_holdVal = 0;
public:
CIESampleAndHold(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CIntElement>&& c)
: x4_sampleSource(std::move(a)), xc_waitFramesMin(std::move(b)), x10_waitFramesMax(std::move(c)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIERandom : public CIntElement {
std::unique_ptr<CIntElement> x4_min;
std::unique_ptr<CIntElement> x8_max;
public:
CIERandom(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_min(std::move(a)), x8_max(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIETimeScale : public CIntElement {
std::unique_ptr<CRealElement> x4_a;
public:
explicit CIETimeScale(std::unique_ptr<CRealElement>&& a) : x4_a(std::move(a)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetCumulativeParticleCount : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetActiveParticleCount : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEGetEmitterTime : public CIntElement {
public:
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIEModulo : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIEModulo(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIESubtract : public CIntElement {
std::unique_ptr<CIntElement> x4_a;
std::unique_ptr<CIntElement> x8_b;
public:
CIESubtract(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b)
: x4_a(std::move(a)), x8_b(std::move(b)) {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
class CIERealToInt final : public CIntElement {
std::unique_ptr<CRealElement> x4_a;
std::unique_ptr<CRealElement> x8_b;
public:
explicit CIERealToInt(std::unique_ptr<CRealElement>&& a, std::unique_ptr<CRealElement>&& b)
: x4_a{std::move(a)}, x8_b{std::move(b)} {}
bool GetValue(int frame, int& valOut) const override;
int GetMaxValue() const override;
};
} // namespace urde
<|endoftext|> |
<commit_before>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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 text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
/*
standard ODE geometry primitives: public API and pairwise collision functions.
the rule is that only the low level primitive collision functions should set
dContactGeom::g1 and dContactGeom::g2.
*/
#include <ode/common.h>
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_kernel.h"
#include "collision_std.h"
#include "collision_util.h"
#ifdef _MSC_VER
#pragma warning(disable:4291) // for VC++, no complaints about "no matching operator delete found"
#endif
//****************************************************************************
// plane public API
static void make_sure_plane_normal_has_unit_length (dxPlane *g)
{
dReal l = g->p[0]*g->p[0] + g->p[1]*g->p[1] + g->p[2]*g->p[2];
if (l > 0) {
l = dRecipSqrt(l);
g->p[0] *= l;
g->p[1] *= l;
g->p[2] *= l;
g->p[3] *= l;
}
else {
g->p[0] = 1;
g->p[1] = 0;
g->p[2] = 0;
g->p[3] = 0;
}
}
dxPlane::dxPlane (dSpaceID space, dReal a, dReal b, dReal c, dReal d) :
dxGeom (space,0)
{
type = dPlaneClass;
p[0] = a;
p[1] = b;
p[2] = c;
p[3] = d;
make_sure_plane_normal_has_unit_length (this);
}
void dxPlane::computeAABB()
{
// @@@ planes that have normal vectors aligned along an axis can use a
// @@@ less comprehensive (half space) bounding box.
aabb[0] = -dInfinity;
aabb[1] = dInfinity;
aabb[2] = -dInfinity;
aabb[3] = dInfinity;
aabb[4] = -dInfinity;
aabb[5] = dInfinity;
}
dGeomID dCreatePlane (dSpaceID space,
dReal a, dReal b, dReal c, dReal d)
{
return new dxPlane (space,a,b,c,d);
}
void dGeomPlaneSetParams (dGeomID g, dReal a, dReal b, dReal c, dReal d)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
p->p[0] = a;
p->p[1] = b;
p->p[2] = c;
p->p[3] = d;
make_sure_plane_normal_has_unit_length (p);
dGeomMoved (g);
}
void dGeomPlaneGetParams (dGeomID g, dVector4 result)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
result[0] = p->p[0];
result[1] = p->p[1];
result[2] = p->p[2];
result[3] = p->p[3];
}
dReal dGeomPlanePointDepth (dGeomID g, dReal x, dReal y, dReal z)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
return p->p[3] - p->p[0]*x - p->p[1]*y - p->p[2]*z;
}
<commit_msg>Added half-space optimisation by Andres James, an improvement for AABBs of planes aligned along a world axis.<commit_after>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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 text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
/*
standard ODE geometry primitives: public API and pairwise collision functions.
the rule is that only the low level primitive collision functions should set
dContactGeom::g1 and dContactGeom::g2.
*/
#include <ode/common.h>
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_kernel.h"
#include "collision_std.h"
#include "collision_util.h"
#ifdef _MSC_VER
#pragma warning(disable:4291) // for VC++, no complaints about "no matching operator delete found"
#endif
//****************************************************************************
// plane public API
static void make_sure_plane_normal_has_unit_length (dxPlane *g)
{
dReal l = g->p[0]*g->p[0] + g->p[1]*g->p[1] + g->p[2]*g->p[2];
if (l > 0) {
l = dRecipSqrt(l);
g->p[0] *= l;
g->p[1] *= l;
g->p[2] *= l;
g->p[3] *= l;
}
else {
g->p[0] = 1;
g->p[1] = 0;
g->p[2] = 0;
g->p[3] = 0;
}
}
dxPlane::dxPlane (dSpaceID space, dReal a, dReal b, dReal c, dReal d) :
dxGeom (space,0)
{
type = dPlaneClass;
p[0] = a;
p[1] = b;
p[2] = c;
p[3] = d;
make_sure_plane_normal_has_unit_length (this);
}
void dxPlane::computeAABB()
{
aabb[0] = -dInfinity;
aabb[1] = dInfinity;
aabb[2] = -dInfinity;
aabb[3] = dInfinity;
aabb[4] = -dInfinity;
aabb[5] = dInfinity;
// Planes that have normal vectors aligned along an axis can use a
// less comprehensive (half space) bounding box.
if ( p[1] == 0.0f && p[2] == 0.0f ) {
// normal aligned with x-axis
aabb[0] = (p[0] > 0) ? -dInfinity : -p[3];
aabb[1] = (p[0] > 0) ? p[3] : dInfinity;
} else
if ( p[0] == 0.0f && p[2] == 0.0f ) {
// normal aligned with y-axis
aabb[2] = (p[1] > 0) ? -dInfinity : -p[3];
aabb[3] = (p[1] > 0) ? p[3] : dInfinity;
} else
if ( p[0] == 0.0f && p[1] == 0.0f ) {
// normal aligned with z-axis
aabb[4] = (p[2] > 0) ? -dInfinity : -p[3];
aabb[5] = (p[2] > 0) ? p[3] : dInfinity;
}
}
dGeomID dCreatePlane (dSpaceID space,
dReal a, dReal b, dReal c, dReal d)
{
return new dxPlane (space,a,b,c,d);
}
void dGeomPlaneSetParams (dGeomID g, dReal a, dReal b, dReal c, dReal d)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
p->p[0] = a;
p->p[1] = b;
p->p[2] = c;
p->p[3] = d;
make_sure_plane_normal_has_unit_length (p);
dGeomMoved (g);
}
void dGeomPlaneGetParams (dGeomID g, dVector4 result)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
result[0] = p->p[0];
result[1] = p->p[1];
result[2] = p->p[2];
result[3] = p->p[3];
}
dReal dGeomPlanePointDepth (dGeomID g, dReal x, dReal y, dReal z)
{
dUASSERT (g && g->type == dPlaneClass,"argument not a plane");
dxPlane *p = (dxPlane*) g;
return p->p[3] - p->p[0]*x - p->p[1]*y - p->p[2]*z;
}
<|endoftext|> |
<commit_before>#ifndef _SDD_HOM_INTERSECTION_HH_
#define _SDD_HOM_INTERSECTION_HH_
#include <algorithm> // all_of, copy
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Intersection homomorphism.
template <typename C>
class intersection
{
public:
/// @brief The type of the homomorphism operands' set.
using operands_type = boost::container::flat_set<homomorphism<C>>;
private:
/// @brief The homomorphism operands' set.
const operands_type operands_;
public:
/// @brief Constructor.
intersection(operands_type&& operands)
: operands_(std::move(operands))
{}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::intersection_builder<C, SDD<C>> intersection_operands;
intersection_operands.reserve(operands_.size());
for (const auto& op : operands_)
{
intersection_operands.add(op(cxt, o, x));
}
try
{
return dd::intersection(cxt.sdd_context(), std::move(intersection_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [](const homomorphism<C>& h){return h.selector();});
}
const operands_type&
operands()
const noexcept
{
return operands_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two intersection.
/// @related intersection
template <typename C>
inline
bool
operator==(const intersection<C>& lhs, const intersection<C>& rhs)
noexcept
{
return lhs.operands() == rhs.operands();
}
/// @internal
/// @related intersection
template <typename C>
std::ostream&
operator<<(std::ostream& os, const intersection<C>& s)
{
os << "(";
std::copy( s.operands().begin(), std::prev(s.operands().end())
, std::ostream_iterator<homomorphism<C>>(os, " & "));
return os << *std::prev(s.operands().end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an intersection's operands.
template <typename C>
struct intersection_builder_helper
{
using result_type = void;
using operands_type = typename intersection<C>::operands_type;
using hom_list_type = std::deque<homomorphism<C>> ;
using locals_type = std::unordered_map<order_position_type, hom_list_type>;
operands_type& operands_;
locals_type& locals_;
intersection_builder_helper(operands_type& operands, locals_type& locals)
noexcept
: operands_(operands)
, locals_(locals)
{}
/// @brief Flatten nested intersections.
void
operator()(const intersection<C>& s, const homomorphism<C>&)
const
{
for (const auto& op : s.operands())
{
visit_self(*this, op);
}
}
/// @brief Regroup locals.
void
operator()(const local<C>& l, const homomorphism<C>&)
const
{
auto insertion = locals_.emplace(l.target(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h)
const
{
operands_.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Intersection homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Intersection(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Intersection construction.");
}
typename hom::intersection<C>::operands_type operands;
operands.reserve(size);
typename hom::intersection_builder_helper<C>::locals_type locals;
hom::intersection_builder_helper<C> ib {operands, locals};
for (; begin != end; ++begin)
{
visit_self(ib, *begin);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, Intersection<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
operands.shrink_to_fit();
return homomorphism<C>::create(mem::construct<hom::intersection<C>>(), std::move(operands));
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Intersection homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Intersection(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Intersection<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::intersection.
template <typename C>
struct hash<sdd::hom::intersection<C>>
{
std::size_t
operator()(const sdd::hom::intersection<C>& s)
const
{
return sdd::util::hash(s.operands().begin(), s.operands().end());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_INTERSECTION_HH_
<commit_msg>Add a const_iterator to an intersection's operands.<commit_after>#ifndef _SDD_HOM_INTERSECTION_HH_
#define _SDD_HOM_INTERSECTION_HH_
#include <algorithm> // all_of, copy
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Intersection homomorphism.
template <typename C>
class intersection
{
public:
/// @brief The type of the homomorphism operands' set.
using operands_type = boost::container::flat_set<homomorphism<C>>;
/// @brief The type of a const iterator on this intersection's operands.
using const_iterator = typename operands_type::const_iterator;
private:
/// @brief The homomorphism operands' set.
const operands_type operands_;
public:
/// @brief Constructor.
intersection(operands_type&& operands)
: operands_(std::move(operands))
{}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::intersection_builder<C, SDD<C>> intersection_operands;
intersection_operands.reserve(operands_.size());
for (const auto& op : operands_)
{
intersection_operands.add(op(cxt, o, x));
}
try
{
return dd::intersection(cxt.sdd_context(), std::move(intersection_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [](const homomorphism<C>& h){return h.selector();});
}
/// @brief Get an iterator to the first operand.
///
/// O(1).
const_iterator
begin()
const noexcept
{
return operands_.begin();
}
/// @brief Get an iterator to the end of operands.
///
/// O(1).
const_iterator
end()
const noexcept
{
return operands_.end();
}
const operands_type&
operands()
const noexcept
{
return operands_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two intersection.
/// @related intersection
template <typename C>
inline
bool
operator==(const intersection<C>& lhs, const intersection<C>& rhs)
noexcept
{
return lhs.operands() == rhs.operands();
}
/// @internal
/// @related intersection
template <typename C>
std::ostream&
operator<<(std::ostream& os, const intersection<C>& s)
{
os << "(";
std::copy( s.operands().begin(), std::prev(s.operands().end())
, std::ostream_iterator<homomorphism<C>>(os, " & "));
return os << *std::prev(s.operands().end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an intersection's operands.
template <typename C>
struct intersection_builder_helper
{
using result_type = void;
using operands_type = typename intersection<C>::operands_type;
using hom_list_type = std::deque<homomorphism<C>> ;
using locals_type = std::unordered_map<order_position_type, hom_list_type>;
operands_type& operands_;
locals_type& locals_;
intersection_builder_helper(operands_type& operands, locals_type& locals)
noexcept
: operands_(operands)
, locals_(locals)
{}
/// @brief Flatten nested intersections.
void
operator()(const intersection<C>& s, const homomorphism<C>&)
const
{
for (const auto& op : s.operands())
{
visit_self(*this, op);
}
}
/// @brief Regroup locals.
void
operator()(const local<C>& l, const homomorphism<C>&)
const
{
auto insertion = locals_.emplace(l.target(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h)
const
{
operands_.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Intersection homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Intersection(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Intersection construction.");
}
typename hom::intersection<C>::operands_type operands;
operands.reserve(size);
typename hom::intersection_builder_helper<C>::locals_type locals;
hom::intersection_builder_helper<C> ib {operands, locals};
for (; begin != end; ++begin)
{
visit_self(ib, *begin);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, Intersection<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
operands.shrink_to_fit();
return homomorphism<C>::create(mem::construct<hom::intersection<C>>(), std::move(operands));
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Intersection homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Intersection(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Intersection<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::intersection.
template <typename C>
struct hash<sdd::hom::intersection<C>>
{
std::size_t
operator()(const sdd::hom::intersection<C>& s)
const
{
return sdd::util::hash(s.operands().begin(), s.operands().end());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_INTERSECTION_HH_
<|endoftext|> |
<commit_before>
#include "wke/wke2.h"
#include "wke/wkeString.h"
#include "wke/wkeWebView.h"
#include "wke/wkeWebWindow.h"
#include "wke/wkeGlobalVar.h"
#include "content/browser/WebPage.h"
#include "content/web_impl_win/BlinkPlatformImpl.h"
#include "content/web_impl_win/WebThreadImpl.h"
#include "content/resources/HeaderFooterHtml.h"
#include "third_party/WebKit/Source/web/WebViewImpl.h"
#include "third_party/WebKit/Source/web/WebSettingsImpl.h"
#include "third_party/WebKit/public/web/WebPrintScalingOption.h"
#include "third_party/WebKit/public/web/WebPrintParams.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkDocument.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "skia/ext/refptr.h"
#include "wtf/text/WTFString.h"
#include "wtf/text/WTFStringUtil.h"
#include "base/values.h"
#include "base/json/json_writer.h"
#include "net/WebURLLoaderInternal.h"
#include "net/InitializeHandleInfo.h"
#include <v8.h>
#include <shlwapi.h>
namespace net {
void WSCI_setHook(void* j, void* hook);
void WSCI_sendtext(void* j, char* buf, size_t len);
void WSCI_sendblob(void* j, char* buf, size_t len);
}
namespace wke {
void printingTest(wkeWebView webview);
wkeMemBuf* printingTest2(wkeWebView webview);
const int kPointsPerInch = 72;
// Length of an inch in CSS's 1px unit.
// http://dev.w3.org/csswg/css3-values/#the-px-unit
const int kPixelsPerInch = 96;
const float kPrintingMinimumShrinkFactor = 1.25f;
void changeRequestUrl(wkeNetJob jobPtr, const char* url)
{
wke::checkThreadCallIsValid(__FUNCTION__);
net::WebURLLoaderInternal* job = (net::WebURLLoaderInternal*)jobPtr;
blink::KURL newUrl(blink::ParsedURLString, url);
job->m_response.setURL(newUrl);
job->firstRequest()->setURL(newUrl);
job->m_initializeHandleInfo->url = url;
ASSERT(!job->m_url);
}
bool setDebugConfig(wkeWebView webview, const char* debugString, const char* param)
{
if (0 == strcmp(debugString, "changeRequestUrl")) {
wkeNetJob job = (wkeNetJob)webview;
changeRequestUrl(job, param);
return true;
}
content::WebPage* webpage = nullptr;
blink::WebViewImpl* webViewImpl = nullptr;
blink::WebSettingsImpl* settings = nullptr;
if (webview)
webpage = webview->getWebPage();
if (webpage)
webViewImpl = webpage->webViewImpl();
if (webViewImpl)
settings = webViewImpl->settingsImpl();
String stringDebug(debugString);
Vector<String> result;
stringDebug.split(",", result);
if (result.size() == 0)
return true;
String item = result[0];
if ("setCookieJarPath" == item || "setCookieJarFullPath" == item) {
std::string pathStr(param);
if (pathStr.size() == 0)
return true;
if ("setCookieJarPath" == item) {
if (pathStr[pathStr.size() - 1] != '\\' && pathStr[pathStr.size() - 1] != '/')
pathStr += '\\';
pathStr += "cookies.dat";
}
std::vector<char> result;
WTF::Utf8ToMByte(pathStr.c_str(), pathStr.size(), &result, CP_ACP);
if (0 == result.size())
return true;
result.push_back('\0');
webview->setCookieJarFullPath(&result[0]);
return true;
} else if ("setLocalStorageFullPath" == item) {
std::string pathStr(param);
if (pathStr.size() == 0)
return true;
webview->setLocalStorageFullPath(pathStr.c_str());
return true;
} else if ("smootTextEnable" == item) {
wke::g_smootTextEnable = atoi(param) == 1;
}
else if ("wsCallback" == item) {
webview->webPage()->wkeHandler().wsCallback = (void*)(param);
return true;
}
else if ("wsCallbackParam" == item) {
webview->webPage()->wkeHandler().wsCallbackParam = (void*)(param);
return true;
}
return false;
}
bool getDebugConfig(wkeWebView webview, const char* debugString, void **ret)
{
if (strcmp("setwshook", debugString) == 0) {
*ret = (void*)net::WSCI_setHook;
return true;
}
else if (strcmp("sendtext", debugString) == 0) {
*ret = (void*)net::WSCI_sendtext;
return true;
}
else if (strcmp("sendblob", debugString) == 0) {
*ret = (void*)net::WSCI_sendblob;
return true;
}
content::WebPage* webpage = nullptr;
blink::WebViewImpl* webViewImpl = nullptr;
blink::WebSettingsImpl* settings = nullptr;
if (webview)
webpage = webview->getWebPage();
if (webpage)
webViewImpl = webpage->webViewImpl();
if (webViewImpl)
settings = webViewImpl->settingsImpl();
String stringDebug(debugString);
Vector<String> result;
stringDebug.split(",", result);
if (result.size() == 0)
return true;
String item = result[0];
return false;
}
void printingTest(wkeWebView webview)
{
content::WebPage* webpage = webview->getWebPage();
blink::WebFrame* frame = webpage->mainFrame();
blink::WebRect printContentArea(0, 0, 500, 600);
blink::WebRect printableArea(0, 0, 500, 600);
blink::WebSize paperSize(500, 600);
const int kPointsPerInch = 72;
int printerDPI = kPointsPerInch;
blink::WebPrintScalingOption printScalingOption = blink::WebPrintScalingOptionSourceSize;
blink::WebPrintParams webkitParams(printContentArea, printableArea, paperSize, printerDPI, printScalingOption);
blink::WebView* blinkWebView = frame->view();
blinkWebView->settings()->setShouldPrintBackgrounds(false);
int pageCount = frame->printBegin(webkitParams);
double cssScaleFactor = 1.0f;
float webkitPageShrinkFactor = frame->getPrintPageShrink(0);
float scaleFactor = cssScaleFactor * webkitPageShrinkFactor;
SkPictureRecorder recorder;
recorder.beginRecording(500 / scaleFactor, 600 / scaleFactor, NULL, 0);
SkCanvas* canvas = recorder.getRecordingCanvas();
frame->printPage(0, canvas);
frame->printEnd();
skia::RefPtr<SkPicture> content = skia::AdoptRef(recorder.endRecordingAsPicture());
SkDynamicMemoryWStream pdfStream;
skia::RefPtr<SkDocument> pdfDoc = skia::AdoptRef(SkDocument::CreatePDF(&pdfStream));
SkRect contentArea = SkRect::MakeIWH(500, 600);
SkCanvas* pdfCanvas = pdfDoc->beginPage(500, 600, nullptr);
pdfCanvas->scale(scaleFactor, scaleFactor);
pdfCanvas->drawPicture(content.get());
pdfCanvas->flush();
pdfDoc->endPage();
pdfDoc->close();
SkData* pdfData = (pdfStream.copyToData());
HANDLE hFile = CreateFileW(L"D:\\1.pdf", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (!hFile || INVALID_HANDLE_VALUE == hFile)
return;
DWORD numberOfBytesWritten = 0;
::WriteFile(hFile, pdfData->data(), pdfData->size(), &numberOfBytesWritten, NULL);
::CloseHandle(hFile);
pdfData->unref();
}
void readFile(const wchar_t* path, std::vector<char>* buffer)
{
HANDLE hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
return;
DWORD fileSizeHigh;
const DWORD bufferSize = ::GetFileSize(hFile, &fileSizeHigh);
DWORD numberOfBytesRead = 0;
buffer->resize(bufferSize);
BOOL b = ::ReadFile(hFile, &buffer->at(0), bufferSize, &numberOfBytesRead, nullptr);
::CloseHandle(hFile);
b = b;
}
static void executeScript(blink::WebFrame* frame, const char* scriptFormat, const base::Value& parameters)
{
std::string json;
base::JSONWriter::Write(parameters, &json);
const int strSize = 2 * (strlen(scriptFormat) + json.size());
char* script = (char*)malloc(strSize);
sprintf(script, scriptFormat, json.c_str());
blink::WebScriptSource source(blink::WebString::fromUTF8(script));
frame->executeScript(source);
free(script);
}
const char kPageLoadScriptFormat[] = "document.open(); document.write(%s); document.close();";
const char kSettingHeaderFooterDate[] = "date";
const char kPageSetupScriptFormat[] = "setup(%s);";
static int getWindowDPI(HWND hWnd)
{
HDC screenDC = ::GetDC(hWnd);
int dpiX = ::GetDeviceCaps(screenDC, LOGPIXELSX);//96100%120125%
::ReleaseDC(nullptr, screenDC);
return dpiX;
}
int convertUnit(int value, int oldUnit, int newUnit)
{
// With integer arithmetic, to divide a value with correct rounding, you need
// to add half of the divisor value to the dividend value. You need to do the
// reverse with negative number.
if (value >= 0) {
return ((value * newUnit) + (oldUnit / 2)) / oldUnit;
} else {
return ((value * newUnit) - (oldUnit / 2)) / oldUnit;
}
}
void printHeaderAndFooter(
bool isPrintPageHeadAndFooter,
blink::WebCanvas* canvas,
int windowDPI,
int pageNumber,
int totalPages,
const blink::WebFrame& sourceFrame,
float webkitScaleFactor,
blink::WebSize pageSizeInPt,
int topMargin,
int bottomMargin
)
{
blink::WebSize pageSizeInPx(convertUnit(pageSizeInPt.width, kPointsPerInch, windowDPI), convertUnit(pageSizeInPt.height, kPointsPerInch, windowDPI));
SkAutoCanvasRestore autoRestore(canvas, true);
canvas->scale(1 / webkitScaleFactor, 1 / webkitScaleFactor);
blink::WebView* webView = blink::WebView::create(NULL);
webView->settings()->setJavaScriptEnabled(true);
blink::WebLocalFrame* frame = blink::WebLocalFrame::create(blink::WebTreeScopeType::Document, NULL);
webView->setMainFrame(frame);
#if 0
std::vector<char> buffer;
readFile(L"E:\\mycode\\miniblink49\\trunk\\content\\resources\\HeaderFooterHtml.htm", &buffer);
base::StringValue html(std::string(buffer.data(), buffer.size()));
#else
base::StringValue html(std::string(content::kHeaderFooterHtml, sizeof(content::kHeaderFooterHtml)));
#endif
// Load page with script to avoid async operations.
executeScript(frame, kPageLoadScriptFormat, html);
SYSTEMTIME st = { 0 };
::GetLocalTime(&st);
char dataBuffer[0x100];
sprintf(dataBuffer, "%d-%d-%d", st.wYear, st.wMonth, st.wDay);
base::DictionaryValue* options = new base::DictionaryValue();
options->SetBoolean("isPrintPageHeadAndFooter", isPrintPageHeadAndFooter);
options->SetString("date", dataBuffer);
options->SetDouble("width", pageSizeInPt.width);
options->SetDouble("height", pageSizeInPt.height);
options->SetDouble("topMargin", topMargin);
options->SetDouble("bottomMargin", bottomMargin);
char* pageNumberStr = (char*)malloc(0x100);
sprintf(pageNumberStr, "%d/%d", pageNumber, totalPages);
options->SetString("pageNumber", pageNumberStr);
free(pageNumberStr);
blink::KURL kurl = sourceFrame.document().url();
options->SetString("url", kurl.getUTF8String().utf8().data());
std::string title = sourceFrame.document().title().utf8();
options->SetString("title", title.empty() ? "print document" : title);
executeScript(frame, kPageSetupScriptFormat, *options);
blink::WebPrintParams webkitParams(pageSizeInPt);
webkitParams.printerDPI = windowDPI;
frame->printBegin(webkitParams);
frame->printPage(0, canvas);
frame->printEnd();
webView->close();
frame->close();
delete options;
}
const wkePdfDatas* printToPdf(wkeWebView webView, blink::WebFrame* webFrame, const wkePrintSettings* params)
{
content::WebPage* webpage = webView->getWebPage();
if (!webpage)
return nullptr;
blink::WebFrame* frame = webFrame;
if (!frame)
frame = webpage->mainFrame();
if (!frame)
return nullptr;
int windowDPI = 72; // chromiumdesired_dpi=72Ӳ룬getWindowDPI(webView->windowHandle());
int dpi = params->dpi;
int srcWidth = convertUnit(params->width, dpi, kPointsPerInch); // תptDPI72Ҳ˵px
int srcHeight = convertUnit(params->height, dpi, kPointsPerInch);
int marginTop = convertUnit(params->marginTop, dpi, kPointsPerInch);
int marginBottom = convertUnit(params->marginBottom, dpi, kPointsPerInch);
int marginLeft = convertUnit(params->marginLeft, dpi, kPointsPerInch);
int marginRight = convertUnit(params->marginRight, dpi, kPointsPerInch);
// PrepareFrameAndViewForPrint, ComputeWebKitPrintParamsInDesiredDpi
blink::WebSize printContentSize(srcWidth - marginLeft - marginRight, srcHeight - marginTop - marginBottom);
blink::WebRect printContentArea(0, 0, (printContentSize.width) /*/ kPrintingMinimumShrinkFactor*/, (printContentSize.height) /*/ kPrintingMinimumShrinkFactor*/);
blink::WebSize paperSize(srcWidth, srcHeight);
blink::WebRect printableArea(0, 0, paperSize.width, paperSize.height);
SkRect clipRect = SkRect::MakeIWH(printContentSize.width, printContentSize.height);
float webkitScaleFactor = 1.0 / kPrintingMinimumShrinkFactor;
blink::WebPrintScalingOption printScalingOption = blink::WebPrintScalingOptionSourceSize;
blink::WebPrintParams webkitParams(printContentArea, printableArea, paperSize, dpi, printScalingOption);
blink::WebView* blinkWebView = frame->view();
blink::WebSize oldSize = webpage->viewportSize();
blink::WebSize printLayoutSize(printContentArea.width, printContentArea.height);
if (params->isLandscape)
printLayoutSize.width = ((int)((printLayoutSize.width) * kPrintingMinimumShrinkFactor));
else
printLayoutSize.height = ((int)((printLayoutSize.height) * kPrintingMinimumShrinkFactor));
printLayoutSize.width = printLayoutSize.width; // convertUnit(printLayoutSize.width, kPointsPerInch, windowDPI); // pt -> px
printLayoutSize.height = printLayoutSize.height; // convertUnit(printLayoutSize.height, kPointsPerInch, windowDPI);
webpage->setViewportSize(printLayoutSize); // paperSize
// double oldZoom = blinkWebView->zoomLevel();
// double zoomLevel = blink::WebView::zoomFactorToZoomLevel(0.5);
// blinkWebView->setZoomLevel(zoomLevel);
// float oldZoom = blinkWebView->pageScaleFactor();
// blinkWebView->setDefaultPageScaleLimits(0.5, 1.5);
// blinkWebView->setPageScaleFactor(0.5);
int pageCount = frame->printBegin(webkitParams);
if (0 == pageCount)
return nullptr;
blinkWebView->settings()->setShouldPrintBackgrounds(params->isPrintBackgroud);
wkePdfDatas* result = new wkePdfDatas();
result->count = pageCount;
result->sizes = (size_t*)malloc(pageCount * sizeof(size_t*));
result->datas = (const void**)malloc(pageCount * sizeof(void*));
for (int i = 0; i < pageCount; ++i) {
float webkitPageShrinkFactor = frame->getPrintPageShrink(i);
SkDynamicMemoryWStream pdfStream;
skia::RefPtr<SkDocument> document = skia::AdoptRef(SkDocument::CreatePDF(&pdfStream, kPointsPerInch));
SkCanvas* canvas = document->beginPage(srcWidth / webkitPageShrinkFactor, srcHeight / webkitPageShrinkFactor);
canvas->scale(webkitPageShrinkFactor, webkitPageShrinkFactor);
printHeaderAndFooter(params->isPrintPageHeadAndFooter, canvas, windowDPI, i + 1, pageCount, *frame, webkitPageShrinkFactor, paperSize, marginTop, marginBottom);
SkRect clipRectTemp = SkRect::MakeIWH(clipRect.width() / webkitPageShrinkFactor, clipRect.height() / webkitPageShrinkFactor);
canvas->save();
canvas->translate(marginLeft / webkitPageShrinkFactor, marginTop / webkitPageShrinkFactor);
canvas->clipRect(clipRectTemp);
frame->printPage(i, canvas);
canvas->restore();
canvas->flush();
document->endPage();
document->close();
SkData* pdfData = pdfStream.copyToData();
result->sizes[i] = pdfData->size();
result->datas[i] = malloc(pdfData->size());
memcpy((void*)(result->datas[i]), pdfData->data(), pdfData->size());
pdfData->unref();
}
frame->printEnd();
//blinkWebView->setZoomLevel(oldZoom);
//blinkWebView->setPageScaleFactor(oldZoom);
webpage->setViewportSize(oldSize);
return result;
}
const wkeMemBuf* printToBitmap(wkeWebView webView, const wkeScreenshotSettings* settings)
{
content::WebPage* webpage = webView->getWebPage();
if (!webpage)
return nullptr;
blink::WebFrame* webFrame = webpage->mainFrame();
if (!webFrame)
return nullptr;
blink::WebSize contentsSize = webFrame->contentsSize();
int width = contentsSize.width;
int height = contentsSize.height;
if (width <= 0 || height <= 0)
return nullptr;
SkBitmap bitmap;
bitmap.allocN32Pixels(width + 0.5, height + 0.5);
SkCanvas canvas(bitmap);
blink::WebString css;
webFrame->drawInCanvas(blink::WebRect(0, 0, width, height), css, &canvas);
canvas.flush();
size_t size = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bitmap.getSize();
BITMAPFILEHEADER fileHeader = {
0x4d42,
sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + size,
0, 0,
sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)
};
BITMAPINFOHEADER bmiHeader = {
sizeof(BITMAPINFOHEADER),
width,
-height,
1,
32,
BI_RGB,
};
std::vector<char> bmpData;
bmpData.resize(size);
char* destBuffer = reinterpret_cast<char*>(&bmpData.at(0));
size_t offset = 0;
memcpy(destBuffer, &fileHeader, sizeof(fileHeader));
offset += sizeof(fileHeader);
memcpy(destBuffer + offset, &bmiHeader, sizeof(bmiHeader));
offset += sizeof(bmiHeader);
bitmap.copyPixelsTo(destBuffer + offset, size);
wkeMemBuf* result = wkeCreateMemBuf(nullptr, destBuffer, size);
return result;
}
}
void wkeUtilRelasePrintPdfDatas(const wkePdfDatas* datas)
{
for (int i = 0; i < datas->count; ++i) {
free((void *)(datas->datas[i]));
}
free((void *)(datas->sizes));
free((void *)(datas->datas));
delete datas;
}
const wkePdfDatas* wkeUtilPrintToPdf(wkeWebView webView, wkeWebFrameHandle frameId, const wkePrintSettings* settings)
{
content::WebPage* webPage = webView->webPage();
blink::WebFrame* webFrame = webPage->getWebFrameFromFrameId(wke::CWebView::wkeWebFrameHandleToFrameId(webPage, frameId));
return wke::printToPdf(webView, webFrame, settings);
}
const wkeMemBuf* wkePrintToBitmap(wkeWebView webView, wkeWebFrameHandle frameId, const wkeScreenshotSettings* settings)
{
return wke::printToBitmap(webView, settings);
}<commit_msg>* 格式整理<commit_after>
#include "wke/wke2.h"
#include "wke/wkeString.h"
#include "wke/wkeWebView.h"
#include "wke/wkeWebWindow.h"
#include "wke/wkeGlobalVar.h"
#include "content/browser/WebPage.h"
#include "content/web_impl_win/BlinkPlatformImpl.h"
#include "content/web_impl_win/WebThreadImpl.h"
#include "content/resources/HeaderFooterHtml.h"
#include "third_party/WebKit/Source/web/WebViewImpl.h"
#include "third_party/WebKit/Source/web/WebSettingsImpl.h"
#include "third_party/WebKit/public/web/WebPrintScalingOption.h"
#include "third_party/WebKit/public/web/WebPrintParams.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkDocument.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "skia/ext/refptr.h"
#include "wtf/text/WTFString.h"
#include "wtf/text/WTFStringUtil.h"
#include "base/values.h"
#include "base/json/json_writer.h"
#include "net/WebURLLoaderInternal.h"
#include "net/InitializeHandleInfo.h"
#include <v8.h>
#include <shlwapi.h>
namespace net {
void WSCI_setHook(void* j, void* hook);
void WSCI_sendtext(void* j, char* buf, size_t len);
void WSCI_sendblob(void* j, char* buf, size_t len);
}
namespace wke {
bool setDebugConfig(wkeWebView webview, const char* debugString, const char* param)
{
return false;
}
bool getDebugConfig(wkeWebView webview, const char* debugString, void **ret)
{
return false;
}
const wkePdfDatas* printToPdf(wkeWebView webView, blink::WebFrame* webFrame, const wkePrintSettings* params)
{
return nullptr;
}
const wkeMemBuf* printToBitmap(wkeWebView webView, const wkeScreenshotSettings* settings)
{
return nullptr;
}
}
void wkeUtilRelasePrintPdfDatas(const wkePdfDatas* datas)
{
for (int i = 0; i < datas->count; ++i) {
free((void *)(datas->datas[i]));
}
free((void *)(datas->sizes));
free((void *)(datas->datas));
delete datas;
}
const wkePdfDatas* wkeUtilPrintToPdf(wkeWebView webView, wkeWebFrameHandle frameId, const wkePrintSettings* settings)
{
content::WebPage* webPage = webView->webPage();
blink::WebFrame* webFrame = webPage->getWebFrameFromFrameId(wke::CWebView::wkeWebFrameHandleToFrameId(webPage, frameId));
return wke::printToPdf(webView, webFrame, settings);
}
const wkeMemBuf* wkePrintToBitmap(wkeWebView webView, wkeWebFrameHandle frameId, const wkeScreenshotSettings* settings)
{
return wke::printToBitmap(webView, settings);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include "poll_manager.h"
#include "de_web_plugin_private.h"
/*! Constructor.
*/
PollManager::PollManager(QObject *parent) :
QObject(parent)
{
pollState = StateIdle;
timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired()));
plugin = qobject_cast<DeRestPluginPrivate*>(parent);
}
/*! Queues polling of the node.
\param restNode - the node to poll
*/
void PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart)
{
Resource *r = dynamic_cast<Resource*>(restNode);
DBG_Assert(r != 0);
if (!r)
{
return;
}
PollItem pitem;
if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle())
{
return;
}
if (r->prefix() == RLights)
{
LightNode *lightNode = static_cast<LightNode*>(restNode);
DBG_Assert(lightNode != 0);
pitem.endpoint = lightNode->haEndpoint().endpoint();
}
else if (r->prefix() == RSensors)
{
Sensor *sensor = static_cast<Sensor*>(restNode);
DBG_Assert(sensor != 0);
pitem.endpoint = sensor->fingerPrint().endpoint;
}
else
{
return;
}
pitem.id = restNode->id();
pitem.prefix = r->prefix();
pitem.address = restNode->address();
pitem.tStart = tStart;
for (int i = 0; i < r->itemCount(); i++)
{
const ResourceItem *item = r->itemForIndex(i);
const char *suffix = item ? item->descriptor().suffix : 0;
if (suffix == RStateOn ||
suffix == RStateBri ||
suffix == RStateColorMode ||
suffix == RStateConsumption ||
suffix == RStatePower ||
suffix == RAttrModelId)
{
pitem.items.push_back(suffix);
}
}
for (PollItem &i : items)
{
if (i.prefix == r->prefix() && i.id == restNode->id())
{
i.items = pitem.items; // update
if (tStart.isValid())
{
i.tStart = tStart;
}
return;
}
}
items.push_back(pitem);
if (!timer->isActive())
{
timer->start(1);
}
}
/*! Delays polling for \p ms milliseconds.
*/
void PollManager::delay(int ms)
{
timer->stop();
timer->start(ms);
}
/*! Handle APS confirm if related to polling.
*/
void PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)
{
if (pollState != StateWait)
{
return;
}
if (apsReqId != conf.id())
{
return;
}
if (dstAddr.hasExt() && conf.dstAddress().hasExt()
&& dstAddr.ext() != conf.dstAddress().ext())
{
}
else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk()
&& dstAddr.nwk() != conf.dstAddress().nwk())
{
}
DBG_Printf(DBG_INFO_L2, "Poll APS confirm %u status: 0x%02X\n", conf.id(), conf.status());
pollState = StateIdle;
timer->stop();
timer->start(1);
}
/*! Timer callback to proceed polling.
*/
void PollManager::pollTimerFired()
{
if (pollState == StateWait)
{
DBG_Printf(DBG_INFO, "timout on poll APS confirm\n");
pollState = StateIdle;
}
DBG_Assert(pollState == StateIdle);
if (items.empty())
{
return;
}
QDateTime now = QDateTime::currentDateTime();
PollItem &pitem = items.front();
Resource *r = plugin->getResource(pitem.prefix, pitem.id);
ResourceItem *item = 0;
RestNodeBase *restNode = 0;
const LightNode *lightNode = 0;
if (r && r->prefix() == RLights)
{
restNode = plugin->getLightNodeForId(pitem.id);
lightNode = static_cast<LightNode*>(restNode);
item = r->item(RStateReachable);
}
else if (r && r->prefix() == RSensors)
{
restNode = plugin->getSensorNodeForId(pitem.id);
item = r->item(RConfigReachable);
}
if (pitem.tStart.isValid() && pitem.tStart > now)
{
if (items.size() > 1)
{
PollItem tmp = pitem;
items.front() = items.back();
items.back() = tmp;
}
timer->start(1);
return;
}
if (!r || pitem.items.empty() ||
!restNode ||
//!restNode->lastRx().isValid() ||
!item || !item->toBool()) // not reachable
{
items.front() = items.back();
items.pop_back();
timer->start(1);
return;
}
quint16 clusterId = 0;
std::vector<quint16> attributes;
item = r->item(RStateOn);
bool isOn = item ? item->toBool() : false;
const char *&suffix = pitem.items[0];
for (size_t i = 0; pitem.items[0] == 0 && i < pitem.items.size(); i++)
{
if (pitem.items[i] != 0)
{
pitem.items[0] = pitem.items[i]; // move to front
pitem.items[i] = 0; // clear
break;
}
}
if (!suffix)
{
pitem.items.clear(); // all done
}
if (suffix == RStateOn)
{
clusterId = ONOFF_CLUSTER_ID;
attributes.push_back(0x0000); // onOff
}
else if (suffix == RStateBri && isOn)
{
NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000);
if (isOn || !val.timestamp.isValid())
{
clusterId = LEVEL_CLUSTER_ID;
attributes.push_back(0x0000); // current level
}
}
else if (suffix == RStateColorMode && lightNode)
{
clusterId = COLOR_CLUSTER_ID;
item = r->item(RConfigColorCapabilities);
if (!item)
{
attributes.push_back(0x0008); // color mode
attributes.push_back(0x4001); // enhanced color mode
attributes.push_back(0x400a); // color capabilities
attributes.push_back(0x400b); // color temperature min
attributes.push_back(0x400c); // color temperature max
}
else
{
quint16 cap = item->toNumber();
std::vector<quint16> toCheck;
if (cap & 0x0002) // enhanced hue supported
{
toCheck.push_back(0x4001); // enhanced color mode
toCheck.push_back(0x4000); // enhanced hue
toCheck.push_back(0x0001); // saturation
}
else if (cap & 0x0001)
{
toCheck.push_back(0x0000); // hue
toCheck.push_back(0x0001); // saturation
toCheck.push_back(0x0008); // color mode
}
else
{
toCheck.push_back(0x0008); // color mode
}
if (cap & 0x0004)
{
toCheck.push_back(0x4002); // Color loop active
}
if (cap & 0x0008)
{
toCheck.push_back(0x0003); // currentX
toCheck.push_back(0x0004); // currentY
}
if (cap & 0x0010)
{
toCheck.push_back(0x0007); // color temperature
}
for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters())
{
if (cl.id() != COLOR_CLUSTER_ID)
{
continue;
}
for (const deCONZ::ZclAttribute &attr : cl.attributes())
{
for (quint16 attrId : toCheck)
{
// discard attributes which are not be available
if (attrId == attr.id() && attr.isAvailable())
{
NodeValue &val = restNode->getZclValue(clusterId, attrId);
if (isOn || !val.timestamp.isValid())
{
attributes.push_back(attrId);
}
}
}
}
break;
}
}
}
else if (suffix == RStateConsumption)
{
clusterId = METERING_CLUSTER_ID;
attributes.push_back(0x0000); // Curent Summation Delivered
}
else if (suffix == RStatePower)
{
clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID;
attributes.push_back(0x050b); // Active Power
item = r->item(RAttrModelId);
if (! item->toString().startsWith(QLatin1String("Plug"))) // OSRAM plug
{
attributes.push_back(0x0505); // RMS Voltage
attributes.push_back(0x0508); // RMS Current
}
}
else if (suffix == RAttrModelId)
{
item = r->item(RAttrModelId);
if (item && (item->toString().isEmpty() || item->toString() == QLatin1String("unknown") ||
(item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith("FLS-A")) // dynamic model ids
))
{
clusterId = BASIC_CLUSTER_ID;
//attributes.push_back(0x0004); // manufacturer
attributes.push_back(0x0005); // model id
}
}
size_t fresh = 0;
for (quint16 attrId : attributes)
{
NodeValue &val = restNode->getZclValue(clusterId, attrId);
if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < 360)
{
fresh++;
}
}
if (clusterId && fresh > 0 && fresh == attributes.size())
{
DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\n", pitem.address.ext(), clusterId);
suffix = 0; // clear
timer->start(100);
}
else if (!attributes.empty() && clusterId &&
plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes))
{
pollState = StateWait;
// TODO this hack to get aps request id
DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes);
apsReqId = plugin->tasks.back().req.id();
dstAddr = pitem.address;
timer->start(20 * 1000); // wait for confirm
suffix = 0; // clear
DBG_Printf(DBG_INFO_L2, "Poll APS request %u to 0x%016llX cluster: 0x%04X\n", apsReqId, dstAddr.ext(), clusterId);
}
else if (suffix)
{
suffix = 0; // clear
timer->start(100);
}
else
{
if (clusterId)
{
DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped\n", pitem.address.ext(), clusterId);
}
timer->start(100);
items.front() = items.back();
items.pop_back();
}
}
<commit_msg>Fix SEGV when restNode->node() isn't available yet<commit_after>/*
* Copyright (c) 2017 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include "poll_manager.h"
#include "de_web_plugin_private.h"
/*! Constructor.
*/
PollManager::PollManager(QObject *parent) :
QObject(parent)
{
pollState = StateIdle;
timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired()));
plugin = qobject_cast<DeRestPluginPrivate*>(parent);
}
/*! Queues polling of the node.
\param restNode - the node to poll
*/
void PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart)
{
Resource *r = dynamic_cast<Resource*>(restNode);
DBG_Assert(r != 0);
if (!r || !restNode->node())
{
return;
}
PollItem pitem;
if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle())
{
return;
}
if (r->prefix() == RLights)
{
LightNode *lightNode = static_cast<LightNode*>(restNode);
DBG_Assert(lightNode != 0);
pitem.endpoint = lightNode->haEndpoint().endpoint();
}
else if (r->prefix() == RSensors)
{
Sensor *sensor = static_cast<Sensor*>(restNode);
DBG_Assert(sensor != 0);
pitem.endpoint = sensor->fingerPrint().endpoint;
}
else
{
return;
}
pitem.id = restNode->id();
pitem.prefix = r->prefix();
pitem.address = restNode->address();
pitem.tStart = tStart;
for (int i = 0; i < r->itemCount(); i++)
{
const ResourceItem *item = r->itemForIndex(i);
const char *suffix = item ? item->descriptor().suffix : 0;
if (suffix == RStateOn ||
suffix == RStateBri ||
suffix == RStateColorMode ||
suffix == RStateConsumption ||
suffix == RStatePower ||
suffix == RAttrModelId)
{
pitem.items.push_back(suffix);
}
}
for (PollItem &i : items)
{
if (i.prefix == r->prefix() && i.id == restNode->id())
{
i.items = pitem.items; // update
if (tStart.isValid())
{
i.tStart = tStart;
}
return;
}
}
items.push_back(pitem);
if (!timer->isActive())
{
timer->start(1);
}
}
/*! Delays polling for \p ms milliseconds.
*/
void PollManager::delay(int ms)
{
timer->stop();
timer->start(ms);
}
/*! Handle APS confirm if related to polling.
*/
void PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)
{
if (pollState != StateWait)
{
return;
}
if (apsReqId != conf.id())
{
return;
}
if (dstAddr.hasExt() && conf.dstAddress().hasExt()
&& dstAddr.ext() != conf.dstAddress().ext())
{
}
else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk()
&& dstAddr.nwk() != conf.dstAddress().nwk())
{
}
DBG_Printf(DBG_INFO_L2, "Poll APS confirm %u status: 0x%02X\n", conf.id(), conf.status());
pollState = StateIdle;
timer->stop();
timer->start(1);
}
/*! Timer callback to proceed polling.
*/
void PollManager::pollTimerFired()
{
if (pollState == StateWait)
{
DBG_Printf(DBG_INFO, "timout on poll APS confirm\n");
pollState = StateIdle;
}
DBG_Assert(pollState == StateIdle);
if (items.empty())
{
return;
}
QDateTime now = QDateTime::currentDateTime();
PollItem &pitem = items.front();
Resource *r = plugin->getResource(pitem.prefix, pitem.id);
ResourceItem *item = 0;
RestNodeBase *restNode = 0;
const LightNode *lightNode = 0;
if (r && r->prefix() == RLights)
{
restNode = plugin->getLightNodeForId(pitem.id);
lightNode = static_cast<LightNode*>(restNode);
item = r->item(RStateReachable);
}
else if (r && r->prefix() == RSensors)
{
restNode = plugin->getSensorNodeForId(pitem.id);
item = r->item(RConfigReachable);
}
if (pitem.tStart.isValid() && pitem.tStart > now)
{
if (items.size() > 1)
{
PollItem tmp = pitem;
items.front() = items.back();
items.back() = tmp;
}
timer->start(1);
return;
}
if (!r || pitem.items.empty() ||
!restNode ||
//!restNode->lastRx().isValid() ||
!item || !item->toBool()) // not reachable
{
items.front() = items.back();
items.pop_back();
timer->start(1);
return;
}
quint16 clusterId = 0;
std::vector<quint16> attributes;
item = r->item(RStateOn);
bool isOn = item ? item->toBool() : false;
const char *&suffix = pitem.items[0];
for (size_t i = 0; pitem.items[0] == 0 && i < pitem.items.size(); i++)
{
if (pitem.items[i] != 0)
{
pitem.items[0] = pitem.items[i]; // move to front
pitem.items[i] = 0; // clear
break;
}
}
if (!suffix)
{
pitem.items.clear(); // all done
}
if (suffix == RStateOn)
{
clusterId = ONOFF_CLUSTER_ID;
attributes.push_back(0x0000); // onOff
}
else if (suffix == RStateBri && isOn)
{
NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000);
if (isOn || !val.timestamp.isValid())
{
clusterId = LEVEL_CLUSTER_ID;
attributes.push_back(0x0000); // current level
}
}
else if (suffix == RStateColorMode && lightNode)
{
clusterId = COLOR_CLUSTER_ID;
item = r->item(RConfigColorCapabilities);
if (!item)
{
attributes.push_back(0x0008); // color mode
attributes.push_back(0x4001); // enhanced color mode
attributes.push_back(0x400a); // color capabilities
attributes.push_back(0x400b); // color temperature min
attributes.push_back(0x400c); // color temperature max
}
else
{
quint16 cap = item->toNumber();
std::vector<quint16> toCheck;
if (cap & 0x0002) // enhanced hue supported
{
toCheck.push_back(0x4001); // enhanced color mode
toCheck.push_back(0x4000); // enhanced hue
toCheck.push_back(0x0001); // saturation
}
else if (cap & 0x0001)
{
toCheck.push_back(0x0000); // hue
toCheck.push_back(0x0001); // saturation
toCheck.push_back(0x0008); // color mode
}
else
{
toCheck.push_back(0x0008); // color mode
}
if (cap & 0x0004)
{
toCheck.push_back(0x4002); // Color loop active
}
if (cap & 0x0008)
{
toCheck.push_back(0x0003); // currentX
toCheck.push_back(0x0004); // currentY
}
if (cap & 0x0010)
{
toCheck.push_back(0x0007); // color temperature
}
for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters())
{
if (cl.id() != COLOR_CLUSTER_ID)
{
continue;
}
for (const deCONZ::ZclAttribute &attr : cl.attributes())
{
for (quint16 attrId : toCheck)
{
// discard attributes which are not be available
if (attrId == attr.id() && attr.isAvailable())
{
NodeValue &val = restNode->getZclValue(clusterId, attrId);
if (isOn || !val.timestamp.isValid())
{
attributes.push_back(attrId);
}
}
}
}
break;
}
}
}
else if (suffix == RStateConsumption)
{
clusterId = METERING_CLUSTER_ID;
attributes.push_back(0x0000); // Curent Summation Delivered
}
else if (suffix == RStatePower)
{
clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID;
attributes.push_back(0x050b); // Active Power
item = r->item(RAttrModelId);
if (! item->toString().startsWith(QLatin1String("Plug"))) // OSRAM plug
{
attributes.push_back(0x0505); // RMS Voltage
attributes.push_back(0x0508); // RMS Current
}
}
else if (suffix == RAttrModelId)
{
item = r->item(RAttrModelId);
if (item && (item->toString().isEmpty() || item->toString() == QLatin1String("unknown") ||
(item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith("FLS-A")) // dynamic model ids
))
{
clusterId = BASIC_CLUSTER_ID;
//attributes.push_back(0x0004); // manufacturer
attributes.push_back(0x0005); // model id
}
}
size_t fresh = 0;
for (quint16 attrId : attributes)
{
NodeValue &val = restNode->getZclValue(clusterId, attrId);
if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < 360)
{
fresh++;
}
}
if (clusterId && fresh > 0 && fresh == attributes.size())
{
DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\n", pitem.address.ext(), clusterId);
suffix = 0; // clear
timer->start(100);
}
else if (!attributes.empty() && clusterId &&
plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes))
{
pollState = StateWait;
// TODO this hack to get aps request id
DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes);
apsReqId = plugin->tasks.back().req.id();
dstAddr = pitem.address;
timer->start(20 * 1000); // wait for confirm
suffix = 0; // clear
DBG_Printf(DBG_INFO_L2, "Poll APS request %u to 0x%016llX cluster: 0x%04X\n", apsReqId, dstAddr.ext(), clusterId);
}
else if (suffix)
{
suffix = 0; // clear
timer->start(100);
}
else
{
if (clusterId)
{
DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped\n", pitem.address.ext(), clusterId);
}
timer->start(100);
items.front() = items.back();
items.pop_back();
}
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "./mitkPhotoacousticMotionCorrectionFilter.h"
#include <mitkImageReadAccessor.h>
mitk::PhotoacousticMotionCorrectionFilter::
PhotoacousticMotionCorrectionFilter() {
// Set the defaults for the OpticalFlowFarneback algorithm
// The values are taken directly out of Thomas's
// US-CV-Based-Optical-Flow-Carotis.ipyn
m_batch = 5;
m_pyr_scale = 0.5;
m_levels = 1;
m_winsize = 40;
m_iterations = 2;
m_poly_n = 7;
m_poly_sigma = 1.5;
m_flags = 0;
SetNumberOfIndexedInputs(2);
SetNumberOfIndexedOutputs(2);
}
mitk::PhotoacousticMotionCorrectionFilter::
~PhotoacousticMotionCorrectionFilter() {}
// void mitk::PhotoacousticMotionCorrectionFilter::SetInput(Image::Pointer
// paImage,
// Image::Pointer
// usImage)
// {
// m_paImage = paImage;
// m_usImage = usImage;
// }
void mitk::PhotoacousticMotionCorrectionFilter::GenerateData() {
MITK_INFO << "Start motion compensation.";
m_paImage = this->GetInput(0);
m_usImage = this->GetInput(1);
// Check that we actually got some images
if (!m_paImage || !m_usImage) {
// TODO: Throw some error here
}
// Check that the image dimensions are the same
if (m_paImage->GetDimension() != m_usImage->GetDimension() &&
m_usImage->GetDimension() == 3) {
MITK_INFO << "Mismatching image dimensions detected in the motion "
"compensation filter.";
// TODO: Throw some error here
}
for (unsigned int i = 0; i < m_paImage->GetDimension(); i++) {
if (m_paImage->GetDimensions()[i] != m_usImage->GetDimensions()[i]) {
MITK_INFO << "Mismatching image dimensions detected in the motion "
"compensation filter.";
// TODO: Throw some error here
}
}
// Initialize output images
if (!m_paCompensated) {
m_paCompensated = mitk::Image::New();
}
if (!m_usCompensated) {
m_usCompensated = mitk::Image::New();
}
m_paCompensated->Initialize(m_paImage->GetPixelType(),
m_paImage->GetDimension(),
m_paImage->GetDimensions());
m_usCompensated->Initialize(m_usImage->GetPixelType(),
m_usImage->GetDimension(),
m_usImage->GetDimensions());
// TODO: remove debug messages
// Initialize the slices
mitk::Image::Pointer pa_slice = mitk::Image::New();
mitk::Image::Pointer us_slice = mitk::Image::New();
pa_slice->Initialize(m_paImage->GetPixelType(), 2,
m_paImage->GetDimensions());
us_slice->Initialize(m_usImage->GetPixelType(), 2,
m_usImage->GetDimensions());
MITK_INFO << "Start iteration.";
// Iterate over all the slices
for (unsigned int i = 0; i < m_paImage->GetDimensions()[2]; i++) {
// Get a read accessor for each slice
mitk::ImageReadAccessor pa_accessor(m_paImage, m_paImage->GetSliceData(i));
mitk::ImageReadAccessor us_accessor(m_paImage, m_usImage->GetSliceData(i));
// Write the correct image data into the slice
pa_slice->SetImportVolume(pa_accessor.GetData());
us_slice->SetImportVolume(us_accessor.GetData());
// Convert them first to an itk::Image and then to a cv::Mat
mitk::CastToItkImage(pa_slice, m_itkPaImage);
mitk::CastToItkImage(us_slice, m_itkUsImage);
MITK_INFO << "Generate Matrix.";
m_PaMatC = itk::OpenCVImageBridge::ITKImageToCVMat<itk::Image<float, 2>>(
m_itkPaImage);
m_UsMatC = itk::OpenCVImageBridge::ITKImageToCVMat<itk::Image<float, 2>>(
m_itkUsImage);
m_PaMat = m_PaMatC.getUMat( cv::ACCESS_READ );
m_UsMat = m_UsMatC.getUMat( cv::ACCESS_READ );
MITK_INFO << "Matrix generated.";
// At the beginning of a batch we set new references and the compensation
// can be skipped.
// TODO: handle m_batch == 0
// if (i % m_batch == 0) {
// m_UsRef = m_UsMat;
// m_UsRes = m_UsMatC;
// m_PaRes = m_PaMatC;
// continue;
// } else {
// // Calculate the flow using the Farneback algorithm
// // TODO: flags hard coded to 0, rethink.
// cv::calcOpticalFlowFarneback(m_UsRef, m_UsMat, m_Flow, m_pyr_scale, m_levels,
// m_winsize, m_iterations, m_poly_n,
// m_poly_sigma, 0);
// // Apply flow to the matrices
// cv::remap(m_PaMatC, m_PaRes, m_Flow, cv::noArray(), cv::INTER_LINEAR);
// cv::remap(m_UsMatC, m_UsRes, m_Flow, cv::noArray(), cv::INTER_LINEAR);
// }
// TODO: Actually do something, not just retransform
m_PaRes = m_PaMatC;
m_UsRes = m_UsMatC;
m_OpenCVToImageFilter->SetOpenCVMat(m_PaRes);
m_OpenCVToImageFilter->Update();
pa_slice = m_OpenCVToImageFilter->GetOutput();
mitk::ImageReadAccessor pa_slice_accessor(pa_slice);
m_paCompensated->SetSlice(pa_slice_accessor.GetData(), i);
m_OpenCVToImageFilter->SetOpenCVMat(m_UsRes);
m_OpenCVToImageFilter->Update();
us_slice = m_OpenCVToImageFilter->GetOutput();
mitk::ImageReadAccessor us_slice_accessor(us_slice);
m_paCompensated->SetSlice(us_slice_accessor.GetData(), i);
}
this->SetNthOutput(1, m_usCompensated);
this->SetNthOutput(0, m_paCompensated);
MITK_INFO << "We succeeded in running through the whole thing!";
}
<commit_msg>cv::Mat were deep copied<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "./mitkPhotoacousticMotionCorrectionFilter.h"
#include <mitkImageReadAccessor.h>
mitk::PhotoacousticMotionCorrectionFilter::
PhotoacousticMotionCorrectionFilter() {
// Set the defaults for the OpticalFlowFarneback algorithm
// The values are taken directly out of Thomas's
// US-CV-Based-Optical-Flow-Carotis.ipyn
m_batch = 5;
m_pyr_scale = 0.5;
m_levels = 1;
m_winsize = 40;
m_iterations = 2;
m_poly_n = 7;
m_poly_sigma = 1.5;
m_flags = 0;
this->SetNumberOfIndexedInputs(2);
this->SetNumberOfIndexedOutputs(2);
mitk::Image::Pointer newOutput = mitk::Image::New();
this->SetNthOutput(0, newOutput);
this->SetNthOutput(1, newOutput);
}
mitk::PhotoacousticMotionCorrectionFilter::
~PhotoacousticMotionCorrectionFilter() {}
// void mitk::PhotoacousticMotionCorrectionFilter::SetInput(Image::Pointer
// paImage,
// Image::Pointer
// usImage)
// {
// m_paImage = paImage;
// m_usImage = usImage;
// }
void mitk::PhotoacousticMotionCorrectionFilter::GenerateData() {
MITK_INFO << "Start motion compensation.";
m_paImage = this->GetInput(0);
m_usImage = this->GetInput(1);
// Check that we actually got some images
if (!m_paImage || !m_usImage) {
// TODO: Throw some error here
}
// Check that the image dimensions are the same
if (m_paImage->GetDimension() != m_usImage->GetDimension() &&
m_usImage->GetDimension() == 3) {
MITK_INFO << "Mismatching image dimensions detected in the motion "
"compensation filter.";
// TODO: Throw some error here
}
for (unsigned int i = 0; i < m_paImage->GetDimension(); i++) {
if (m_paImage->GetDimensions()[i] != m_usImage->GetDimensions()[i]) {
MITK_INFO << "Mismatching image dimensions detected in the motion "
"compensation filter.";
// TODO: Throw some error here
}
}
// Initialize output images
if (!m_paCompensated) {
m_paCompensated = mitk::Image::New();
}
if (!m_usCompensated) {
m_usCompensated = mitk::Image::New();
}
m_paCompensated->Initialize(m_paImage->GetPixelType(),
m_paImage->GetDimension(),
m_paImage->GetDimensions());
m_usCompensated->Initialize(m_usImage->GetPixelType(),
m_usImage->GetDimension(),
m_usImage->GetDimensions());
// TODO: remove debug messages
// Initialize the slices
mitk::Image::Pointer pa_slice = mitk::Image::New();
mitk::Image::Pointer us_slice = mitk::Image::New();
pa_slice->Initialize(m_paImage->GetPixelType(), 2,
m_paImage->GetDimensions());
us_slice->Initialize(m_usImage->GetPixelType(), 2,
m_usImage->GetDimensions());
MITK_INFO << "Start iteration.";
// Iterate over all the slices
for (unsigned int i = 0; i < m_paImage->GetDimensions()[2]; i++) {
// Get a read accessor for each slice
mitk::ImageReadAccessor pa_accessor(m_paImage, m_paImage->GetSliceData(i));
mitk::ImageReadAccessor us_accessor(m_paImage, m_usImage->GetSliceData(i));
// Write the correct image data into the slice
pa_slice->SetImportVolume(pa_accessor.GetData());
us_slice->SetImportVolume(us_accessor.GetData());
// Convert them first to an itk::Image and then to a cv::Mat
mitk::CastToItkImage(pa_slice, m_itkPaImage);
mitk::CastToItkImage(us_slice, m_itkUsImage);
MITK_INFO << "Generate Matrix.";
m_PaMatC = itk::OpenCVImageBridge::ITKImageToCVMat<itk::Image<float, 2>>(
m_itkPaImage);
m_UsMatC = itk::OpenCVImageBridge::ITKImageToCVMat<itk::Image<float, 2>>(
m_itkUsImage);
m_PaMat = m_PaMatC.getUMat( cv::ACCESS_READ ).clone();
m_UsMat = m_UsMatC.getUMat( cv::ACCESS_READ ).clone();
MITK_INFO << "Matrix generated.";
// At the beginning of a batch we set new references and the compensation
// can be skipped.
// TODO: handle m_batch == 0
if (i % m_batch == 0) {
MITK_INFO << "Start of batch.";
m_UsRef = m_UsMat.clone();
m_UsRes = m_UsMatC.clone();
m_PaRes = m_PaMatC.clone();
continue;
} else {
// Calculate the flow using the Farneback algorithm
// TODO: flags hard coded to 0, rethink.
MITK_INFO << "Apply algorithm.";
cv::calcOpticalFlowFarneback(m_UsRef, m_UsMat, m_Flow, m_pyr_scale, m_levels,
m_winsize, m_iterations, m_poly_n,
m_poly_sigma, 0);
// Apply flow to the matrices
cv::remap(m_PaMatC, m_PaRes, m_Flow, cv::noArray(), cv::INTER_LINEAR);
cv::remap(m_UsMatC, m_UsRes, m_Flow, cv::noArray(), cv::INTER_LINEAR);
}
// TODO: Actually do something, not just retransform
// m_PaRes = m_PaMatC;
// m_UsRes = m_UsMatC;
m_OpenCVToImageFilter->SetOpenCVMat(m_PaRes);
m_OpenCVToImageFilter->Update();
pa_slice = m_OpenCVToImageFilter->GetOutput();
mitk::ImageReadAccessor pa_slice_accessor(pa_slice);
m_paCompensated->SetSlice(pa_slice_accessor.GetData(), i);
m_OpenCVToImageFilter->SetOpenCVMat(m_UsRes);
m_OpenCVToImageFilter->Update();
us_slice = m_OpenCVToImageFilter->GetOutput();
mitk::ImageReadAccessor us_slice_accessor(us_slice);
m_paCompensated->SetSlice(us_slice_accessor.GetData(), i);
}
this->SetNthOutput(1, m_usCompensated);
this->SetNthOutput(0, m_paCompensated);
MITK_INFO << "We succeeded in running through the whole thing!";
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkRelabelComponentImageFilter_hxx
#define itkRelabelComponentImageFilter_hxx
#include "itkRelabelComponentImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkProgressReporter.h"
#include <map>
namespace itk
{
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method
Superclass::GenerateInputRequestedRegion();
// We need all the input.
InputImagePointer input = const_cast<InputImageType *>(this->GetInput());
if (input)
{
input->SetRequestedRegion(input->GetLargestPossibleRegion());
}
}
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateData()
{
SizeValueType i;
// Use a map to keep track of the size of each object. Object
// number -> ObjectType (which has Object number and the two sizes)
using MapType = std::map<LabelType, RelabelComponentObjectType>;
MapType sizeMap;
typename MapType::iterator mapIt;
using MapValueType = typename MapType::value_type;
// Get the input and the output
typename TInputImage::ConstPointer input = this->GetInput();
typename TOutputImage::Pointer output = this->GetOutput();
// Setup a progress reporter. We have 2 stages to the algorithm so
// use the total number of pixels accessed. We walk the entire input
// in the first pass, then walk just the output requested region in
// the second pass.
ProgressReporter progress(
this, 0, input->GetRequestedRegion().GetNumberOfPixels() + output->GetRequestedRegion().GetNumberOfPixels());
// Calculate the size of pixel
float physicalPixelSize = 1.0;
for (i = 0; i < TInputImage::ImageDimension; ++i)
{
physicalPixelSize *= input->GetSpacing()[i];
}
RelabelComponentObjectType initialSize;
initialSize.m_SizeInPixels = 1;
initialSize.m_SizeInPhysicalUnits = physicalPixelSize;
// First pass: walk the entire input image and determine what
// labels are used and the number of pixels used in each label.
//
// walk the input
ImageRegionConstIterator<InputImageType> it(input, input->GetRequestedRegion());
it.GoToBegin();
while (!it.IsAtEnd())
{
// Get the input pixel value
const auto inputValue = static_cast<LabelType>(it.Get());
// if the input pixel is not the background
if (inputValue != NumericTraits<LabelType>::ZeroValue())
{
// Does this label already exist
mapIt = sizeMap.find(inputValue);
if (mapIt == sizeMap.end())
{
// label is not currently in the map
initialSize.m_ObjectNumber = inputValue;
sizeMap.insert(MapValueType(inputValue, initialSize));
}
else
{
// label is already in the map, update the values
(*mapIt).second.m_SizeInPixels++;
(*mapIt).second.m_SizeInPhysicalUnits += physicalPixelSize;
}
}
// increment the iterators
++it;
progress.CompletedPixel();
}
// Now we need to reorder the labels. Use the m_ObjectSortingOrder
// to determine how to sort the objects. Define a map for converting
// input labels to output labels.
//
using VectorType = std::vector<RelabelComponentObjectType>;
VectorType sizeVector;
typename VectorType::iterator vit;
using RelabelMapType = std::map<LabelType, LabelType>;
using RelabelMapValueType = typename RelabelMapType::value_type;
RelabelMapType relabelMap;
// copy the original object map to a vector so we can sort it
for (mapIt = sizeMap.begin(); mapIt != sizeMap.end(); ++mapIt)
{
sizeVector.push_back((*mapIt).second);
}
// Sort the objects by size by default, unless m_SortByObjectSize
// is set to false.
if (m_SortByObjectSize)
{
std::sort(sizeVector.begin(), sizeVector.end(), RelabelComponentSizeInPixelsComparator());
}
// create a lookup table to map the input label to the output label.
// cache the object sizes for later access by the user
m_NumberOfObjects = static_cast<LabelType>(sizeVector.size());
m_OriginalNumberOfObjects = static_cast<LabelType>(sizeVector.size());
m_SizeOfObjectsInPixels.clear();
m_SizeOfObjectsInPixels.resize(m_NumberOfObjects);
m_SizeOfObjectsInPhysicalUnits.clear();
m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects);
int NumberOfObjectsRemoved = 0;
for (i = 0, vit = sizeVector.begin(); vit != sizeVector.end(); ++vit, ++i)
{
// if we find an object smaller than the minimum size, we
// terminate the loop.
if (m_MinimumObjectSize > 0 && (*vit).m_SizeInPixels < m_MinimumObjectSize)
{
// map small objects to the background
NumberOfObjectsRemoved++;
relabelMap.insert(RelabelMapValueType((*vit).m_ObjectNumber, 0));
}
else
{
// map for input labels to output labels (Note we use i+1 in the
// map since index 0 is the background)
relabelMap.insert(RelabelMapValueType((*vit).m_ObjectNumber, i + 1));
// cache object sizes for later access by the user
m_SizeOfObjectsInPixels[i] = (*vit).m_SizeInPixels;
m_SizeOfObjectsInPhysicalUnits[i] = (*vit).m_SizeInPhysicalUnits;
}
}
// update number of objects and resize cache vectors if we have removed small
// objects
m_NumberOfObjects -= NumberOfObjectsRemoved;
if (NumberOfObjectsRemoved > 0)
{
m_SizeOfObjectsInPixels.resize(m_NumberOfObjects);
m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects);
}
// Second pass: walk just the output requested region and relabel
// the necessary pixels.
//
// Allocate the output
this->AllocateOutputs();
// Remap the labels. Note we only walk the region of the output
// that was requested. This may be a subset of the input image.
OutputPixelType outputValue;
ImageRegionIterator<OutputImageType> oit;
oit = ImageRegionIterator<OutputImageType>(output, output->GetRequestedRegion());
it = ImageRegionConstIterator<InputImageType>(input, output->GetRequestedRegion());
it.GoToBegin();
oit.GoToBegin();
while (!oit.IsAtEnd())
{
const auto inputValue = static_cast<LabelType>(it.Get());
if (inputValue != NumericTraits<LabelType>::ZeroValue())
{
// lookup the mapped label
outputValue = static_cast<OutputPixelType>(relabelMap[inputValue]);
oit.Set(outputValue);
}
else
{
oit.Set(inputValue);
}
// increment the iterators
++it;
++oit;
progress.CompletedPixel();
}
}
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl;
os << indent << "OriginalNumberOfObjects: " << m_OriginalNumberOfObjects << std::endl;
os << indent << "NumberOfObjectsToPrint: " << m_NumberOfObjectsToPrint << std::endl;
os << indent << "MinimumObjectSizez: " << m_MinimumObjectSize << std::endl;
os << indent << "SortByObjectSize: " << m_SortByObjectSize << std::endl;
typename ObjectSizeInPixelsContainerType::const_iterator it;
ObjectSizeInPhysicalUnitsContainerType::const_iterator fit;
LabelType i;
// limit the number of objects to print
LabelType numPrint = m_NumberOfObjectsToPrint;
if (numPrint > m_SizeOfObjectsInPixels.size())
{
numPrint = static_cast<LabelType>(m_SizeOfObjectsInPixels.size());
}
for (i = 0, it = m_SizeOfObjectsInPixels.begin(), fit = m_SizeOfObjectsInPhysicalUnits.begin(); i < numPrint;
++it, ++fit, ++i)
{
os << indent << "Object #" << i + 1 << ": " << *it << " pixels, " << *fit << " physical units" << std::endl;
}
if (numPrint < m_SizeOfObjectsInPixels.size())
{
os << indent << "..." << std::endl;
}
}
} // end namespace itk
#endif
<commit_msg>BUG: Fix RelabelComponentImageFilter with sorting off, size on<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkRelabelComponentImageFilter_hxx
#define itkRelabelComponentImageFilter_hxx
#include "itkRelabelComponentImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkProgressReporter.h"
#include <map>
namespace itk
{
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method
Superclass::GenerateInputRequestedRegion();
// We need all the input.
InputImagePointer input = const_cast<InputImageType *>(this->GetInput());
if (input)
{
input->SetRequestedRegion(input->GetLargestPossibleRegion());
}
}
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateData()
{
SizeValueType i;
// Use a map to keep track of the size of each object. Object
// number -> ObjectType (which has Object number and the two sizes)
using MapType = std::map<LabelType, RelabelComponentObjectType>;
MapType sizeMap;
typename MapType::iterator mapIt;
using MapValueType = typename MapType::value_type;
// Get the input and the output
typename TInputImage::ConstPointer input = this->GetInput();
typename TOutputImage::Pointer output = this->GetOutput();
// Setup a progress reporter. We have 2 stages to the algorithm so
// use the total number of pixels accessed. We walk the entire input
// in the first pass, then walk just the output requested region in
// the second pass.
ProgressReporter progress(
this, 0, input->GetRequestedRegion().GetNumberOfPixels() + output->GetRequestedRegion().GetNumberOfPixels());
// Calculate the size of pixel
float physicalPixelSize = 1.0;
for (i = 0; i < TInputImage::ImageDimension; ++i)
{
physicalPixelSize *= input->GetSpacing()[i];
}
RelabelComponentObjectType initialSize;
initialSize.m_SizeInPixels = 1;
initialSize.m_SizeInPhysicalUnits = physicalPixelSize;
// First pass: walk the entire input image and determine what
// labels are used and the number of pixels used in each label.
//
// walk the input
ImageRegionConstIterator<InputImageType> it(input, input->GetRequestedRegion());
it.GoToBegin();
while (!it.IsAtEnd())
{
// Get the input pixel value
const auto inputValue = static_cast<LabelType>(it.Get());
// if the input pixel is not the background
if (inputValue != NumericTraits<LabelType>::ZeroValue())
{
// Does this label already exist
mapIt = sizeMap.find(inputValue);
if (mapIt == sizeMap.end())
{
// label is not currently in the map
initialSize.m_ObjectNumber = inputValue;
sizeMap.insert(MapValueType(inputValue, initialSize));
}
else
{
// label is already in the map, update the values
(*mapIt).second.m_SizeInPixels++;
(*mapIt).second.m_SizeInPhysicalUnits += physicalPixelSize;
}
}
// increment the iterators
++it;
progress.CompletedPixel();
}
// Now we need to reorder the labels. Use the m_ObjectSortingOrder
// to determine how to sort the objects. Define a map for converting
// input labels to output labels.
//
using VectorType = std::vector<RelabelComponentObjectType>;
VectorType sizeVector;
typename VectorType::iterator vit;
using RelabelMapType = std::map<LabelType, LabelType>;
using RelabelMapValueType = typename RelabelMapType::value_type;
RelabelMapType relabelMap;
// copy the original object map to a vector so we can sort it
for (mapIt = sizeMap.begin(); mapIt != sizeMap.end(); ++mapIt)
{
sizeVector.push_back((*mapIt).second);
}
// Sort the objects by size by default, unless m_SortByObjectSize
// is set to false.
if (m_SortByObjectSize)
{
std::sort(sizeVector.begin(), sizeVector.end(), RelabelComponentSizeInPixelsComparator());
}
// create a lookup table to map the input label to the output label.
// cache the object sizes for later access by the user
m_NumberOfObjects = static_cast<LabelType>(sizeVector.size());
m_OriginalNumberOfObjects = static_cast<LabelType>(sizeVector.size());
m_SizeOfObjectsInPixels.clear();
m_SizeOfObjectsInPixels.resize(m_NumberOfObjects);
m_SizeOfObjectsInPhysicalUnits.clear();
m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects);
int NumberOfObjectsRemoved = 0;
for (i = 0, vit = sizeVector.begin(); vit != sizeVector.end(); ++vit)
{
// if we find an object smaller than the minimum size, we
// terminate the loop.
if (m_MinimumObjectSize > 0 && (*vit).m_SizeInPixels < m_MinimumObjectSize)
{
// map small objects to the background
++NumberOfObjectsRemoved;
relabelMap.insert(RelabelMapValueType((*vit).m_ObjectNumber, 0));
}
else
{
// map for input labels to output labels (Note we use i+1 in the
// map since index 0 is the background)
relabelMap.insert(RelabelMapValueType((*vit).m_ObjectNumber, i + 1));
// cache object sizes for later access by the user
m_SizeOfObjectsInPixels[i] = (*vit).m_SizeInPixels;
m_SizeOfObjectsInPhysicalUnits[i] = (*vit).m_SizeInPhysicalUnits;
++i;
}
}
// update number of objects and resize cache vectors if we have removed small
// objects
m_NumberOfObjects -= NumberOfObjectsRemoved;
if (NumberOfObjectsRemoved > 0)
{
m_SizeOfObjectsInPixels.resize(m_NumberOfObjects);
m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects);
}
// Second pass: walk just the output requested region and relabel
// the necessary pixels.
//
// Allocate the output
this->AllocateOutputs();
// Remap the labels. Note we only walk the region of the output
// that was requested. This may be a subset of the input image.
OutputPixelType outputValue;
ImageRegionIterator<OutputImageType> oit;
oit = ImageRegionIterator<OutputImageType>(output, output->GetRequestedRegion());
it = ImageRegionConstIterator<InputImageType>(input, output->GetRequestedRegion());
it.GoToBegin();
oit.GoToBegin();
while (!oit.IsAtEnd())
{
const auto inputValue = static_cast<LabelType>(it.Get());
if (inputValue != NumericTraits<LabelType>::ZeroValue())
{
// lookup the mapped label
outputValue = static_cast<OutputPixelType>(relabelMap[inputValue]);
oit.Set(outputValue);
}
else
{
oit.Set(inputValue);
}
// increment the iterators
++it;
++oit;
progress.CompletedPixel();
}
}
template <typename TInputImage, typename TOutputImage>
void
RelabelComponentImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl;
os << indent << "OriginalNumberOfObjects: " << m_OriginalNumberOfObjects << std::endl;
os << indent << "NumberOfObjectsToPrint: " << m_NumberOfObjectsToPrint << std::endl;
os << indent << "MinimumObjectSizez: " << m_MinimumObjectSize << std::endl;
os << indent << "SortByObjectSize: " << m_SortByObjectSize << std::endl;
typename ObjectSizeInPixelsContainerType::const_iterator it;
ObjectSizeInPhysicalUnitsContainerType::const_iterator fit;
LabelType i;
// limit the number of objects to print
LabelType numPrint = m_NumberOfObjectsToPrint;
if (numPrint > m_SizeOfObjectsInPixels.size())
{
numPrint = static_cast<LabelType>(m_SizeOfObjectsInPixels.size());
}
for (i = 0, it = m_SizeOfObjectsInPixels.begin(), fit = m_SizeOfObjectsInPhysicalUnits.begin(); i < numPrint;
++it, ++fit, ++i)
{
os << indent << "Object #" << i + 1 << ": " << *it << " pixels, " << *fit << " physical units" << std::endl;
}
if (numPrint < m_SizeOfObjectsInPixels.size())
{
os << indent << "..." << std::endl;
}
}
} // end namespace itk
#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$ */
///////////////////////////////////////////////////////////////////////////////
// Class AliPHOSCalibHistoProducer accumulating histograms
// with amplitudes per PHOS channel
// It is intended to run at DAQ computers (LDC, GDC, HLT or MOOD)
// and it fills the histograms with amplitudes per channel.
// Usage example see in PHOS/macros/Shuttle/AliPHOSCalibHistoProducer.C
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////
#include "AliLog.h"
#include "AliPHOSCalibHistoProducer.h"
#include "TH1.h"
#include "TH2F.h"
#include "TFile.h"
#include "AliPHOSRawDecoder.h"
ClassImp(AliPHOSCalibHistoProducer)
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer() :
fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
fEvents(0),fNbins(100),fXlow(0.),fXup(1000.)
{
// Constructor: initializes data members
// Checks existence of histograms which might have been left
// from the previous runs to continues their filling
fHistoFile = new TFile("calibHisto.root","update");
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]=hist;
else
fAmpHisto[module][column][row] = 0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(Int_t nbinsx, Double_t xlow, Double_t xup) :
fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
fEvents(0),fNbins(nbinsx),fXlow(xlow),fXup(xup)
{
// Constructor: initializes data members.
// Checks existence of histograms which might have been left
// from the previous runs to continues their filling.
// In addition sets number of bins, low and upper limits common for all histograms.
fHistoFile = new TFile("calibHisto.root","update");
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]=hist;
else
fAmpHisto[module][column][row] = 0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::~AliPHOSCalibHistoProducer()
{
// Destructor
UpdateHistoFile();
if(fHistoFile) delete fHistoFile;
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(const AliPHOSCalibHistoProducer &histoproducer) :
TObject(histoproducer),fRawDecoder(histoproducer.fRawDecoder),fHistoFile(histoproducer.fHistoFile),
fUpdatingRate(histoproducer.fUpdatingRate),fIsOldRCUFormat(histoproducer.fIsOldRCUFormat),
fEvents(histoproducer.fEvents),fNbins(histoproducer.fNbins),fXlow(histoproducer.fXlow),fXup(histoproducer.fXup)
{
//Copy constructor.
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)histoproducer.fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]= new TH1F(*hist);
else
fAmpHisto[module][column][row]=0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer& AliPHOSCalibHistoProducer::operator=
(const AliPHOSCalibHistoProducer &histoproducer)
{
//Assignment operator.
if(this != &histoproducer) {
fRawDecoder = histoproducer.fRawDecoder;
fHistoFile = histoproducer.fHistoFile;
fUpdatingRate = histoproducer.fUpdatingRate;
fIsOldRCUFormat = histoproducer.fIsOldRCUFormat;
fEvents = histoproducer.fEvents;
fEvents = histoproducer.fEvents;
fNbins = histoproducer.fNbins;
fXlow = histoproducer.fXlow;
fXup = histoproducer.fXup;
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
if(fAmpHisto[module][column][row]){
delete fAmpHisto[module][column][row];
fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
}
else
fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
}
}
}
}
return *this;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::Run()
{
// Reads raw data of current event and fills amplitude histograms
// The histograms are written to file every fUpdatingRate events
if(!fRawDecoder) AliFatal("Raw decoder not set!");
Double_t energy;
Int_t mod,col,row;
if(fIsOldRCUFormat)
fRawDecoder->SetOldRCUFormat(kTRUE);
while(fRawDecoder->NextDigit()) {
if(fRawDecoder->IsLowGain()) continue;
energy = fRawDecoder->GetEnergy();
mod = fRawDecoder->GetModule()-1;
col = fRawDecoder->GetColumn()-1;
row = fRawDecoder->GetRow()-1;
if(fAmpHisto[mod][col][row]) {
fAmpHisto[mod][col][row]->Fill(energy);
}
else {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",mod,col,row);
fAmpHisto[mod][col][row] = new TH1F(hname,hname,fNbins,fXlow,fXup);
fAmpHisto[mod][col][row]->Fill(energy);
}
}
// update histograms in local file every 100th event
if(fEvents != 0 && fEvents%fUpdatingRate == 0) {
AliInfo(Form("Updating histo file, event %d, run %d\n",
fEvents,fRawDecoder->GetRawReader()->GetRunNumber()));
UpdateHistoFile();
}
// UpdateHistoFile();
// AliInfo(Form("%d events of run %d processed.",iEvent,runNum));
fEvents++;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::UpdateHistoFile()
{
// Write histograms to file
if(!fHistoFile) return;
if(!fHistoFile->IsOpen()) return;
TH1F* hist=0;
char hname[128];
char htitle[128];
for(Int_t module=0; module<5; module++) {
sprintf(hname,"hMeanE%d",module);
sprintf(htitle,"Mean energies in module %d",module);
TH2F hMeanE(hname,htitle,56,0.,56.,64,0.,64);
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
hist = fAmpHisto[module][column][row];
if(hist) hist->Write(hist->GetName(),TObject::kWriteDelete);
if(hist) hMeanE.SetBinContent(column,row,hist->GetMean());
}
}
hMeanE.Write(hMeanE.GetName(),TObject::kWriteDelete);
}
}
<commit_msg>#include added<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$ */
///////////////////////////////////////////////////////////////////////////////
// Class AliPHOSCalibHistoProducer accumulating histograms
// with amplitudes per PHOS channel
// It is intended to run at DAQ computers (LDC, GDC, HLT or MOOD)
// and it fills the histograms with amplitudes per channel.
// Usage example see in PHOS/macros/Shuttle/AliPHOSCalibHistoProducer.C
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////
#include "AliLog.h"
#include "AliPHOSCalibHistoProducer.h"
#include "TH1.h"
#include "TH2F.h"
#include "TFile.h"
#include "AliPHOSRawDecoder.h"
#include "AliRawReader.h"
ClassImp(AliPHOSCalibHistoProducer)
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer() :
fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
fEvents(0),fNbins(100),fXlow(0.),fXup(1000.)
{
// Constructor: initializes data members
// Checks existence of histograms which might have been left
// from the previous runs to continues their filling
fHistoFile = new TFile("calibHisto.root","update");
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]=hist;
else
fAmpHisto[module][column][row] = 0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(Int_t nbinsx, Double_t xlow, Double_t xup) :
fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
fEvents(0),fNbins(nbinsx),fXlow(xlow),fXup(xup)
{
// Constructor: initializes data members.
// Checks existence of histograms which might have been left
// from the previous runs to continues their filling.
// In addition sets number of bins, low and upper limits common for all histograms.
fHistoFile = new TFile("calibHisto.root","update");
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]=hist;
else
fAmpHisto[module][column][row] = 0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::~AliPHOSCalibHistoProducer()
{
// Destructor
UpdateHistoFile();
if(fHistoFile) delete fHistoFile;
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(const AliPHOSCalibHistoProducer &histoproducer) :
TObject(histoproducer),fRawDecoder(histoproducer.fRawDecoder),fHistoFile(histoproducer.fHistoFile),
fUpdatingRate(histoproducer.fUpdatingRate),fIsOldRCUFormat(histoproducer.fIsOldRCUFormat),
fEvents(histoproducer.fEvents),fNbins(histoproducer.fNbins),fXlow(histoproducer.fXlow),fXup(histoproducer.fXup)
{
//Copy constructor.
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",module,column,row);
TH1F* hist = (TH1F*)histoproducer.fHistoFile->Get(hname);
if(hist)
fAmpHisto[module][column][row]= new TH1F(*hist);
else
fAmpHisto[module][column][row]=0;
}
}
}
}
//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer& AliPHOSCalibHistoProducer::operator=
(const AliPHOSCalibHistoProducer &histoproducer)
{
//Assignment operator.
if(this != &histoproducer) {
fRawDecoder = histoproducer.fRawDecoder;
fHistoFile = histoproducer.fHistoFile;
fUpdatingRate = histoproducer.fUpdatingRate;
fIsOldRCUFormat = histoproducer.fIsOldRCUFormat;
fEvents = histoproducer.fEvents;
fEvents = histoproducer.fEvents;
fNbins = histoproducer.fNbins;
fXlow = histoproducer.fXlow;
fXup = histoproducer.fXup;
for(Int_t module=0; module<5; module++) {
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
if(fAmpHisto[module][column][row]){
delete fAmpHisto[module][column][row];
fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
}
else
fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
}
}
}
}
return *this;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::Run()
{
// Reads raw data of current event and fills amplitude histograms
// The histograms are written to file every fUpdatingRate events
if(!fRawDecoder) AliFatal("Raw decoder not set!");
Double_t energy;
Int_t mod,col,row;
if(fIsOldRCUFormat)
fRawDecoder->SetOldRCUFormat(kTRUE);
while(fRawDecoder->NextDigit()) {
if(fRawDecoder->IsLowGain()) continue;
energy = fRawDecoder->GetEnergy();
mod = fRawDecoder->GetModule()-1;
col = fRawDecoder->GetColumn()-1;
row = fRawDecoder->GetRow()-1;
if(fAmpHisto[mod][col][row]) {
fAmpHisto[mod][col][row]->Fill(energy);
}
else {
char hname[128];
sprintf(hname,"mod%dcol%drow%d",mod,col,row);
fAmpHisto[mod][col][row] = new TH1F(hname,hname,fNbins,fXlow,fXup);
fAmpHisto[mod][col][row]->Fill(energy);
}
}
// update histograms in local file every 100th event
if(fEvents != 0 && fEvents%fUpdatingRate == 0) {
AliInfo(Form("Updating histo file, event %d, run %d\n",
fEvents,fRawDecoder->GetRawReader()->GetRunNumber()));
UpdateHistoFile();
}
// UpdateHistoFile();
// AliInfo(Form("%d events of run %d processed.",iEvent,runNum));
fEvents++;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::UpdateHistoFile()
{
// Write histograms to file
if(!fHistoFile) return;
if(!fHistoFile->IsOpen()) return;
TH1F* hist=0;
char hname[128];
char htitle[128];
for(Int_t module=0; module<5; module++) {
sprintf(hname,"hMeanE%d",module);
sprintf(htitle,"Mean energies in module %d",module);
TH2F hMeanE(hname,htitle,56,0.,56.,64,0.,64);
for(Int_t column=0; column<56; column++) {
for(Int_t row=0; row<64; row++) {
hist = fAmpHisto[module][column][row];
if(hist) hist->Write(hist->GetName(),TObject::kWriteDelete);
if(hist) hMeanE.SetBinContent(column,row,hist->GetMean());
}
}
hMeanE.Write(hMeanE.GetName(),TObject::kWriteDelete);
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 Stanford University
*
* Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "CoordinatorClient.h"
#include "ProtoBuf.h"
namespace RAMCloud {
/**
* Create a new table.
*
* \param name
* Name for the new table (NULL-terminated string).
*
* \exception InternalError
*/
void
CoordinatorClient::createTable(const char* name)
{
Buffer req;
uint32_t length = strlen(name) + 1;
CreateTableRpc::Request& reqHdr(allocHeader<CreateTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
while (true) {
Buffer resp;
sendRecv<CreateTableRpc>(session, req, resp);
try {
checkStatus(HERE);
return;
} catch (const RetryException& e) {
LOG(DEBUG, "RETRY trying to create table");
yield();
}
}
}
/**
* Delete a table.
*
* All objects in the table are implicitly deleted, along with any
* other information associated with the table (such as, someday,
* indexes). If the table does not currently exist than the operation
* returns successfully without actually doing anything.
*
* \param name
* Name of the table to delete (NULL-terminated string).
*
* \exception InternalError
*/
void
CoordinatorClient::dropTable(const char* name)
{
Buffer req, resp;
uint32_t length = strlen(name) + 1;
DropTableRpc::Request& reqHdr(allocHeader<DropTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
sendRecv<DropTableRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* Look up a table by name and return a small integer handle that
* can be used to access the table.
*
* \param name
* Name of the desired table (NULL-terminated string).
*
* \return
* The return value is an identifier for the table; this is used
* instead of the table's name for most RAMCloud operations
* involving the table.
*
* \exception TableDoesntExistException
* \exception InternalError
*/
uint32_t
CoordinatorClient::openTable(const char* name)
{
Buffer req, resp;
uint32_t length = strlen(name) + 1;
OpenTableRpc::Request& reqHdr(allocHeader<OpenTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
const OpenTableRpc::Response& respHdr(
sendRecv<OpenTableRpc>(session, req, resp));
checkStatus(HERE);
return respHdr.tableId;
}
/**
* Servers call this when they come online to beg for work.
* \return
* A server ID guaranteed never to have been used before.
*/
uint64_t
CoordinatorClient::enlistServer(ServerType serverType,
string localServiceLocator)
{
while (true) {
try {
Buffer req;
Buffer resp;
EnlistServerRpc::Request& reqHdr(
allocHeader<EnlistServerRpc>(req));
reqHdr.serverType = serverType;
reqHdr.serviceLocatorLength = localServiceLocator.length() + 1;
strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
localServiceLocator.c_str(),
reqHdr.serviceLocatorLength);
const EnlistServerRpc::Response& respHdr(
sendRecv<EnlistServerRpc>(session, req, resp));
checkStatus(HERE);
return respHdr.serverId;
} catch (TransportException& e) {
LOG(NOTICE,
"TransportException trying to talk to coordinator: %s",
e.str().c_str());
LOG(NOTICE, "retrying");
yield();
}
}
}
/**
* List all live backup servers.
* Masters call and cache this periodically to find backups.
*/
void
CoordinatorClient::getBackupList(ProtoBuf::ServerList& serverList)
{
Buffer req;
Buffer resp;
allocHeader<GetBackupListRpc>(req);
const GetBackupListRpc::Response& respHdr(
sendRecv<GetBackupListRpc>(session, req, resp));
checkStatus(HERE);
ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
respHdr.serverListLength, serverList);
}
/**
* Return the entire tablet map.
* Clients use this to find objects.
* If the returned data becomes too big, we should add parameters to
* specify a subrange.
* \param[out] tabletMap
* Each tablet has a service locator string describing where to find
* its master.
*/
void
CoordinatorClient::getTabletMap(ProtoBuf::Tablets& tabletMap)
{
Buffer req;
Buffer resp;
allocHeader<GetTabletMapRpc>(req);
const GetTabletMapRpc::Response& respHdr(
sendRecv<GetTabletMapRpc>(session, req, resp));
checkStatus(HERE);
ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
respHdr.tabletMapLength, tabletMap);
}
/**
* Report a slow or dead server.
*/
void
CoordinatorClient::hintServerDown(string serviceLocator)
{
Buffer req;
Buffer resp;
HintServerDownRpc::Request& reqHdr(
allocHeader<HintServerDownRpc>(req));
reqHdr.serviceLocatorLength = serviceLocator.length() + 1;
strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
serviceLocator.c_str(),
reqHdr.serviceLocatorLength);
sendRecv<HintServerDownRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* \copydoc MasterClient::ping
*/
void
CoordinatorClient::ping()
{
Buffer req;
Buffer resp;
allocHeader<PingRpc>(req);
sendRecv<PingRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* Tell the coordinator that recovery of a particular tablets have
* been recovered on the master who is calling.
*
* \param tablets
* The tablets which form a partition of a will which are
* now done recovering.
*/
void
CoordinatorClient::tabletsRecovered(const ProtoBuf::Tablets& tablets)
{
Buffer req, resp;
TabletsRecoveredRpc::Request& reqHdr(allocHeader<TabletsRecoveredRpc>(req));
reqHdr.tabletsLength = serializeToResponse(req, tablets);
sendRecv<TabletsRecoveredRpc>(session, req, resp);
checkStatus(HERE);
}
} // namespace RAMCloud
<commit_msg>Expand CoordinatorClient docs<commit_after>/* Copyright (c) 2010 Stanford University
*
* Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "CoordinatorClient.h"
#include "ProtoBuf.h"
namespace RAMCloud {
/**
* Create a new table.
*
* \param name
* Name for the new table (NULL-terminated string).
*
* \exception InternalError
*/
void
CoordinatorClient::createTable(const char* name)
{
Buffer req;
uint32_t length = strlen(name) + 1;
CreateTableRpc::Request& reqHdr(allocHeader<CreateTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
while (true) {
Buffer resp;
sendRecv<CreateTableRpc>(session, req, resp);
try {
checkStatus(HERE);
return;
} catch (const RetryException& e) {
LOG(DEBUG, "RETRY trying to create table");
yield();
}
}
}
/**
* Delete a table.
*
* All objects in the table are implicitly deleted, along with any
* other information associated with the table (such as, someday,
* indexes). If the table does not currently exist than the operation
* returns successfully without actually doing anything.
*
* \param name
* Name of the table to delete (NULL-terminated string).
*
* \exception InternalError
*/
void
CoordinatorClient::dropTable(const char* name)
{
Buffer req, resp;
uint32_t length = strlen(name) + 1;
DropTableRpc::Request& reqHdr(allocHeader<DropTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
sendRecv<DropTableRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* Look up a table by name and return a small integer handle that
* can be used to access the table.
*
* \param name
* Name of the desired table (NULL-terminated string).
*
* \return
* The return value is an identifier for the table; this is used
* instead of the table's name for most RAMCloud operations
* involving the table.
*
* \exception TableDoesntExistException
* \exception InternalError
*/
uint32_t
CoordinatorClient::openTable(const char* name)
{
Buffer req, resp;
uint32_t length = strlen(name) + 1;
OpenTableRpc::Request& reqHdr(allocHeader<OpenTableRpc>(req));
reqHdr.nameLength = length;
memcpy(new(&req, APPEND) char[length], name, length);
const OpenTableRpc::Response& respHdr(
sendRecv<OpenTableRpc>(session, req, resp));
checkStatus(HERE);
return respHdr.tableId;
}
/**
* Servers call this when they come online to beg for work.
* \param serverType
* Master, etc.
* \param localServiceLocator
* The service locator describing how other hosts can contact the server.
* \return
* A server ID guaranteed never to have been used before.
*/
uint64_t
CoordinatorClient::enlistServer(ServerType serverType,
string localServiceLocator)
{
while (true) {
try {
Buffer req;
Buffer resp;
EnlistServerRpc::Request& reqHdr(
allocHeader<EnlistServerRpc>(req));
reqHdr.serverType = serverType;
reqHdr.serviceLocatorLength = localServiceLocator.length() + 1;
strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
localServiceLocator.c_str(),
reqHdr.serviceLocatorLength);
const EnlistServerRpc::Response& respHdr(
sendRecv<EnlistServerRpc>(session, req, resp));
checkStatus(HERE);
return respHdr.serverId;
} catch (TransportException& e) {
LOG(NOTICE,
"TransportException trying to talk to coordinator: %s",
e.str().c_str());
LOG(NOTICE, "retrying");
yield();
}
}
}
/**
* List all live backup servers.
* Masters call and cache this periodically to find backups.
* \param[out] serverList
* An empty ServerList that will be filled with current backup servers.
*/
void
CoordinatorClient::getBackupList(ProtoBuf::ServerList& serverList)
{
Buffer req;
Buffer resp;
allocHeader<GetBackupListRpc>(req);
const GetBackupListRpc::Response& respHdr(
sendRecv<GetBackupListRpc>(session, req, resp));
checkStatus(HERE);
ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
respHdr.serverListLength, serverList);
}
/**
* Return the entire tablet map.
* Clients use this to find objects.
* If the returned data becomes too big, we should add parameters to
* specify a subrange.
* \param[out] tabletMap
* An empty Tablets that will be filled with current tablets.
* Each tablet has a service locator string describing where to find
* its master.
*/
void
CoordinatorClient::getTabletMap(ProtoBuf::Tablets& tabletMap)
{
Buffer req;
Buffer resp;
allocHeader<GetTabletMapRpc>(req);
const GetTabletMapRpc::Response& respHdr(
sendRecv<GetTabletMapRpc>(session, req, resp));
checkStatus(HERE);
ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
respHdr.tabletMapLength, tabletMap);
}
/**
* Report a slow or dead server.
*/
void
CoordinatorClient::hintServerDown(string serviceLocator)
{
Buffer req;
Buffer resp;
HintServerDownRpc::Request& reqHdr(
allocHeader<HintServerDownRpc>(req));
reqHdr.serviceLocatorLength = serviceLocator.length() + 1;
strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
serviceLocator.c_str(),
reqHdr.serviceLocatorLength);
sendRecv<HintServerDownRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* \copydoc MasterClient::ping
*/
void
CoordinatorClient::ping()
{
Buffer req;
Buffer resp;
allocHeader<PingRpc>(req);
sendRecv<PingRpc>(session, req, resp);
checkStatus(HERE);
}
/**
* Tell the coordinator that recovery of a particular tablets have
* been recovered on the master who is calling.
*
* \param tablets
* The tablets which form a partition of a will which are
* now done recovering.
*/
void
CoordinatorClient::tabletsRecovered(const ProtoBuf::Tablets& tablets)
{
Buffer req, resp;
TabletsRecoveredRpc::Request& reqHdr(allocHeader<TabletsRecoveredRpc>(req));
reqHdr.tabletsLength = serializeToResponse(req, tablets);
sendRecv<TabletsRecoveredRpc>(session, req, resp);
checkStatus(HERE);
}
} // namespace RAMCloud
<|endoftext|> |
<commit_before><?hh // partial
namespace package\examples;
require_once __DIR__ . '/../vendor/autoload.php';
use package\Package;
$package = Package::fromOptions(shape(
'namespace' => 'package\\examples\\classes\\',
'packageDirectory' => realpath(__DIR__ . '/src')
));
foreach ($package->classes() as $class) {
$instance = $class->instantiate();
var_dump($instance);
}
<commit_msg>Update example<commit_after><?hh // partial
namespace package\examples;
require_once __DIR__ . '/../vendor/autoload.php';
use package\Package;
$classes = Package::fromOptions(shape(
'namespace' => 'package\\examples\\classes\\',
'packageDirectory' => realpath(__DIR__ . '/src')
))->classes()->toImmVector();
foreach ($classes as $class) {
$instance = $class->instantiate();
var_dump($instance);
}
<|endoftext|> |
<commit_before>/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include <fstream>
#include <iostream>
#include <vector>
#include <hdf5/hdffile.hpp>
#include <hdf5/hdfdataset.hpp>
using std::ofstream;
using std::ios;
#include "Time.H"
#include "zCFDFvMesh.H"
#include "primitiveMesh.H"
#include "wallFvPatch.H"
#include "symmetryFvPatch.H"
#include "cellModeller.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::zCFDFvMesh::zCFDFvMesh(const IOobject& io)
:
fvMesh(io)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::zCFDFvMesh::writezCFDMesh() const
{
// make a directory called proInterface in the case
mkDir(time().rootPath()/time().caseName()/"zCFDInterface");
// open a file for the mesh
std::string filename = (
time().rootPath()/
time().caseName()/
"zCFDInterface"/
time().caseName() + ".h5"
).c_str();
hdf::HDFFile<> file(filename, hdf::HDFFile<>::truncate);
Info<< "Writing Header" << endl;
boost::shared_ptr<hdf::HDFGroup<> > meshg = file.openGroup("mesh", true);
std::vector<hsize_t> dims(1, 1);
meshg->createAttribute<int>("numFaces", dims)->writeData(nFaces());
meshg->createAttribute<int>("numCells", dims)->writeData(nCells());
int numFaces = nFaces();
int numCells = nCells();
std::vector<hsize_t> fileDims(2);
Info<< "Writing Points" << endl;
// Writing points
{
std::vector<double> coord;
coord.reserve(nPoints()*3);
const pointField& p = points();
forAll(p, pointI)
{
coord.push_back(p[pointI].x());
coord.push_back(p[pointI].y());
coord.push_back(p[pointI].z());
}
fileDims[0] = coord.size()/3;
fileDims[1] = 3;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<double>("nodeVertex", d1)->writeData(coord);
}
Info<< "Writing Neighbours" << endl;
const labelUList& own = owner();
const labelUList& nei = neighbour();
//const labelUList& cellZone = cellZones();
/*
const wordList& cellZone = cellZones().names();
forAll(cellZone, cz)
{
Info << cellZone[cz] << endl;
Info << cellZones().whichZone(0) << endl;
//Info<< cellZones()[cz] << std::endl;
}
*/
std::vector<int> cellZone(numCells,0);
//std::map<int,int> foamCellZoneMap;
for(int i = 0; i < numCells;++i){
int cz = cellZones().whichZone(i);
cellZone[i] = cz+1;
}
{
fileDims[0] = cellZone.size();
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("cellZone", d1)->writeData(cellZone);
}
Info<< "Face Zones" << endl;
const wordList& faceZone = faceZones().names();
forAll(faceZone, cz)
{
Info << faceZone[cz] << endl;
//Info<< cellZones()[cz] << std::endl;
// }
}
{ // Face cell
fileDims[0] = numFaces;
fileDims[1] = 2;
hdf::Slab<1> d2(fileDims);
dims[0] = 2 * numFaces;
hdf::Slab<1> memFaceCell(dims);
boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceCell", d2);
std::vector<int> faceCell;
//faceCell.reserve(2 * 50000);
int faceOffset=0;
int i=0;
forAll(own, faceI)
{
int left = own[faceI];
int right = nei[faceI];
faceCell.push_back(left);
faceCell.push_back(right);
/*
if(i % 50000)
{
std::vector<hsize_t> dims(2,0);
dims[0] = numFaces;
dims[1] = 2;
hdf::Slab<2> filespace(dims);
dims[0] = 50000;
dims[1] = 2;
hdf::Slab<2> memspace(dims);
std::vector<hsize_t> offset(2,0);
offset[0] = faceOffset;
std::vector<hsize_t> stride(2,1);
hdf::Slab<2> fileselec(filespace,offset,stride,dims);
dataset->writeData(&faceCell[0],memspace,fileselec);
faceCell.resize(0);
faceOffset += 50000;
}*/
i++;
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
const labelList& patchFaceCells =
boundaryMesh()[patchI].faceCells();
forAll(patchFaces, faceI)
{
int left = patchFaceCells[faceI];
int right = numCells;
faceCell.push_back(left);
faceCell.push_back(right);
numCells++;
}
}
if(faceCell.size())
{
std::vector<hsize_t> dims(2,0);
dims[0] = numFaces;
dims[1] = 2;
hdf::Slab<2> filespace(dims);
dims[0] = faceCell.size()/2;
dims[1] = 2;
hdf::Slab<2> memspace(dims);
std::vector<hsize_t> offset(2,0);
offset[0] = faceOffset;
std::vector<hsize_t> stride(2,1);
hdf::Slab<2> fileselec(filespace,offset,stride,dims);
dataset->writeData(&faceCell[0],memspace,fileselec);
}
faceOffset += faceCell.size()/2;
faceCell.resize(0);
}
Info<< "Writing Faces" << endl;
const faceList& fcs = faces();
size_t totalFaceNodes=0;
{ // FaceType
std::vector<int> faceType;
faceType.reserve(numFaces);
forAll(own, faceI)
{
const labelList& l = fcs[faceI];
int n = l.size();
faceType.push_back(n);
totalFaceNodes+=n;
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
const labelList& l = patchFaces[faceI];
int n = l.size();
faceType.push_back(n);
totalFaceNodes+=n;
}
}
fileDims[0] = numFaces;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceType", d1)->writeData(faceType);
}
{ // Face nodes
fileDims[0] = totalFaceNodes;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceNodes", d1);
std::vector<int> faceNodes;
faceNodes.reserve(totalFaceNodes);
forAll(own, faceI)
{
const labelList& l = fcs[faceI];
forAll(l, lI)
{
faceNodes.push_back(l[lI]);
}
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
const labelList& l = patchFaces[faceI];
forAll(l, lI)
{
faceNodes.push_back(l[lI]);
}
}
}
dataset->writeData(faceNodes);
}
Info<< "Writing Boundary Conditions" << endl;
{ // FaceBC
std::vector<int> faceBC(numFaces, 0);
int i=0;
forAll(own, faceI)
{
faceBC[i] = 0; i++;
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
int bc = -1;
// Write patch type
if (isA<wallFvPatch>(boundary()[patchI]))
{
bc=3;
}
else if (isA<symmetryFvPatch>(boundary()[patchI]))
{
bc=7;
}
else
{
bc=9;
}
faceBC[i] = bc; i++;
}
}
assert(i == numFaces);
fileDims[0] = numFaces;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceBC", d1)->writeData(faceBC);
}
{ // Face Info
std::vector<int> faceInfo;
faceInfo.reserve(2 * numFaces);
forAll(own, faceI)
{
int z = 0;
int dummy = 0;
faceInfo.push_back(z);
faceInfo.push_back(dummy);
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
int z = patchI+1;
int dummy = 0;
faceInfo.push_back(z);
faceInfo.push_back(dummy);
}
}
fileDims[0] = numFaces;
fileDims[1] = 2;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceInfo", d1)->writeData(faceInfo);
}
}
// ************************************************************************* //
<commit_msg>Added zone map writer<commit_after>/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <hdf5/hdffile.hpp>
#include <hdf5/hdfdataset.hpp>
using std::ofstream;
using std::ios;
#include "Time.H"
#include "zCFDFvMesh.H"
#include "primitiveMesh.H"
#include "wallFvPatch.H"
#include "symmetryFvPatch.H"
#include "cellModeller.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::zCFDFvMesh::zCFDFvMesh(const IOobject& io)
:
fvMesh(io)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::zCFDFvMesh::writezCFDMesh() const
{
// make a directory called proInterface in the case
mkDir(time().rootPath()/time().caseName()/"zCFDInterface");
// open a file for the mesh
std::string filename = (
time().rootPath()/
time().caseName()/
"zCFDInterface"/
time().caseName() + ".h5"
).c_str();
hdf::HDFFile<> file(filename, hdf::HDFFile<>::truncate);
Info<< "Writing Header" << endl;
boost::shared_ptr<hdf::HDFGroup<> > meshg = file.openGroup("mesh", true);
std::vector<hsize_t> dims(1, 1);
meshg->createAttribute<int>("numFaces", dims)->writeData(nFaces());
meshg->createAttribute<int>("numCells", dims)->writeData(nCells());
int numFaces = nFaces();
int numCells = nCells();
std::vector<hsize_t> fileDims(2);
Info<< "Writing Points" << endl;
// Writing points
{
std::vector<double> coord;
coord.reserve(nPoints()*3);
const pointField& p = points();
forAll(p, pointI)
{
coord.push_back(p[pointI].x());
coord.push_back(p[pointI].y());
coord.push_back(p[pointI].z());
}
fileDims[0] = coord.size()/3;
fileDims[1] = 3;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<double>("nodeVertex", d1)->writeData(coord);
}
Info<< "Writing Neighbours" << endl;
const labelUList& own = owner();
const labelUList& nei = neighbour();
//const labelUList& cellZone = cellZones();
/*
const wordList& cellZone = cellZones().names();
forAll(cellZone, cz)
{
Info << cellZone[cz] << endl;
Info << cellZones().whichZone(0) << endl;
//Info<< cellZones()[cz] << std::endl;
}
*/
std::vector<int> cellZone(numCells,0);
//std::map<int,int> foamCellZoneMap;
for(int i = 0; i < numCells;++i){
int cz = cellZones().whichZone(i);
cellZone[i] = cz+1;
}
{
fileDims[0] = cellZone.size();
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("cellZone", d1)->writeData(cellZone);
}
Info<< "Face Zones" << endl;
const wordList& faceZone = faceZones().names();
forAll(faceZone, cz)
{
Info << faceZone[cz] << endl;
//Info<< cellZones()[cz] << std::endl;
// }
}
{ // Face cell
fileDims[0] = numFaces;
fileDims[1] = 2;
hdf::Slab<1> d2(fileDims);
dims[0] = 2 * numFaces;
hdf::Slab<1> memFaceCell(dims);
boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceCell", d2);
std::vector<int> faceCell;
//faceCell.reserve(2 * 50000);
int faceOffset=0;
int i=0;
forAll(own, faceI)
{
int left = own[faceI];
int right = nei[faceI];
faceCell.push_back(left);
faceCell.push_back(right);
/*
if(i % 50000)
{
std::vector<hsize_t> dims(2,0);
dims[0] = numFaces;
dims[1] = 2;
hdf::Slab<2> filespace(dims);
dims[0] = 50000;
dims[1] = 2;
hdf::Slab<2> memspace(dims);
std::vector<hsize_t> offset(2,0);
offset[0] = faceOffset;
std::vector<hsize_t> stride(2,1);
hdf::Slab<2> fileselec(filespace,offset,stride,dims);
dataset->writeData(&faceCell[0],memspace,fileselec);
faceCell.resize(0);
faceOffset += 50000;
}*/
i++;
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
const labelList& patchFaceCells =
boundaryMesh()[patchI].faceCells();
forAll(patchFaces, faceI)
{
int left = patchFaceCells[faceI];
int right = numCells;
faceCell.push_back(left);
faceCell.push_back(right);
numCells++;
}
}
if(faceCell.size())
{
std::vector<hsize_t> dims(2,0);
dims[0] = numFaces;
dims[1] = 2;
hdf::Slab<2> filespace(dims);
dims[0] = faceCell.size()/2;
dims[1] = 2;
hdf::Slab<2> memspace(dims);
std::vector<hsize_t> offset(2,0);
offset[0] = faceOffset;
std::vector<hsize_t> stride(2,1);
hdf::Slab<2> fileselec(filespace,offset,stride,dims);
dataset->writeData(&faceCell[0],memspace,fileselec);
}
faceOffset += faceCell.size()/2;
faceCell.resize(0);
}
Info<< "Writing Faces" << endl;
const faceList& fcs = faces();
size_t totalFaceNodes=0;
{ // FaceType
std::vector<int> faceType;
faceType.reserve(numFaces);
forAll(own, faceI)
{
const labelList& l = fcs[faceI];
int n = l.size();
faceType.push_back(n);
totalFaceNodes+=n;
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
const labelList& l = patchFaces[faceI];
int n = l.size();
faceType.push_back(n);
totalFaceNodes+=n;
}
}
fileDims[0] = numFaces;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceType", d1)->writeData(faceType);
}
{ // Face nodes
fileDims[0] = totalFaceNodes;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceNodes", d1);
std::vector<int> faceNodes;
faceNodes.reserve(totalFaceNodes);
forAll(own, faceI)
{
const labelList& l = fcs[faceI];
forAll(l, lI)
{
faceNodes.push_back(l[lI]);
}
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
const labelList& l = patchFaces[faceI];
forAll(l, lI)
{
faceNodes.push_back(l[lI]);
}
}
}
dataset->writeData(faceNodes);
}
Info<< "Writing Boundary Conditions" << endl;
std::vector<std::string> bcType;
{ // FaceBC
std::vector<int> faceBC(numFaces, 0);
int i=0;
forAll(own, faceI)
{
faceBC[i] = 0; i++;
}
forAll(boundary(), patchI)
{
int bc = -1;
// Write patch type
if (isA<wallFvPatch>(boundary()[patchI]))
{
bc=3;
bcType.push_back("wall");
}
else if (isA<symmetryFvPatch>(boundary()[patchI]))
{
bc=7;
bcType.push_back("symmetry");
}
else
{
bc=9;
bcType.push_back("freestream");
}
const faceUList& patchFaces = boundaryMesh()[patchI];
forAll(patchFaces, faceI)
{
faceBC[i] = bc; i++;
}
}
assert(i == numFaces);
fileDims[0] = numFaces;
fileDims[1] = 1;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceBC", d1)->writeData(faceBC);
}
std::map<int,std::string> bcNames;
{ // Face Info
std::vector<int> faceInfo;
faceInfo.reserve(2 * numFaces);
forAll(own, faceI)
{
int z = 0;
int dummy = 0;
faceInfo.push_back(z);
faceInfo.push_back(dummy);
}
forAll(boundary(), patchI)
{
const faceUList& patchFaces = boundaryMesh()[patchI];
const wordList& names = boundaryMesh().names();
int z = patchI+1;
bcNames[patchI] = names[patchI];
forAll(patchFaces, faceI)
{
int dummy = 0;
faceInfo.push_back(z);
faceInfo.push_back(dummy);
}
}
fileDims[0] = numFaces;
fileDims[1] = 2;
hdf::Slab<1> d1(fileDims);
meshg->createDataset<int>("faceInfo", d1)->writeData(faceInfo);
}
{ // zone.py
// Write zone helper
std::string filename = (
time().rootPath()/
time().caseName()/
"zCFDInterface"/
time().caseName() + "_zone.py"
).c_str();
std::ofstream out(filename.c_str());
std::map<std::string, std::string> bcMap;
bcMap["interior"] = "interior";
bcMap["symmetry"] = "symmetry";
bcMap["symmetry2"] = "symmetry plane";
bcMap["freestream"] = "freestream";
bcMap["wall"] = "wall";
bcMap["inlet"] = "inlet";
bcMap["pressure"] = "pressure";
int zoneId = 1;
out << "# Zone handling helper functions\n\n";
out << "zone_name_to_id={";
for (std::vector<std::string>::iterator itr = bcType.begin(); itr != bcType.end();
++itr) {
out << "\"" << bcNames[zoneId - 1] << "\": " << zoneId << ",\n";
zoneId++;
}
out << "}\n";
out << "id_to_zone_name= {v: k for k, v in zone_name_to_id.items()}\n";
out << "def to_id(names):\n";
out << " # Converts names list to id list\n";
out << " id=[]\n";
out << " for n in names:\n";
out << " id.append(zone_name_to_id[n])\n";
out << " return id\n";
out << "def from_id(id):\n";
out << " # returns name of id\n";
out << " return id_to_zone_name[id]\n";
out << "fluid_zone={";
out << "\""
<< "fluid"
<< "\": " << 1 << ",\n";
out << "}\n";
for (std::map<std::string, std::string>::iterator bit = bcMap.begin();
bit != bcMap.end(); ++bit) {
out << bit->first << "=[";
zoneId = 1;
for (std::vector<std::string>::iterator itr = bcType.begin(); itr != bcType.end();
++itr) {
std::string bcName = *itr;
if (bcName == bit->second) {
out << "\"" << bcNames[zoneId - 1] << "\",";
}
zoneId++;
}
out << "]\n";
}
out.close();
}
}
// ************************************************************************* //
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResultFuture> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResultFuture> result(new TaskResultFuture());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
runPipeline(app.get(), &pipeline, result);
if (instance->failed) {
RAISE(kRuntimeError, "task failed");
}
result->returnResult(instance->task);
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::runPipeline(
Application* app,
LocalTaskPipeline* pipeline,
RefPtr<TaskResultFuture> result) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
result->updateStatus([&pipeline] (TaskStatus* status) {
status->num_subtasks_total = pipeline->tasks.size();
});
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto cache_key = taskref->task->cacheKeySHA1();
if (!cache_key.isEmpty()) {
taskref->cache_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("cache_$0", cache_key.get()));
}
auto cached =
!cache_key.isEmpty() &&
FileUtil::exists(taskref->cache_filename);
if (cached) {
auto cache_file = File::openFile(
taskref->cache_filename,
File::O_READ);
Buffer cache_hdr(sizeof(uint64_t));
cache_file.read(&cache_hdr);
util::BinaryMessageReader reader(cache_hdr.data(), cache_hdr.size());
auto cache_version = *reader.readUInt64();
auto cache_size = cache_file.size() - cache_hdr.size();
fnord::logDebug(
"fnord.dproc",
"Reading RDD from cache: $0, key=$1, version=$2",
taskref->debug_name,
cache_key.isEmpty() ? "<nil>" : cache_key.get(),
cache_version);
taskref->task->decode(
new io::MmappedFile(
std::move(cache_file),
cache_hdr.size(),
cache_size));
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
taskref->finished = true;
waiting = false;
break;
}
auto parent_task = taskref;
size_t numdeps = 0;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
++numdeps;
}
if (numdeps > 0) {
result->updateStatus([numdeps] (TaskStatus* status) {
status->num_subtasks_total += numdeps;
});
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (dep->failed) {
taskref->failed = true;
taskref->finished = true;
waiting = false;
}
if (!dep->finished) {
deps_finished = false;
}
}
if (!taskref->finished) {
if (!deps_finished) {
++num_waiting;
continue;
}
auto ckey = taskref->task->cacheKeySHA1();
fnord::logDebug(
"fnord.dproc",
"Computing RDD: $0, key=$1, version=$2",
taskref->debug_name,
ckey.isEmpty() ? "<nil>" : ckey.get(),
taskref->task->cacheVersion());
taskref->running = true;
tpool_.run(std::bind(
&LocalScheduler::runTask,
this,
pipeline,
taskref,
result));
waiting = false;
}
}
fnord::logDebug(
"fnord.dproc",
"Running local pipeline id=$0: $1",
(void*) pipeline,
result->status().toString());
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logDebug(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task,
RefPtr<TaskResultFuture> result) {
try {
task->task->compute(task.get());
if (!task->cache_filename.empty()) {
auto cache_file = task->cache_filename;
{
auto f = File::openFile(
cache_file + "~",
File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);
util::BinaryMessageWriter hdr;
hdr.appendUInt64(task->task->cacheVersion());
f.write(hdr.data(), hdr.size());
auto res = task->task->encode();
f.write(res->data(), res->size());
}
FileUtil::mv(cache_file + "~", cache_file);
}
} catch (const std::exception& e) {
task->failed = true;
fnord::logError("fnord.dproc", e, "error");
}
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
running(false),
expanded(false),
finished(false),
failed(false) {}
RefPtr<Task> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
return dep->task;
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<commit_msg>cache filenames<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-dproc/LocalScheduler.h>
namespace fnord {
namespace dproc {
LocalScheduler::LocalScheduler(
const String& tempdir /* = "/tmp" */,
size_t max_threads /* = 8 */,
size_t max_requests /* = 32 */) :
tempdir_(tempdir),
tpool_(max_threads),
req_tpool_(max_requests) {}
void LocalScheduler::start() {
req_tpool_.start();
tpool_.start();
}
void LocalScheduler::stop() {
req_tpool_.stop();
tpool_.stop();
}
RefPtr<TaskResultFuture> LocalScheduler::run(
RefPtr<Application> app,
const TaskSpec& task) {
RefPtr<TaskResultFuture> result(new TaskResultFuture());
try {
auto instance = mkRef(
new LocalTaskRef(
app,
task.task_name(),
Buffer(task.params().data(), task.params().size())));
req_tpool_.run([this, app, result, instance] () {
try {
LocalTaskPipeline pipeline;
pipeline.tasks.push_back(instance);
runPipeline(app.get(), &pipeline, result);
if (instance->failed) {
RAISE(kRuntimeError, "task failed");
}
result->returnResult(instance->task);
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
});
} catch (const StandardException& e) {
fnord::logError("dproc.scheduler", e, "task failed");
result->returnError(e);
}
return result;
}
void LocalScheduler::runPipeline(
Application* app,
LocalTaskPipeline* pipeline,
RefPtr<TaskResultFuture> result) {
fnord::logInfo(
"fnord.dproc",
"Starting local pipeline id=$0 tasks=$1",
(void*) pipeline,
pipeline->tasks.size());
std::unique_lock<std::mutex> lk(pipeline->mutex);
result->updateStatus([&pipeline] (TaskStatus* status) {
status->num_subtasks_total = pipeline->tasks.size();
});
while (pipeline->tasks.size() > 0) {
bool waiting = true;
size_t num_waiting = 0;
size_t num_running = 0;
size_t num_completed = 0;
for (auto& taskref : pipeline->tasks) {
if (taskref->finished) {
++num_completed;
continue;
}
if (taskref->running) {
++num_running;
continue;
}
if (!taskref->expanded) {
taskref->expanded = true;
auto cache_key = taskref->task->cacheKeySHA1();
if (!cache_key.isEmpty()) {
taskref->cache_filename = FileUtil::joinPaths(
tempdir_,
StringUtil::format("$0.rdd", cache_key.get()));
}
auto cached =
!cache_key.isEmpty() &&
FileUtil::exists(taskref->cache_filename);
if (cached) {
auto cache_file = File::openFile(
taskref->cache_filename,
File::O_READ);
Buffer cache_hdr(sizeof(uint64_t));
cache_file.read(&cache_hdr);
util::BinaryMessageReader reader(cache_hdr.data(), cache_hdr.size());
auto cache_version = *reader.readUInt64();
auto cache_size = cache_file.size() - cache_hdr.size();
fnord::logDebug(
"fnord.dproc",
"Reading RDD from cache: $0, key=$1, version=$2",
taskref->debug_name,
cache_key.isEmpty() ? "<nil>" : cache_key.get(),
cache_version);
taskref->task->decode(
new io::MmappedFile(
std::move(cache_file),
cache_hdr.size(),
cache_size));
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
taskref->finished = true;
waiting = false;
break;
}
auto parent_task = taskref;
size_t numdeps = 0;
for (const auto& dep : taskref->task->dependencies()) {
RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
parent_task->dependencies.emplace_back(depref);
pipeline->tasks.emplace_back(depref);
++numdeps;
}
if (numdeps > 0) {
result->updateStatus([numdeps] (TaskStatus* status) {
status->num_subtasks_total += numdeps;
});
}
waiting = false;
break;
}
bool deps_finished = true;
for (const auto& dep : taskref->dependencies) {
if (dep->failed) {
taskref->failed = true;
taskref->finished = true;
waiting = false;
}
if (!dep->finished) {
deps_finished = false;
}
}
if (!taskref->finished) {
if (!deps_finished) {
++num_waiting;
continue;
}
auto ckey = taskref->task->cacheKeySHA1();
fnord::logDebug(
"fnord.dproc",
"Computing RDD: $0, key=$1, version=$2",
taskref->debug_name,
ckey.isEmpty() ? "<nil>" : ckey.get(),
taskref->task->cacheVersion());
taskref->running = true;
tpool_.run(std::bind(
&LocalScheduler::runTask,
this,
pipeline,
taskref,
result));
waiting = false;
}
}
fnord::logDebug(
"fnord.dproc",
"Running local pipeline id=$0: $1",
(void*) pipeline,
result->status().toString());
if (waiting) {
pipeline->wakeup.wait(lk);
}
while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
pipeline->tasks.pop_back();
}
}
fnord::logDebug(
"fnord.dproc",
"Completed local pipeline id=$0",
(void*) pipeline);
}
void LocalScheduler::runTask(
LocalTaskPipeline* pipeline,
RefPtr<LocalTaskRef> task,
RefPtr<TaskResultFuture> result) {
try {
task->task->compute(task.get());
if (!task->cache_filename.empty()) {
auto cache_file = task->cache_filename;
{
auto f = File::openFile(
cache_file + "~",
File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);
util::BinaryMessageWriter hdr;
hdr.appendUInt64(task->task->cacheVersion());
f.write(hdr.data(), hdr.size());
auto res = task->task->encode();
f.write(res->data(), res->size());
}
FileUtil::mv(cache_file + "~", cache_file);
}
} catch (const std::exception& e) {
task->failed = true;
fnord::logError("fnord.dproc", e, "error");
}
result->updateStatus([&pipeline] (TaskStatus* status) {
++status->num_subtasks_completed;
});
std::unique_lock<std::mutex> lk(pipeline->mutex);
task->finished = true;
lk.unlock();
pipeline->wakeup.notify_all();
}
LocalScheduler::LocalTaskRef::LocalTaskRef(
RefPtr<Application> app,
const String& task_name,
const Buffer& params) :
task(app->getTaskInstance(task_name, params)),
debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
running(false),
expanded(false),
finished(false),
failed(false) {}
RefPtr<Task> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
if (index >= dependencies.size()) {
RAISEF(kIndexError, "invalid dependecy index: $0", index);
}
const auto& dep = dependencies[index];
return dep->task;
}
size_t LocalScheduler::LocalTaskRef::numDependencies() const {
return dependencies.size();
}
} // namespace dproc
} // namespace fnord
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief R8C/M110AN, R8C/M120AN グループ・システム・レジスター定義 @n
Copyright 2014 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief プロセッサモードレジスタ0 PM0
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0010> pm0_io;
struct pm0_t : public pm0_io {
using pm0_io::operator =;
using pm0_io::operator ();
using pm0_io::operator |=;
using pm0_io::operator &=;
bit_t<pm0_io, 3> SRST;
};
static pm0_t PM0;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief モジュールスタンバイ制御レジスタ MSTCR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0012> mstcr_io;
struct mstcr_t : public mstcr_io {
using mstcr_io::operator =;
using mstcr_io::operator ();
using mstcr_io::operator |=;
using mstcr_io::operator &=;
bit_t<mstcr_io, 0> MSTTRJ;
bit_t<mstcr_io, 1> MSTTRB;
bit_t<mstcr_io, 4> MSTAD;
bit_t<mstcr_io, 5> MSTTRC;
bit_t<mstcr_io, 6> MSTUART;
};
static mstcr_t MSTCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief プロテクトレジスタ PRCR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0013> prcr_io;
struct prcr_t : public prcr_io {
using prcr_io::operator =;
using prcr_io::operator ();
using prcr_io::operator |=;
using prcr_io::operator &=;
bit_t<prcr_io, 0> PRC0;
bit_t<prcr_io, 1> PRC1;
bit_t<prcr_io, 3> PRC3;
bit_t<prcr_io, 4> PRC4;
};
static prcr_t PRCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ハードウェアリセットプロテクトレジスタ HRPR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0016> hrpr_io;
struct hrpr_t : public hrpr_io {
using hrpr_io::operator =;
using hrpr_io::operator ();
using hrpr_io::operator |=;
using hrpr_io::operator &=;
bit_t<hrpr_io, 0> RAMCRE;
};
static hrpr_t HRPR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief リセット要因判別レジスタ RSTFR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x005f> rstfr_io;
typedef io8_ro<0x005f> rstfr_io_ro;
struct rstfr_t : public rstfr_io, rstfr_io_ro {
using rstfr_io::operator =;
using rstfr_io::operator ();
using rstfr_io::operator |=;
using rstfr_io::operator &=;
using rstfr_io_ro::operator ();
bit_t<rstfr_io, 0> CWR;
bit_t<rstfr_io_ro, 1> HWR;
bit_t<rstfr_io_ro, 2> SWR;
bit_t<rstfr_io_ro, 3> WDR;
};
static rstfr_t RSTFR;
}
<commit_msg>update comment<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief R8C/M110AN, R8C/M120AN グループ・システム・レジスター定義 @n
Copyright 2014 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief プロセッサモードレジスタ0 PM0
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0010> pm0_io;
struct pm0_t : public pm0_io {
using pm0_io::operator =;
using pm0_io::operator ();
using pm0_io::operator |=;
using pm0_io::operator &=;
bit_t<pm0_io, 3> SRST;
};
static pm0_t PM0;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief モジュールスタンバイ制御レジスタ MSTCR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0012> mstcr_io;
struct mstcr_t : public mstcr_io {
using mstcr_io::operator =;
using mstcr_io::operator ();
using mstcr_io::operator |=;
using mstcr_io::operator &=;
bit_t<mstcr_io, 0> MSTTRJ;
bit_t<mstcr_io, 1> MSTTRB;
bit_t<mstcr_io, 4> MSTAD;
bit_t<mstcr_io, 5> MSTTRC;
bit_t<mstcr_io, 6> MSTUART;
};
static mstcr_t MSTCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief プロテクトレジスタ PRCR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0013> prcr_io;
struct prcr_t : public prcr_io {
using prcr_io::operator =;
using prcr_io::operator ();
using prcr_io::operator |=;
using prcr_io::operator &=;
bit_t<prcr_io, 0> PRC0;
bit_t<prcr_io, 1> PRC1;
bit_t<prcr_io, 3> PRC3;
bit_t<prcr_io, 4> PRC4;
};
static prcr_t PRCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ハードウェアリセットプロテクトレジスタ HRPR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x0016> hrpr_io;
struct hrpr_t : public hrpr_io {
using hrpr_io::operator =;
using hrpr_io::operator ();
using hrpr_io::operator |=;
using hrpr_io::operator &=;
bit_t<hrpr_io, 0> RAMCRE;
};
static hrpr_t HRPR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief リセット要因判別レジスタ RSTFR
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef io8<0x005f> rstfr_io;
typedef io8_ro<0x005f> rstfr_io_ro;
struct rstfr_t : public rstfr_io, rstfr_io_ro {
using rstfr_io::operator =;
using rstfr_io::operator ();
using rstfr_io::operator |=;
using rstfr_io::operator &=;
using rstfr_io_ro::operator ();
bit_t<rstfr_io, 0> CWR;
bit_t<rstfr_io_ro, 1> HWR;
bit_t<rstfr_io_ro, 2> SWR;
bit_t<rstfr_io_ro, 3> WDR;
};
static rstfr_t RSTFR;
}
<|endoftext|> |
<commit_before>#include "species.hpp"
#include "vboindexer.hpp"
#include "universe.hpp"
#include "scene.hpp"
#include "shader.hpp"
#include "material.hpp"
#include "object.hpp"
#include "species_or_glyph.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include standard headers
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
namespace yli
{
namespace ontology
{
void Species::bind_object(yli::ontology::Object* const object)
{
// get `childID` from `Species` and set pointer to `object`.
yli::hierarchy::bind_child_to_parent<yli::ontology::Object*>(
object,
this->object_pointer_vector,
this->free_objectID_queue,
this->number_of_objects);
}
void Species::unbind_object(const std::size_t childID)
{
yli::hierarchy::unbind_child_from_parent(
childID,
this->object_pointer_vector,
this->free_objectID_queue,
this->number_of_objects);
}
void Species::bind_to_parent()
{
// get `childID` from `Material` and set pointer to this `Species`.
this->material_parent->bind_species(this);
}
void Species::bind_to_new_parent(yli::ontology::Material* const new_material_pointer)
{
// unbind from the old parent `Material`.
this->material_parent->unbind_species(this->childID);
// get `childID` from `Material` and set pointer to this `Species`.
this->material_parent = new_material_pointer;
this->material_parent->bind_species(this);
}
Species::~Species()
{
if (!this->is_symbiont_species)
{
// destructor.
std::cout << "Species with childID " << std::dec << this->childID << " will be destroyed.\n";
// destroy all objects of this species.
std::cout << "All objects of this species will be destroyed.\n";
yli::hierarchy::delete_children<yli::ontology::Object*>(this->object_pointer_vector, this->number_of_objects);
// Cleanup VBO, shader and texture.
glDeleteBuffers(1, &this->vertexbuffer);
glDeleteBuffers(1, &this->uvbuffer);
glDeleteBuffers(1, &this->normalbuffer);
glDeleteBuffers(1, &this->elementbuffer);
// set pointer to this species to nullptr.
this->material_parent->set_species_pointer(this->childID, nullptr);
}
}
void Species::render()
{
if (this->vram_buffer_in_use)
{
this->prerender();
// render this `Species`.
yli::ontology::render_species_or_glyph<yli::ontology::Species*>(this);
this->postrender();
}
}
yli::ontology::Entity* Species::get_parent() const
{
if (this->is_symbiont_species)
{
return nullptr;
}
return this->material_parent;
}
void Species::set_object_pointer(const std::size_t childID, yli::ontology::Object* const child_pointer)
{
yli::hierarchy::set_child_pointer(childID, child_pointer, this->object_pointer_vector, this->free_objectID_queue, this->number_of_objects);
}
std::size_t Species::get_image_width() const
{
return this->image_width;
}
const std::string& Species::get_model_file_format() const
{
return this->model_file_format;
}
std::size_t Species::get_image_height() const
{
return this->image_height;
}
}
}
<commit_msg>`Species::bind_to_parent`: check `this->material_parent` for `nullptr`.<commit_after>#include "species.hpp"
#include "vboindexer.hpp"
#include "universe.hpp"
#include "scene.hpp"
#include "shader.hpp"
#include "material.hpp"
#include "object.hpp"
#include "species_or_glyph.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include standard headers
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
namespace yli
{
namespace ontology
{
void Species::bind_object(yli::ontology::Object* const object)
{
// get `childID` from `Species` and set pointer to `object`.
yli::hierarchy::bind_child_to_parent<yli::ontology::Object*>(
object,
this->object_pointer_vector,
this->free_objectID_queue,
this->number_of_objects);
}
void Species::unbind_object(const std::size_t childID)
{
yli::hierarchy::unbind_child_from_parent(
childID,
this->object_pointer_vector,
this->free_objectID_queue,
this->number_of_objects);
}
void Species::bind_to_parent()
{
// requirements:
// `this->material_parent` must not be `nullptr`.
yli::ontology::Material* const material = this->material_parent;
if (material == nullptr)
{
std::cerr << "ERROR: `Species::bind_to_parent`: `material` is `nullptr`!\n";
return;
}
// get `childID` from `Material` and set pointer to this `Species`.
this->material_parent->bind_species(this);
}
void Species::bind_to_new_parent(yli::ontology::Material* const new_material_pointer)
{
// unbind from the old parent `Material`.
this->material_parent->unbind_species(this->childID);
// get `childID` from `Material` and set pointer to this `Species`.
this->material_parent = new_material_pointer;
this->material_parent->bind_species(this);
}
Species::~Species()
{
if (!this->is_symbiont_species)
{
// destructor.
std::cout << "Species with childID " << std::dec << this->childID << " will be destroyed.\n";
// destroy all objects of this species.
std::cout << "All objects of this species will be destroyed.\n";
yli::hierarchy::delete_children<yli::ontology::Object*>(this->object_pointer_vector, this->number_of_objects);
// Cleanup VBO, shader and texture.
glDeleteBuffers(1, &this->vertexbuffer);
glDeleteBuffers(1, &this->uvbuffer);
glDeleteBuffers(1, &this->normalbuffer);
glDeleteBuffers(1, &this->elementbuffer);
// set pointer to this species to nullptr.
this->material_parent->set_species_pointer(this->childID, nullptr);
}
}
void Species::render()
{
if (this->vram_buffer_in_use)
{
this->prerender();
// render this `Species`.
yli::ontology::render_species_or_glyph<yli::ontology::Species*>(this);
this->postrender();
}
}
yli::ontology::Entity* Species::get_parent() const
{
if (this->is_symbiont_species)
{
return nullptr;
}
return this->material_parent;
}
void Species::set_object_pointer(const std::size_t childID, yli::ontology::Object* const child_pointer)
{
yli::hierarchy::set_child_pointer(childID, child_pointer, this->object_pointer_vector, this->free_objectID_queue, this->number_of_objects);
}
std::size_t Species::get_image_width() const
{
return this->image_width;
}
const std::string& Species::get_model_file_format() const
{
return this->model_file_format;
}
std::size_t Species::get_image_height() const
{
return this->image_height;
}
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "taskschedulertbb.h"
namespace embree
{
bool g_tbb_threads_initialized = false;
tbb::task_scheduler_init g_tbb_threads(tbb::task_scheduler_init::deferred);
class TBBAffinity: public tbb::task_scheduler_observer
{
public:
tbb::atomic<int> threadCount;
void on_scheduler_entry( bool ) {
++threadCount;
setAffinity(TaskScheduler::threadIndex()); // FIXME: use threadCount?
}
void on_scheduler_exit( bool ) {
--threadCount;
}
public:
TBBAffinity() { threadCount = 0; }
int get_concurrency() { return threadCount; }
void set_concurrency(int i) { threadCount = i; }
} tbb_affinity;
size_t TaskScheduler::g_numThreads = 0;
void TaskScheduler::create(size_t numThreads, bool set_affinity)
{
/* first terminate threads in case we configured them */
if (g_tbb_threads_initialized) {
g_tbb_threads.terminate();
g_tbb_threads_initialized = false;
}
/* only set affinity if requested by the user */
if (set_affinity) {
tbb_affinity.set_concurrency(0);
tbb_affinity.observe(true);
}
/* now either keep default settings or configure number of threads */
if (numThreads == 0)
{
g_tbb_threads_initialized = false;
g_numThreads = tbb::task_scheduler_init::default_num_threads();
} else {
g_tbb_threads_initialized = true;
g_tbb_threads.initialize(int(numThreads));
g_numThreads = numThreads;
}
/* also start worker threads in affinity mode */
if (set_affinity) {
tbb::parallel_for(size_t(0), size_t(g_numThreads), size_t(1), [] ( size_t i ) {
while (tbb_affinity.threadCount != g_numThreads) {};
});
}
}
void TaskScheduler::destroy()
{
if (g_tbb_threads_initialized) {
g_tbb_threads.terminate();
g_tbb_threads_initialized = false;
}
}
}
<commit_msg>starting TBB threads if affinity got set<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "taskschedulertbb.h"
namespace embree
{
bool g_tbb_threads_initialized = false;
tbb::task_scheduler_init g_tbb_threads(tbb::task_scheduler_init::deferred);
class TBBAffinity: public tbb::task_scheduler_observer
{
public:
tbb::atomic<int> threadCount;
void on_scheduler_entry( bool ) {
++threadCount;
setAffinity(TaskScheduler::threadIndex()); // FIXME: use threadCount?
}
void on_scheduler_exit( bool ) {
--threadCount;
}
public:
TBBAffinity() { threadCount = 0; }
int get_concurrency() { return threadCount; }
void set_concurrency(int i) { threadCount = i; }
} tbb_affinity;
size_t TaskScheduler::g_numThreads = 0;
void TaskScheduler::create(size_t numThreads, bool set_affinity)
{
/* first terminate threads in case we configured them */
if (g_tbb_threads_initialized) {
g_tbb_threads.terminate();
g_tbb_threads_initialized = false;
}
/* only set affinity if requested by the user */
if (set_affinity) {
tbb_affinity.set_concurrency(0);
tbb_affinity.observe(true);
}
/* now either keep default settings or configure number of threads */
if (numThreads == 0)
{
g_tbb_threads_initialized = false;
g_numThreads = tbb::task_scheduler_init::default_num_threads();
} else {
g_tbb_threads_initialized = true;
g_tbb_threads.initialize(int(numThreads));
g_numThreads = numThreads;
}
/* also start worker threads in affinity mode */
if (set_affinity) {
tbb::parallel_for(size_t(0), size_t(g_numThreads), size_t(1), [] ( size_t i ) {
while (tbb_affinity.threadCount != g_numThreads) {
yield();
};
});
}
}
void TaskScheduler::destroy()
{
if (g_tbb_threads_initialized) {
g_tbb_threads.terminate();
g_tbb_threads_initialized = false;
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkTransformation.h>
char *target_name = NULL;
char *dofin_name = NULL;
char *dofout_name = NULL;
irtkGreyImage *target;
irtkMultiLevelFreeFormTransformation *mffd;
#ifdef WIN32
#include <time.h>
#include <windows.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
struct timezone
{
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag;
if (NULL != tv)
{
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tmpres /= 10; /*convert into microseconds*/
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
#else
#include <sys/time.h>
#endif
#include <nr.h>
#include <nrutil.h>
void usage()
{
cerr << "Usage: ffdadd [target] [dofin] [dofout] [options]" << endl;
cerr << "where the following options are supported:\n" << endl;
cerr << "<-Tx1 value> Region of interest in target image" << endl;
cerr << "<-Ty1 value> Region of interest in target image" << endl;
cerr << "<-Tz1 value> Region of interest in target image" << endl;
cerr << "<-Tt1 value> Region of interest in target image" << endl;
cerr << "<-Tx2 value> Region of interest in target image" << endl;
cerr << "<-Ty2 value> Region of interest in target image" << endl;
cerr << "<-Tz2 value> Region of interest in target image" << endl;
cerr << "<-Tt2 value> Region of interest in target image" << endl;
cerr << "<-dx value> Control point spacing for x" << endl;
cerr << "<-dy value> Control point spacing for y" << endl;
cerr << "<-dz value> Control point spacing for z" << endl;
cerr << "<-dt value> Control point spacing for t" << endl;
cerr << "<-ds value> Control point spacing for x, y, z and t" << endl;
cerr << "<-3D> Generate 3D FFD (default)" << endl;
cerr << "<-4D> Generate 4D FFD" << endl;
cout << endl;
exit(1);
}
int main(int argc, char **argv)
{
double dx, dy, dz, dt, noise;
int i1, j1, k1, l1, i2, j2, k2, l2, ok, fluid, ffd4D;
// Check command line
if (argc < 4) {
usage();
}
// Parse file names
target_name = argv[1];
argc--;
argv++;
dofin_name = argv[1];
argc--;
argv++;
dofout_name = argv[1];
argc--;
argv++;
// Read image image
cout << "Reading image ... "; cout.flush();
target = new irtkGreyImage;
target->Read(target_name);
cout << "done" << endl;
// Fix ROI
i1 = 0;
j1 = 0;
k1 = 0;
l1 = 0;
i2 = target->GetX();
j2 = target->GetY();
k2 = target->GetZ();
l2 = target->GetT();
// Fix spacing
dx = 20;
dy = 20;
dz = 20;
dt = 20;
// No 4D FFD
ffd4D = false;
// No fluid
fluid = false;
// Don't add noise
noise = 0;
// Parse remaining parameters
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-Tx1") == 0)) {
argc--;
argv++;
i1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tx2") == 0)) {
argc--;
argv++;
i2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ty1") == 0)) {
argc--;
argv++;
j1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ty2") == 0)) {
argc--;
argv++;
j2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tz1") == 0)) {
argc--;
argv++;
k1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tz2") == 0)) {
argc--;
argv++;
k2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tt1") == 0)) {
argc--;
argv++;
l1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tt2") == 0)) {
argc--;
argv++;
l2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dx") == 0)) {
argc--;
argv++;
dx = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dy") == 0)) {
argc--;
argv++;
dy = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dz") == 0)) {
argc--;
argv++;
dz = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dt") == 0)) {
argc--;
argv++;
dt = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-ds") == 0)) {
argc--;
argv++;
dx = atof(argv[1]);
dy = atof(argv[1]);
dz = atof(argv[1]);
dt = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-fluid") == 0)) {
argc--;
argv++;
fluid = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-3D") == 0)) {
argc--;
argv++;
ffd4D = false;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-4D") == 0)) {
argc--;
argv++;
ffd4D = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-noise") == 0)) {
argc--;
argv++;
noise = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Read transformation
if (fluid == true) {
mffd = new irtkFluidFreeFormTransformation;
} else {
mffd = new irtkMultiLevelFreeFormTransformation;
}
mffd->irtkTransformation::Read(dofin_name);
// If there is an region of interest, use it
if ((i1 != 0) || (i2 != target->GetX()) ||
(j1 != 0) || (j2 != target->GetY()) ||
(k1 != 0) || (k2 != target->GetZ()) ||
(l1 != 0) || (l2 != target->GetT())) {
*target = target->GetRegion(i1, j1, k1, l1, i2, j2, k2, l2);
}
if (ffd4D == false) {
// Create free-form transformation
irtkBSplineFreeFormTransformation3D *affd = new irtkBSplineFreeFormTransformation(*target, dx, dy, dz);
// Add noise to the transformation
if (noise > 0) {
int i;
long temp;
timeval tv;
gettimeofday(&tv, NULL);
temp = -tv.tv_usec;
for (i = 0; i < affd->NumberOfDOFs(); i++) affd->Put(i, noise*gasdev(&temp));
}
// Add and write file
mffd->PushLocalTransformation(affd);
} else {
// Create free-form transformation
irtkBSplineFreeFormTransformation4D *affd = new irtkBSplineFreeFormTransformation4D(*target, dx, dy, dz, dt);
// Add noise to the transformation
if (noise > 0) {
int i;
long temp;
timeval tv;
gettimeofday(&tv, NULL);
temp = -tv.tv_usec;
for (i = 0; i < affd->NumberOfDOFs(); i++) affd->Put(i, noise*gasdev(&temp));
}
// Add and write file
mffd->PushLocalTransformation(affd);
}
mffd->irtkTransformation::Write(dofout_name);
}
<commit_msg>Removed recipes gasdev function from ffdadd.cc<commit_after>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkTransformation.h>
char *target_name = NULL;
char *dofin_name = NULL;
char *dofout_name = NULL;
irtkGreyImage *target;
irtkMultiLevelFreeFormTransformation *mffd;
#ifdef WIN32
#include <time.h>
#include <windows.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
struct timezone
{
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag;
if (NULL != tv)
{
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tmpres /= 10; /*convert into microseconds*/
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
#else
#include <sys/time.h>
#endif
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
void usage()
{
cerr << "Usage: ffdadd [target] [dofin] [dofout] [options]" << endl;
cerr << "where the following options are supported:\n" << endl;
cerr << "<-Tx1 value> Region of interest in target image" << endl;
cerr << "<-Ty1 value> Region of interest in target image" << endl;
cerr << "<-Tz1 value> Region of interest in target image" << endl;
cerr << "<-Tt1 value> Region of interest in target image" << endl;
cerr << "<-Tx2 value> Region of interest in target image" << endl;
cerr << "<-Ty2 value> Region of interest in target image" << endl;
cerr << "<-Tz2 value> Region of interest in target image" << endl;
cerr << "<-Tt2 value> Region of interest in target image" << endl;
cerr << "<-dx value> Control point spacing for x" << endl;
cerr << "<-dy value> Control point spacing for y" << endl;
cerr << "<-dz value> Control point spacing for z" << endl;
cerr << "<-dt value> Control point spacing for t" << endl;
cerr << "<-ds value> Control point spacing for x, y, z and t" << endl;
cerr << "<-3D> Generate 3D FFD (default)" << endl;
cerr << "<-4D> Generate 4D FFD" << endl;
cout << endl;
exit(1);
}
int main(int argc, char **argv)
{
double dx, dy, dz, dt, noise;
int i1, j1, k1, l1, i2, j2, k2, l2, ok, fluid, ffd4D;
// Check command line
if (argc < 4) {
usage();
}
// Parse file names
target_name = argv[1];
argc--;
argv++;
dofin_name = argv[1];
argc--;
argv++;
dofout_name = argv[1];
argc--;
argv++;
// Read image image
cout << "Reading image ... "; cout.flush();
target = new irtkGreyImage;
target->Read(target_name);
cout << "done" << endl;
// Fix ROI
i1 = 0;
j1 = 0;
k1 = 0;
l1 = 0;
i2 = target->GetX();
j2 = target->GetY();
k2 = target->GetZ();
l2 = target->GetT();
// Fix spacing
dx = 20;
dy = 20;
dz = 20;
dt = 20;
// No 4D FFD
ffd4D = false;
// No fluid
fluid = false;
// Don't add noise
noise = 0;
// Parse remaining parameters
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-Tx1") == 0)) {
argc--;
argv++;
i1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tx2") == 0)) {
argc--;
argv++;
i2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ty1") == 0)) {
argc--;
argv++;
j1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ty2") == 0)) {
argc--;
argv++;
j2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tz1") == 0)) {
argc--;
argv++;
k1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tz2") == 0)) {
argc--;
argv++;
k2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tt1") == 0)) {
argc--;
argv++;
l1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tt2") == 0)) {
argc--;
argv++;
l2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dx") == 0)) {
argc--;
argv++;
dx = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dy") == 0)) {
argc--;
argv++;
dy = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dz") == 0)) {
argc--;
argv++;
dz = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-dt") == 0)) {
argc--;
argv++;
dt = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-ds") == 0)) {
argc--;
argv++;
dx = atof(argv[1]);
dy = atof(argv[1]);
dz = atof(argv[1]);
dt = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-fluid") == 0)) {
argc--;
argv++;
fluid = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-3D") == 0)) {
argc--;
argv++;
ffd4D = false;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-4D") == 0)) {
argc--;
argv++;
ffd4D = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-noise") == 0)) {
argc--;
argv++;
noise = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Read transformation
if (fluid == true) {
mffd = new irtkFluidFreeFormTransformation;
} else {
mffd = new irtkMultiLevelFreeFormTransformation;
}
mffd->irtkTransformation::Read(dofin_name);
// If there is an region of interest, use it
if ((i1 != 0) || (i2 != target->GetX()) ||
(j1 != 0) || (j2 != target->GetY()) ||
(k1 != 0) || (k2 != target->GetZ()) ||
(l1 != 0) || (l2 != target->GetT())) {
*target = target->GetRegion(i1, j1, k1, l1, i2, j2, k2, l2);
}
if (ffd4D == false) {
// Create free-form transformation
irtkBSplineFreeFormTransformation3D *affd = new irtkBSplineFreeFormTransformation(*target, dx, dy, dz);
// Add noise to the transformation
if (noise > 0) {
int i;
long temp;
timeval tv;
gettimeofday(&tv, NULL);
temp = -tv.tv_usec;
boost::mt19937 rng;
rng.seed(temp);
boost::normal_distribution<> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&,
boost::normal_distribution<> > var_nor(rng, nd);
for (i = 0; i < affd->NumberOfDOFs(); i++) affd->Put(i, noise*var_nor());
}
// Add and write file
mffd->PushLocalTransformation(affd);
} else {
// Create free-form transformation
irtkBSplineFreeFormTransformation4D *affd = new irtkBSplineFreeFormTransformation4D(*target, dx, dy, dz, dt);
// Add noise to the transformation
if (noise > 0) {
int i;
long temp;
timeval tv;
gettimeofday(&tv, NULL);
temp = -tv.tv_usec;
boost::mt19937 rng;
rng.seed(temp);
boost::normal_distribution<> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&,
boost::normal_distribution<> > var_nor(rng, nd);
for (i = 0; i < affd->NumberOfDOFs(); i++) affd->Put(i, noise*var_nor());
}
// Add and write file
mffd->PushLocalTransformation(affd);
}
mffd->irtkTransformation::Write(dofout_name);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.
#include <thread>
#include <windows.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/self_path.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/error.hpp>
#include "../cerberus/plugin.hpp"
#include "radar.hpp"
#include "root_window.hpp"
namespace
{
std::size_t g_on_frame_callback_id{};
std::unique_ptr<std::thread> g_window_thread{};
}
extern "C" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR
LoadPlugin(hadesmem::cerberus::PluginInterface* cerberus)
HADESMEM_DETAIL_NOEXCEPT
{
try
{
HADESMEM_DETAIL_TRACE_A("Initializing.");
// Using a wrapper lambda to work around a GCC link error on x86
auto const window_thread = []()
{
WindowThread(
hadesmem::detail::GetHandleToSelf(), nullptr, nullptr, SW_SHOW);
};
g_window_thread.reset(new std::thread(window_thread));
g_window_thread->detach();
InitializeRadar(cerberus);
return 0;
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
return 1;
}
}
extern "C" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR
UnloadPlugin(hadesmem::cerberus::PluginInterface* cerberus)
HADESMEM_DETAIL_NOEXCEPT
{
try
{
HADESMEM_DETAIL_TRACE_A("Cleaning up.");
CleanupRadar(cerberus);
auto const hwnd = GetWindowHandle();
if (hwnd && ::SendMessageW(hwnd, WM_CLOSE, 0, 0))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
hadesmem::Error{} << hadesmem::ErrorString{"SendMessageW failed."}
<< hadesmem::ErrorCodeWinLast{last_error});
}
auto const& thread = GetThreadHandle();
if (thread.IsValid())
{
DWORD const wait_result =
::WaitForSingleObject(thread.GetHandle(), INFINITE);
if (wait_result != WAIT_OBJECT_0)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
hadesmem::Error{}
<< hadesmem::ErrorString{"WaitForSingleObject failed."}
<< hadesmem::ErrorCodeWinLast{last_error}
<< hadesmem::ErrorCodeWinOther(wait_result));
}
}
return 0;
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
return 1;
}
}
BOOL WINAPI
DllMain(HINSTANCE /*instance*/, DWORD /*reason*/, LPVOID /*reserved*/)
HADESMEM_DETAIL_NOEXCEPT
{
return TRUE;
}
<commit_msg>* [Cerberus] Remove dead variable. * [Cerberus] Fix bug.<commit_after>// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.
#include <thread>
#include <windows.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/self_path.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/error.hpp>
#include "../cerberus/plugin.hpp"
#include "radar.hpp"
#include "root_window.hpp"
namespace
{
std::unique_ptr<std::thread> g_window_thread{};
}
extern "C" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR
LoadPlugin(hadesmem::cerberus::PluginInterface* cerberus)
HADESMEM_DETAIL_NOEXCEPT
{
try
{
HADESMEM_DETAIL_TRACE_A("Initializing.");
// Preemptively fix a potential order of destruction issue by ensuring this
// is used very early.
auto const& thread = GetThreadHandle();
(void)thread;
// Using a wrapper lambda to work around a GCC link error on x86
auto const window_thread = []()
{
WindowThread(
hadesmem::detail::GetHandleToSelf(), nullptr, nullptr, SW_SHOW);
};
g_window_thread.reset(new std::thread(window_thread));
g_window_thread->detach();
InitializeRadar(cerberus);
return 0;
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
return 1;
}
}
extern "C" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR
UnloadPlugin(hadesmem::cerberus::PluginInterface* cerberus)
HADESMEM_DETAIL_NOEXCEPT
{
try
{
HADESMEM_DETAIL_TRACE_A("Cleaning up.");
CleanupRadar(cerberus);
auto const hwnd = GetWindowHandle();
if (hwnd && ::SendMessageW(hwnd, WM_CLOSE, 0, 0))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
hadesmem::Error{} << hadesmem::ErrorString{"SendMessageW failed."}
<< hadesmem::ErrorCodeWinLast{last_error});
}
auto const& thread = GetThreadHandle();
if (thread.IsValid())
{
DWORD const wait_result =
::WaitForSingleObject(thread.GetHandle(), INFINITE);
if (wait_result != WAIT_OBJECT_0)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
hadesmem::Error{}
<< hadesmem::ErrorString{"WaitForSingleObject failed."}
<< hadesmem::ErrorCodeWinLast{last_error}
<< hadesmem::ErrorCodeWinOther(wait_result));
}
}
return 0;
}
catch (...)
{
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
return 1;
}
}
BOOL WINAPI
DllMain(HINSTANCE /*instance*/, DWORD /*reason*/, LPVOID /*reserved*/)
HADESMEM_DETAIL_NOEXCEPT
{
return TRUE;
}
<|endoftext|> |
<commit_before>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "sysadm-client.h"
#include <QSslConfiguration>
#include <QJsonArray>
// === PUBLIC ===
sysadm_client::sysadm_client(){
SOCKET = new QWebSocket("sysadm-client", QWebSocketProtocol::VersionLatest, this);
SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
QList<QSslError> ignored; ignored << QSslError(QSslError::SelfSignedCertificate) << QSslError(QSslError::HostNameMismatch);
SOCKET->ignoreSslErrors(ignored);
//SOCKET->ignoreSslErrors();
//use the new Qt5 connection syntax for compile time checks that connections are valid
connect(SOCKET, &QWebSocket::connected, this, &sysadm_client::socketConnected);
connect(SOCKET, &QWebSocket::disconnected, this, &sysadm_client::socketClosed);
connect(SOCKET, &QWebSocket::textMessageReceived, this, &sysadm_client::socketMessage);
//Old connect syntax for the "error" signal (special note about issues in the docs)
connect(SOCKET, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)) );
connect(SOCKET, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(socketSslErrors(const QList<QSslError>&)) );
keepActive=false; //not setup yet
settings = new QSettings("PC-BSD","sysadm-client", this);
}
sysadm_client::~sysadm_client(){
}
// Overall Connection functions (start/stop)
void sysadm_client::openConnection(QString user, QString pass, QString hostIP){
cuser = user; cpass = pass; chost = hostIP;
qDebug() << "Client: Setup connection:" << user << pass << hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString authkey, QString hostIP){
cauthkey = authkey; chost = hostIP;
setupSocket();
}
void sysadm_client::closeConnection(){
keepActive = false;
//de-authorize the current auth token
cauthkey.clear();
performAuth();
//Now close the connection
SOCKET->close(QWebSocketProtocol::CloseCodeNormal, "sysadm-client closed");
}
// Connection Hosts Database Access
QStringList sysadm_client::knownHosts(){
//Returns: <IP>::::<Name>
QStringList hosts =settings->value("knownhosts",QStringList()).toStringList();
for(int i=0; i<hosts.length(); i++){
hosts[i].append("::::" + settings->value("hostnames/"+hosts[i],"").toString() );
}
return hosts;
}
void sysadm_client::saveHost(QString IP, QString name){
QStringList hosts = settings->value("knownhosts",QStringList()).toStringList();
hosts << IP;
hosts.removeDuplicates();
settings->setValue("knownhosts",hosts);
settings->setValue("hostnames/"+IP,name);
}
void sysadm_client::removeHost(QString IP){
QStringList hosts = settings->value("knownhosts",QStringList()).toStringList();
hosts.removeAll(IP);
settings->setValue("knownhosts",hosts);
settings->remove("hostnames/"+IP);
}
// Register for Event Notifications (no notifications by default)
void sysadm_client::registerForEvents(EVENT_TYPE event, bool receive){
bool set = events.contains(event);
if( set && receive){ return; } //already registered
else if(!set && !receive){ return; } //already unregistered
else if(set){ events << event; }
else{ events.removeAll(event); }
//Since this can be setup before the socket is connected - see if we can send this message right away
if(SOCKET->isValid()){
sendEventSubscription(event, receive);
}
}
// Messages which are still pending a response
QStringList sysadm_client::pending(){ return PENDING; } //returns only the "id" for each
// Fetch a message from the recent cache
QJsonObject sysadm_client::cachedRequest(QString id){
if(SENT.contains(id)){ return SENT.value(id); }
else{ return QJsonObject(); }
}
QJsonValue sysadm_client::cachedReply(QString id){
if(BACK.contains(id)){ return BACK.value(id); }
else{ return QJsonObject(); }
}
// === PRIVATE ===
//Functions to do the initial socket setup
void sysadm_client::setupSocket(){
qDebug() << "Setup Socket:" << SOCKET->isValid();
if(SOCKET->isValid()){ return; }
//uses chost for setup
// - assemble the host URL
if(chost.contains("://")){ chost = chost.section("://",1,1); } //Chop off the custom http/ftp/other header (always need "wss://")
QString url = "wss://"+chost;
bool hasport = false;
url.section(":",-1).toInt(&hasport); //check if the last piece of the url is a valid number
//Could add a check for a valid port number as well - but that is a bit overkill right now
if(!hasport){ url.append(":"+QString::number(WSPORTDEFAULT)); }
qDebug() << " - URL:" << url;
SOCKET->open(QUrl(url));
}
void sysadm_client::performAuth(QString user, QString pass){
//uses cauthkey if empty inputs
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
bool noauth = false;
if(user.isEmpty() && pass.isEmpty()){
if(cauthkey.isEmpty()){
//Nothing to authenticate - de-auth the connection instead
obj.insert("name","auth_clear");
obj.insert("args","");
noauth = true;
}else{
//Saved token authentication
obj.insert("name","auth_token");
QJsonObject arg;
arg.insert("token",cauthkey);
obj.insert("args", arg);
}
}else{
//User/password authentication
obj.insert("name","auth");
QJsonObject arg;
arg.insert("username",user);
arg.insert("password",pass);
obj.insert("args", arg);
}
sendSocketMessage(obj);
if(noauth){ emit clientUnauthorized(); }
}
//Communication subroutines with the server (block until message comes back)
void sysadm_client::sendEventSubscription(EVENT_TYPE event, bool subscribe){
QJsonObject obj;
obj.insert("namespace","events");
obj.insert("name", subscribe ? "subscribe" : "unsubscribe");
obj.insert("id", "sysadm-client-event-auto");
QString arg;
if(event == DISPATCHER){ arg = "dispatcher"; }
obj.insert("args", arg);
sendSocketMessage(obj);
}
void sysadm_client::sendSocketMessage(QJsonObject msg){
QJsonDocument doc(msg);
SOCKET->sendTextMessage(doc.toJson(QJsonDocument::Compact));
}
//Simplification functions
QJsonObject sysadm_client::convertServerReply(QString reply){
QJsonDocument doc = QJsonDocument::fromJson(reply.toUtf8());
if(doc.isObject()){ return doc.object(); }
else{ return QJsonObject(); }
}
// === PUBLIC SLOTS ===
// Communications with server (send message, get response via signal later)
void sysadm_client::communicate(QString ID, QString namesp, QString name, QJsonValue args){
//Overloaded function for a request which needs assembly
QJsonObject obj;
obj.insert("namespace",namesp);
obj.insert("name", name);
obj.insert("id", ID);
obj.insert("args", args);
communicate(QList<QJsonObject>() << obj);
}
void sysadm_client::communicate(QJsonObject request){
//Overloaded function for a single JSON request
communicate(QList<QJsonObject>() << request);
}
void sysadm_client::communicate(QList<QJsonObject> requests){
for(int i=0; i<requests.length(); i++){
QString ID = requests[i].value("id").toString();
if(ID.isEmpty()){
qDebug() << "Malformed JSON request:" << requests[i];
continue;
}
//Save this into the cache
SENT.insert(ID, requests[i]);
if(BACK.contains(ID)){ BACK.remove(ID); }
PENDING << ID;
//Now send off the message
if(SOCKET->isValid()){ sendSocketMessage(requests[i]); }
}
}
// === PRIVATE SLOTS ===
//Socket signal/slot connections
void sysadm_client::socketConnected(){ //Signal: connected()
keepActive = true; //got a valid connection - try to keep this open automatically
num_fail = 0; //reset fail counter - got a valid connection
emit clientConnected();
performAuth(cuser, cpass);
cuser.clear(); cpass.clear(); //just to ensure no trace left in memory
}
void sysadm_client::socketClosed(){ //Signal: disconnected()
if(keepActive && num_fail < FAIL_MAX){
//Socket closed due to timeout?
// Go ahead and re-open it if possible with the last-used settings/auth
num_fail++;
setupSocket();
}else{
num_fail = 0; //reset back to nothing
emit clientDisconnected();
//Server cache is now invalid - completely lost connection
SENT.clear(); BACK.clear(); PENDING.clear();
}
}
void sysadm_client::socketSslErrors(const QList<QSslError>&errlist){ //Signal: sslErrors()
qWarning() << "SSL Errors Detected:" << errlist.length();
//SOCKET->ignoreSslErrors(QList<QSslError>() << QSslError(QSslError::SelfSignedCertificate) << QSslError(QSslError::HostNameMismatch) );
QList<QSslError> ignored;
for(int i=0; i< errlist.length(); i++){
if(errlist[i].error()==QSslError::SelfSignedCertificate || errlist[i].error()==QSslError::HostNameMismatch ){
qDebug() << " - (IGNORED) " << errlist[i].errorString();
ignored << errlist[i];
}else{
qWarning() << " - " << errlist[i].errorString();
}
}
if(!ignored.isEmpty()){
qDebug() << "Ignoring errors:";
SOCKET->ignoreSslErrors(ignored);
}
}
void sysadm_client::socketError(QAbstractSocket::SocketError err){ //Signal:: error()
qWarning() << "Socket Error detected:" << err;
if(err==13){qWarning() << " - SSL Handshake Failed"; }
qWarning() << " - Final websocket error:" << SOCKET->errorString();
}
//void sysadm_client::socketProxyAuthRequired(const QNetworkProxy &proxy, QAuthenticator *auth); //Signal: proxyAuthenticationRequired()
// - Main message input parsing
void sysadm_client::socketMessage(QString msg){ //Signal: textMessageReceived()
qDebug() << "New Reply From Server:" << msg;
//Convert this into a JSON object
QJsonObject obj = convertServerReply(msg);
QString ID = obj.value("id").toString();
QString namesp = obj.value("namespace").toString();
QString name = obj.value("name").toString();
//Still need to add some parsing to the return message
if(ID=="sysadm-client-auth-auto"){
//Reply to automated auth system
if(name=="error"){
emit clientUnauthorized();
}else{
QJsonValue args = obj.value("args");
if(args.isArray()){
cauthkey = args.toArray().first().toString();
emit clientAuthorized();
//Now automatically re-subscribe to events as needed
for(int i=0; i<events.length(); i++){ sendEventSubscription(events[i]); }
}
}
}else if(ID=="sysadm-client-event-auto"){
//Reply to automated event subscription - don't need to save this
}else if(namesp=="events"){
//Event notification - not tied to any particular request
if(name=="dispatcher"){ emit DispatcherEvent(obj.value("args")); }
}else{
//Now save this message into the cache for use later (if not an auth reply)
if(!ID.isEmpty()){
PENDING.removeAll(ID);
BACK.insert(ID, obj);
}
emit newReply(ID, name, namesp, obj.value("args"));
}
}
<commit_msg>Get the SSL stuff sorted out with a workaround for the ignored errors settings. Now the client can successfully connect to the server.<commit_after>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "sysadm-client.h"
#include <QSslConfiguration>
#include <QJsonArray>
#include <QTimer>
// === PUBLIC ===
sysadm_client::sysadm_client(){
SOCKET = new QWebSocket("sysadm-client", QWebSocketProtocol::VersionLatest, this);
SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
//SOCKET->ignoreSslErrors();
//use the new Qt5 connection syntax for compile time checks that connections are valid
connect(SOCKET, &QWebSocket::connected, this, &sysadm_client::socketConnected);
connect(SOCKET, &QWebSocket::disconnected, this, &sysadm_client::socketClosed);
connect(SOCKET, &QWebSocket::textMessageReceived, this, &sysadm_client::socketMessage);
//Old connect syntax for the "error" signal (special note about issues in the docs)
connect(SOCKET, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)) );
connect(SOCKET, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(socketSslErrors(const QList<QSslError>&)) );
keepActive=false; //not setup yet
settings = new QSettings("PC-BSD","sysadm-client", this);
}
sysadm_client::~sysadm_client(){
}
// Overall Connection functions (start/stop)
void sysadm_client::openConnection(QString user, QString pass, QString hostIP){
cuser = user; cpass = pass; chost = hostIP;
qDebug() << "Client: Setup connection:" << user << pass << hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString authkey, QString hostIP){
cauthkey = authkey; chost = hostIP;
setupSocket();
}
void sysadm_client::closeConnection(){
keepActive = false;
//de-authorize the current auth token
cauthkey.clear();
performAuth();
//Now close the connection
SOCKET->close(QWebSocketProtocol::CloseCodeNormal, "sysadm-client closed");
}
// Connection Hosts Database Access
QStringList sysadm_client::knownHosts(){
//Returns: <IP>::::<Name>
QStringList hosts =settings->value("knownhosts",QStringList()).toStringList();
for(int i=0; i<hosts.length(); i++){
hosts[i].append("::::" + settings->value("hostnames/"+hosts[i],"").toString() );
}
return hosts;
}
void sysadm_client::saveHost(QString IP, QString name){
QStringList hosts = settings->value("knownhosts",QStringList()).toStringList();
hosts << IP;
hosts.removeDuplicates();
settings->setValue("knownhosts",hosts);
settings->setValue("hostnames/"+IP,name);
}
void sysadm_client::removeHost(QString IP){
QStringList hosts = settings->value("knownhosts",QStringList()).toStringList();
hosts.removeAll(IP);
settings->setValue("knownhosts",hosts);
settings->remove("hostnames/"+IP);
}
// Register for Event Notifications (no notifications by default)
void sysadm_client::registerForEvents(EVENT_TYPE event, bool receive){
bool set = events.contains(event);
if( set && receive){ return; } //already registered
else if(!set && !receive){ return; } //already unregistered
else if(set){ events << event; }
else{ events.removeAll(event); }
//Since this can be setup before the socket is connected - see if we can send this message right away
if(SOCKET->isValid()){
sendEventSubscription(event, receive);
}
}
// Messages which are still pending a response
QStringList sysadm_client::pending(){ return PENDING; } //returns only the "id" for each
// Fetch a message from the recent cache
QJsonObject sysadm_client::cachedRequest(QString id){
if(SENT.contains(id)){ return SENT.value(id); }
else{ return QJsonObject(); }
}
QJsonValue sysadm_client::cachedReply(QString id){
if(BACK.contains(id)){ return BACK.value(id); }
else{ return QJsonObject(); }
}
// === PRIVATE ===
//Functions to do the initial socket setup
void sysadm_client::setupSocket(){
qDebug() << "Setup Socket:" << SOCKET->isValid();
if(SOCKET->isValid()){ return; }
//uses chost for setup
// - assemble the host URL
if(chost.contains("://")){ chost = chost.section("://",1,1); } //Chop off the custom http/ftp/other header (always need "wss://")
QString url = "wss://"+chost;
bool hasport = false;
url.section(":",-1).toInt(&hasport); //check if the last piece of the url is a valid number
//Could add a check for a valid port number as well - but that is a bit overkill right now
if(!hasport){ url.append(":"+QString::number(WSPORTDEFAULT)); }
qDebug() << " - URL:" << url;
QTimer::singleShot(0,SOCKET, SLOT(ignoreSslErrors()) );
SOCKET->open(QUrl(url));
//QList<QSslError> ignored; ignored << QSslError(QSslError::SelfSignedCertificate) << QSslError(QSslError::HostNameMismatch);
//SOCKET->ignoreSslErrors(ignored);
}
void sysadm_client::performAuth(QString user, QString pass){
//uses cauthkey if empty inputs
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
bool noauth = false;
if(user.isEmpty() && pass.isEmpty()){
if(cauthkey.isEmpty()){
//Nothing to authenticate - de-auth the connection instead
obj.insert("name","auth_clear");
obj.insert("args","");
noauth = true;
}else{
//Saved token authentication
obj.insert("name","auth_token");
QJsonObject arg;
arg.insert("token",cauthkey);
obj.insert("args", arg);
}
}else{
//User/password authentication
obj.insert("name","auth");
QJsonObject arg;
arg.insert("username",user);
arg.insert("password",pass);
obj.insert("args", arg);
}
sendSocketMessage(obj);
if(noauth){ emit clientUnauthorized(); }
}
//Communication subroutines with the server (block until message comes back)
void sysadm_client::sendEventSubscription(EVENT_TYPE event, bool subscribe){
QJsonObject obj;
obj.insert("namespace","events");
obj.insert("name", subscribe ? "subscribe" : "unsubscribe");
obj.insert("id", "sysadm-client-event-auto");
QString arg;
if(event == DISPATCHER){ arg = "dispatcher"; }
obj.insert("args", arg);
sendSocketMessage(obj);
}
void sysadm_client::sendSocketMessage(QJsonObject msg){
QJsonDocument doc(msg);
SOCKET->sendTextMessage(doc.toJson(QJsonDocument::Compact));
}
//Simplification functions
QJsonObject sysadm_client::convertServerReply(QString reply){
QJsonDocument doc = QJsonDocument::fromJson(reply.toUtf8());
if(doc.isObject()){ return doc.object(); }
else{ return QJsonObject(); }
}
// === PUBLIC SLOTS ===
// Communications with server (send message, get response via signal later)
void sysadm_client::communicate(QString ID, QString namesp, QString name, QJsonValue args){
//Overloaded function for a request which needs assembly
QJsonObject obj;
obj.insert("namespace",namesp);
obj.insert("name", name);
obj.insert("id", ID);
obj.insert("args", args);
communicate(QList<QJsonObject>() << obj);
}
void sysadm_client::communicate(QJsonObject request){
//Overloaded function for a single JSON request
communicate(QList<QJsonObject>() << request);
}
void sysadm_client::communicate(QList<QJsonObject> requests){
for(int i=0; i<requests.length(); i++){
QString ID = requests[i].value("id").toString();
if(ID.isEmpty()){
qDebug() << "Malformed JSON request:" << requests[i];
continue;
}
//Save this into the cache
SENT.insert(ID, requests[i]);
if(BACK.contains(ID)){ BACK.remove(ID); }
PENDING << ID;
//Now send off the message
if(SOCKET->isValid()){ sendSocketMessage(requests[i]); }
}
}
// === PRIVATE SLOTS ===
//Socket signal/slot connections
void sysadm_client::socketConnected(){ //Signal: connected()
keepActive = true; //got a valid connection - try to keep this open automatically
num_fail = 0; //reset fail counter - got a valid connection
emit clientConnected();
performAuth(cuser, cpass);
cuser.clear(); cpass.clear(); //just to ensure no trace left in memory
}
void sysadm_client::socketClosed(){ //Signal: disconnected()
if(keepActive && num_fail < FAIL_MAX){
//Socket closed due to timeout?
// Go ahead and re-open it if possible with the last-used settings/auth
num_fail++;
setupSocket();
}else{
num_fail = 0; //reset back to nothing
emit clientDisconnected();
//Server cache is now invalid - completely lost connection
SENT.clear(); BACK.clear(); PENDING.clear();
}
}
void sysadm_client::socketSslErrors(const QList<QSslError>&errlist){ //Signal: sslErrors()
qWarning() << "SSL Errors Detected:" << errlist.length();
QList<QSslError> ignored;
for(int i=0; i< errlist.length(); i++){
if(errlist[i].error()==QSslError::SelfSignedCertificate || errlist[i].error()==QSslError::HostNameMismatch ){
qDebug() << " - (IGNORED) " << errlist[i].errorString();
ignored << errlist[i];
}else{
qWarning() << " - " << errlist[i].errorString();
}
}
if(ignored.length() != errlist.length()){
SOCKET->close(); //SSL errors - close the connection
}
}
void sysadm_client::socketError(QAbstractSocket::SocketError err){ //Signal:: error()
qWarning() << "Socket Error detected:" << err;
if(err==QAbstractSocket::SslHandshakeFailedError){qWarning() << " - SSL Handshake Failed"; }
qWarning() << " - Final websocket error:" << SOCKET->errorString();
}
//void sysadm_client::socketProxyAuthRequired(const QNetworkProxy &proxy, QAuthenticator *auth); //Signal: proxyAuthenticationRequired()
// - Main message input parsing
void sysadm_client::socketMessage(QString msg){ //Signal: textMessageReceived()
qDebug() << "New Reply From Server:" << msg;
//Convert this into a JSON object
QJsonObject obj = convertServerReply(msg);
QString ID = obj.value("id").toString();
QString namesp = obj.value("namespace").toString();
QString name = obj.value("name").toString();
//Still need to add some parsing to the return message
if(ID=="sysadm-client-auth-auto"){
//Reply to automated auth system
if(name=="error"){
emit clientUnauthorized();
}else{
QJsonValue args = obj.value("args");
if(args.isArray()){
cauthkey = args.toArray().first().toString();
emit clientAuthorized();
//Now automatically re-subscribe to events as needed
for(int i=0; i<events.length(); i++){ sendEventSubscription(events[i]); }
}
}
}else if(ID=="sysadm-client-event-auto"){
//Reply to automated event subscription - don't need to save this
}else if(namesp=="events"){
//Event notification - not tied to any particular request
if(name=="dispatcher"){ emit DispatcherEvent(obj.value("args")); }
}else{
//Now save this message into the cache for use later (if not an auth reply)
if(!ID.isEmpty()){
PENDING.removeAll(ID);
BACK.insert(ID, obj);
}
emit newReply(ID, name, namesp, obj.value("args"));
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// rule_test.cpp
//
// Identification: test/optimizer/rule_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#define private public
#include "optimizer/operator_expression.h"
#include "optimizer/operators.h"
#include "optimizer/optimizer.h"
#include "optimizer/rule.h"
#include "optimizer/rule_impls.h"
#include "catalog/catalog.h"
#include "common/logger.h"
#include "common/statement.h"
#include "executor/create_executor.h"
#include "executor/delete_executor.h"
#include "executor/insert_executor.h"
#include "executor/plan_executor.h"
#include "executor/update_executor.h"
#include "optimizer/simple_optimizer.h"
#include "parser/parser.h"
#include "planner/create_plan.h"
#include "planner/delete_plan.h"
#include "planner/insert_plan.h"
#include "planner/update_plan.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Binding Tests
//===--------------------------------------------------------------------===//
using namespace optimizer;
class RuleTests : public PelotonTest {};
TEST_F(RuleTests, SimpleRuleApplyTest) {
// Build op plan node to match rule
auto left_get = std::make_shared<OperatorExpression>(LogicalGet::make(0));
auto right_get = std::make_shared<OperatorExpression>(LogicalGet::make(0));
auto val = type::ValueFactory::GetBooleanValue(true);
auto join = std::make_shared<OperatorExpression>(LogicalInnerJoin::make());
join->PushChild(left_get);
join->PushChild(right_get);
// Setup rule
InnerJoinCommutativity rule;
EXPECT_TRUE(rule.Check(join));
std::vector<std::shared_ptr<OperatorExpression>> outputs;
rule.Transform(join, outputs);
EXPECT_EQ(outputs.size(), 1);
}
// Test whether update stament will use index scan plan
TEST_F(RuleTests, UpdateDelWithIndexScanTest) {
LOG_INFO("Bootstrapping...");
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, nullptr);
LOG_INFO("Bootstrapping completed!");
// Create a table first
auto& txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
LOG_INFO("Creating table");
LOG_INFO(
"Query: CREATE TABLE department_table(dept_id INT PRIMARY KEY,student_id "
"INT, dept_name TEXT);");
std::unique_ptr<Statement> statement;
statement.reset(new Statement("CREATE",
"CREATE TABLE department_table(dept_id INT "
"PRIMARY KEY, student_id INT, dept_name "
"TEXT);"));
auto& peloton_parser = parser::Parser::GetInstance();
auto create_stmt = peloton_parser.BuildParseTree(
"CREATE TABLE department_table(dept_id INT PRIMARY KEY, student_id INT, "
"dept_name TEXT);");
statement->SetPlanTree(
optimizer::SimpleOptimizer::BuildPelotonPlanTree(create_stmt));
std::vector<common::Value*> params;
std::vector<ResultType> result;
bridge::PlanExecutor::PrintPlan(statement->GetPlanTree().get(), "Plan");
std::vector<int> result_format;
result_format =
std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
bridge::peloton_status status = bridge::PlanExecutor::ExecutePlan(
statement->GetPlanTree().get(), params, result, result_format);
LOG_INFO("Statement executed. Result: %d", status.m_result);
LOG_INFO("Table Created");
txn_manager.CommitTransaction(txn);
EXPECT_EQ(catalog::Catalog::GetInstance()
->GetDatabaseWithName(DEFAULT_DB_NAME)
->GetTableCount(),
1);
// Inserting a tuple end-to-end
txn = txn_manager.BeginTransaction();
LOG_INFO("Inserting a tuple...");
LOG_INFO(
"Query: INSERT INTO department_table(dept_id,student_id ,dept_name) "
"VALUES (1,52,'hello_1');");
statement.reset(new Statement("INSERT",
"INSERT INTO department_table(dept_id, "
"student_id, dept_name) VALUES "
"(1,52,'hello_1');"));
auto insert_stmt = peloton_parser.BuildParseTree(
"INSERT INTO department_table(dept_id,student_id,dept_name) VALUES "
"(1,52,'hello_1');");
statement->SetPlanTree(
optimizer::SimpleOptimizer::BuildPelotonPlanTree(insert_stmt));
result_format =
std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
status = bridge::PlanExecutor::ExecutePlan(statement->GetPlanTree().get(),
params, result, result_format);
LOG_INFO("Statement executed. Result: %d", status.m_result);
LOG_INFO("Tuple inserted!");
txn_manager.CommitTransaction(txn);
// Now Create index
txn = txn_manager.BeginTransaction();
LOG_INFO("Creating and Index");
LOG_INFO("Query: CREATE INDEX saif ON department_table (student_id);");
statement.reset(new Statement(
"CREATE", "CREATE INDEX saif ON department_table (student_id);"));
auto update_stmt = peloton_parser.BuildParseTree(
"CREATE INDEX saif ON department_table (student_id);");
statement->SetPlanTree(
optimizer::SimpleOptimizer::BuildPelotonPlanTree(update_stmt));
result_format =
std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
status = bridge::PlanExecutor::ExecutePlan(statement->GetPlanTree().get(),
params, result, result_format);
LOG_INFO("Statement executed. Result: %d", status.m_result);
LOG_INFO("INDEX CREATED!");
txn_manager.CommitTransaction(txn);
auto target_table_ = catalog::Catalog::GetInstance()->GetTableWithName(
DEFAULT_DB_NAME, "department_table");
// Expected 1 , Primary key index + created index
EXPECT_EQ(target_table_->GetIndexCount(), 2);
// Test update tuple with index scan
txn = txn_manager.BeginTransaction();
LOG_INFO("Updating a tuple...");
LOG_INFO(
"Query: UPDATE department_table SET dept_name = 'CS' WHERE student_id = 52");
statement.reset(new Statement(
"UPDATE",
"UPDATE department_table SET dept_name = 'CS' WHERE student_id = 52"));
LOG_INFO("Building parse tree...");
update_stmt = peloton_parser.BuildParseTree(
"UPDATE department_table SET dept_name = 'CS' WHERE student_id = 52");
LOG_INFO("Building parse tree completed!");
LOG_INFO("Building plan tree...");
statement->SetPlanTree(
optimizer::SimpleOptimizer::BuildPelotonPlanTree(update_stmt));
LOG_INFO("Building plan tree completed!");
planner::AbstractPlan *plan = statement->GetPlanTree().get();
bridge::PlanExecutor::PrintPlan(statement->GetPlanTree().get(), "Plan");
// Check scan plan
ASSERT_FALSE(plan == nullptr);
if (plan->GetPlanNodeType() == PLAN_NODE_TYPE_UPDATE) {
auto& scanPlan = plan->GetChildren().front();
EXPECT_EQ(scanPlan->GetPlanNodeType(), PLAN_NODE_TYPE_INDEXSCAN);
}
LOG_INFO("Executing plan...");
result_format =
std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
status = bridge::PlanExecutor::ExecutePlan(statement->GetPlanTree().get(),
params, result, result_format);
LOG_INFO("Statement executed. Result: %d", status.m_result);
LOG_INFO("Tuple Updated!");
txn_manager.CommitTransaction(txn);
// Test delete tuple with index scan
txn = txn_manager.BeginTransaction();
LOG_INFO("Deleting a tuple...");
LOG_INFO("Query: DELETE FROM department_table WHERE student_id = 52");
statement.reset(new Statement(
"DELETE", "DELETE FROM department_table WHERE student_id = 52"));
LOG_INFO("Building parse tree...");
auto delete_stmt = peloton_parser.BuildParseTree(
"DELETE FROM department_table WHERE student_id = 52");
LOG_INFO("Building parse tree completed!");
LOG_INFO("Building plan tree...");
statement->SetPlanTree(
optimizer::SimpleOptimizer::BuildPelotonPlanTree(delete_stmt));
LOG_INFO("Building plan tree completed!");
planner::AbstractPlan *delPlan = statement->GetPlanTree().get();
bridge::PlanExecutor::PrintPlan(statement->GetPlanTree().get(), "Plan");
// Check scan plan
ASSERT_FALSE(delPlan == nullptr);
if (delPlan->GetPlanNodeType() == PLAN_NODE_TYPE_DELETE) {
auto& scanPlan = delPlan->GetChildren().front();
EXPECT_EQ(scanPlan->GetPlanNodeType(), PLAN_NODE_TYPE_INDEXSCAN);
}
LOG_INFO("Executing plan...");
result_format = std::move(std::vector<int>(0, 0));
status = bridge::PlanExecutor::ExecutePlan(statement->GetPlanTree().get(),
params, result, result_format);
LOG_INFO("Statement executed. Result: %d", status.m_result);
LOG_INFO("Tuple deleted!");
txn_manager.CommitTransaction(txn);
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} /* namespace test */
} /* namespace peloton */
<commit_msg>Remove index scan test in rule_test<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// rule_test.cpp
//
// Identification: test/optimizer/rule_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#define private public
#include "optimizer/operator_expression.h"
#include "optimizer/operators.h"
#include "optimizer/optimizer.h"
#include "optimizer/rule.h"
#include "optimizer/rule_impls.h"
#include "catalog/catalog.h"
#include "common/logger.h"
#include "common/statement.h"
#include "executor/create_executor.h"
#include "executor/delete_executor.h"
#include "executor/insert_executor.h"
#include "executor/plan_executor.h"
#include "executor/update_executor.h"
#include "optimizer/simple_optimizer.h"
#include "parser/parser.h"
#include "planner/create_plan.h"
#include "planner/delete_plan.h"
#include "planner/insert_plan.h"
#include "planner/update_plan.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Binding Tests
//===--------------------------------------------------------------------===//
using namespace optimizer;
class RuleTests : public PelotonTest {};
TEST_F(RuleTests, SimpleRuleApplyTest) {
// Build op plan node to match rule
auto left_get = std::make_shared<OperatorExpression>(LogicalGet::make(0));
auto right_get = std::make_shared<OperatorExpression>(LogicalGet::make(0));
auto val = type::ValueFactory::GetBooleanValue(true);
auto join = std::make_shared<OperatorExpression>(LogicalInnerJoin::make());
join->PushChild(left_get);
join->PushChild(right_get);
// Setup rule
InnerJoinCommutativity rule;
EXPECT_TRUE(rule.Check(join));
std::vector<std::shared_ptr<OperatorExpression>> outputs;
rule.Transform(join, outputs);
EXPECT_EQ(outputs.size(), 1);
}
} /* namespace test */
} /* namespace peloton */
<|endoftext|> |
<commit_before>#include <vector>
#include "unittest/catch.h"
#include "core/pattern.h"
#include "core/task.h"
#include "plugins/pluginUtils.h"
#include "plugins/pmd.h"
#include "utils/utils.h"
#include "executorStub.h"
#include "optionsStub.h"
using std::vector;
using std::string;
using execHelper::config::SettingsNode;
using execHelper::core::Task;
using execHelper::core::TaskCollection;
using execHelper::core::Pattern;
using execHelper::plugins::Pmd;
using execHelper::test::OptionsStub;
using execHelper::test::utils::Patterns;
using execHelper::test::utils::PATTERN1;
using execHelper::test::utils::PATTERN2;
using execHelper::test::utils::PATTERNS;
using execHelper::test::utils::PATTERN_KEYS;
using execHelper::test::utils::copyAndAppend;
using execHelper::test::utils::createPatternCombination;
using execHelper::core::test::ExecutorStub;
namespace {
const string pmdConfigKey("pmd");
const string PLUGIN_CONFIG_KEY("pmd");
const string EXEC_CONFIG_KEY("exec");
const string TOOL_CONFIG_KEY("tool");
const string MINIMUM_TOKENS_CONFIG_KEY("minimum-tokens");
const string FILES_CONFIG_KEY("files");
const string LANGUAGE_CONFIG_KEY("language");
}
namespace execHelper { namespace plugins { namespace test {
SCENARIO("Test the default options of the pmd plugin", "[plugins][pmd]") {
GIVEN("A default configuration and the plugin") {
Pmd plugin;
Task task;
const OptionsStub options;
WHEN("We call the plugin") {
bool returnCode = plugin.apply("random-command", task, options);
THEN("The call should fail") {
REQUIRE_FALSE(returnCode);
}
}
}
}
SCENARIO("Test the mandatory options of the pmd plugin", "[plugins][pmd]") {
GIVEN("The respective configuration and the plugin") {
const string command("pmd-command");
OptionsStub options;
SettingsNode& rootSettings = options.m_settings;
Pmd plugin;
Task task;
WHEN("We add the tool config parameter") {
AND_WHEN("We use a general parameter") {
rootSettings.add({pmdConfigKey, "tool"}, "tool");
}
AND_WHEN("We use a specific parameter") {
rootSettings.add({pmdConfigKey, command, "tool"}, "tool");
}
THEN_WHEN("We apply the plugin") {
bool returnCode = plugin.apply(command, task, options);
THEN_CHECK("That the apply succeeds") {
REQUIRE_FALSE(returnCode);
}
}
}
WHEN("We add the exec config parameter") {
THEN("As a general parameter") {
rootSettings.add({pmdConfigKey, "exec"}, "pmd.sh");
}
THEN("As a specific parameter") {
rootSettings.add({pmdConfigKey, command, "exec"}, "pmd.sh");
}
REQUIRE_FALSE(plugin.apply(command, task, options));
}
WHEN("We add all mandatory config parameters and apply command ") {
THEN("As a general command") {
rootSettings.add({pmdConfigKey, "tool"}, "tool");
rootSettings.add({pmdConfigKey, "exec"}, "pmd.sh");
}
THEN("As a specific command") {
rootSettings.add({pmdConfigKey, command, "tool"}, "tool");
rootSettings.add({pmdConfigKey, command, "exec"}, "pmd.sh");
}
REQUIRE(plugin.apply(command, task, options));
ExecutorStub::TaskQueue actualTasks;
Task actualTask({"pmd.sh", "tool"});
actualTasks.emplace_back(actualTask);
REQUIRE(actualTasks == options.m_executor.getExecutedTasks());
}
}
}
SCENARIO("Make combinations of different configurations for the pmd plugin", "[plugins][pmd]") {
MAKE_COMBINATIONS("Of several settings") {
const string command("pmd-command");
OptionsStub options;
for(const auto& pattern : PATTERNS) {
options.m_patternsHandler->addPattern(pattern);
}
SettingsNode& rootSettings = options.m_settings;
rootSettings.add({PLUGIN_CONFIG_KEY, "patterns"}, {PATTERN1.getKey(), PATTERN2.getKey()});
// Add the settings of an other command to make sure we take the expected ones
const string otherCommandKey("other-command");
Pmd plugin;
Task task;
Task expectedTask;
TaskCollection exec({"pmd.sh"});
TaskCollection tool({"tool1"});
TaskCollection minimumTokens;
TaskCollection files;
TaskCollection verbosity;
TaskCollection language;
TaskCollection commandLine;
SettingsNode::SettingsKeys baseSettingsKeys = {PLUGIN_CONFIG_KEY};
SettingsNode::SettingsKeys otherBaseSettingsKeys = {PLUGIN_CONFIG_KEY, otherCommandKey};
COMBINATIONS("Toggle between general and specific command settings") {
baseSettingsKeys.push_back(command);
}
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, EXEC_CONFIG_KEY), "other-exec");
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, TOOL_CONFIG_KEY), "other-tool");
COMBINATIONS("Switch off verbosity") {
options.m_verbosity = false;
}
COMBINATIONS("Switch on verbosity") {
options.m_verbosity = true;
verbosity.emplace_back("-verbose");
}
COMBINATIONS("Switch on the cpd tool") {
tool.clear();
tool = {"cpd"};
}
COMBINATIONS("Switch on minimum tokens") {
const string minimumTokensValue("100");
rootSettings.add(copyAndAppend(baseSettingsKeys, MINIMUM_TOKENS_CONFIG_KEY), minimumTokensValue);
if(tool[0] == "cpd") {
minimumTokens.emplace_back("--minimum-tokens");
minimumTokens.emplace_back("100");
}
}
COMBINATIONS("Switch on files") {
const vector<string> filesValue({"file1", "file2", "file*"});
rootSettings.add(copyAndAppend(baseSettingsKeys, FILES_CONFIG_KEY), filesValue);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, FILES_CONFIG_KEY), "other-file");
if(tool[0] == "cpd") {
for(const auto& file : filesValue) {
files.emplace_back("--files");
files.emplace_back(file);
}
}
}
COMBINATIONS("Add a language") {
const string languageValue("language1");
language.push_back("--language");
language.push_back(languageValue);
rootSettings.add(copyAndAppend(baseSettingsKeys, LANGUAGE_CONFIG_KEY), languageValue);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, LANGUAGE_CONFIG_KEY), "other-language");
}
COMBINATIONS("Add a command line") {
commandLine = {"{" + PATTERN2.getKey() + "}", "{" + PATTERN2.getKey() + "}"};
rootSettings.add(copyAndAppend(baseSettingsKeys, "command-line"), commandLine);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, "command-line"), "--some-command");
}
rootSettings.add(copyAndAppend(baseSettingsKeys, EXEC_CONFIG_KEY), exec);
rootSettings.add(copyAndAppend(baseSettingsKeys, TOOL_CONFIG_KEY), tool);
expectedTask.append(exec);
expectedTask.append(tool);
expectedTask.append(minimumTokens);
expectedTask.append(files);
expectedTask.append(language);
expectedTask.append(verbosity);
expectedTask.append(commandLine);
ExecutorStub::TaskQueue expectedTasks;
for(const std::map<string, string>& target : options.makePatternPermutator(PATTERN_KEYS)) {
Task replacedExpectedTask = replacePatternCombinations(expectedTask, target);
expectedTasks.emplace_back(replacedExpectedTask);
}
bool returnCode = plugin.apply(command, task, options);
THEN_CHECK("It should succeed") {
REQUIRE(returnCode);
}
THEN_CHECK("It called the right commands") {
REQUIRE(expectedTasks == options.m_executor.getExecutedTasks());
}
}
}
} } }
<commit_msg>Fixed remarks of clang-tidy<commit_after>#include <vector>
#include "unittest/catch.h"
#include "core/pattern.h"
#include "core/task.h"
#include "plugins/pluginUtils.h"
#include "plugins/pmd.h"
#include "utils/utils.h"
#include "executorStub.h"
#include "optionsStub.h"
using std::vector;
using std::string;
using execHelper::config::SettingsNode;
using execHelper::core::Task;
using execHelper::core::TaskCollection;
using execHelper::plugins::Pmd;
using execHelper::test::OptionsStub;
using execHelper::test::utils::Patterns;
using execHelper::test::utils::PATTERN1;
using execHelper::test::utils::PATTERN2;
using execHelper::test::utils::PATTERNS;
using execHelper::test::utils::PATTERN_KEYS;
using execHelper::test::utils::copyAndAppend;
using execHelper::core::test::ExecutorStub;
namespace {
const string pmdConfigKey("pmd");
const string PLUGIN_CONFIG_KEY("pmd");
const string EXEC_CONFIG_KEY("exec");
const string TOOL_CONFIG_KEY("tool");
const string MINIMUM_TOKENS_CONFIG_KEY("minimum-tokens");
const string FILES_CONFIG_KEY("files");
const string LANGUAGE_CONFIG_KEY("language");
}
namespace execHelper { namespace plugins { namespace test {
SCENARIO("Test the default options of the pmd plugin", "[plugins][pmd]") {
GIVEN("A default configuration and the plugin") {
Pmd plugin;
Task task;
const OptionsStub options;
WHEN("We call the plugin") {
bool returnCode = plugin.apply("random-command", task, options);
THEN("The call should fail") {
REQUIRE_FALSE(returnCode);
}
}
}
}
SCENARIO("Test the mandatory options of the pmd plugin", "[plugins][pmd]") {
GIVEN("The respective configuration and the plugin") {
const string command("pmd-command");
OptionsStub options;
SettingsNode& rootSettings = options.m_settings;
Pmd plugin;
Task task;
WHEN("We add the tool config parameter") {
AND_WHEN("We use a general parameter") {
rootSettings.add({pmdConfigKey, "tool"}, "tool");
}
AND_WHEN("We use a specific parameter") {
rootSettings.add({pmdConfigKey, command, "tool"}, "tool");
}
THEN_WHEN("We apply the plugin") {
bool returnCode = plugin.apply(command, task, options);
THEN_CHECK("That the apply succeeds") {
REQUIRE_FALSE(returnCode);
}
}
}
WHEN("We add the exec config parameter") {
THEN("As a general parameter") {
rootSettings.add({pmdConfigKey, "exec"}, "pmd.sh");
}
THEN("As a specific parameter") {
rootSettings.add({pmdConfigKey, command, "exec"}, "pmd.sh");
}
REQUIRE_FALSE(plugin.apply(command, task, options));
}
WHEN("We add all mandatory config parameters and apply command ") {
THEN("As a general command") {
rootSettings.add({pmdConfigKey, "tool"}, "tool");
rootSettings.add({pmdConfigKey, "exec"}, "pmd.sh");
}
THEN("As a specific command") {
rootSettings.add({pmdConfigKey, command, "tool"}, "tool");
rootSettings.add({pmdConfigKey, command, "exec"}, "pmd.sh");
}
REQUIRE(plugin.apply(command, task, options));
ExecutorStub::TaskQueue actualTasks;
Task actualTask({"pmd.sh", "tool"});
actualTasks.emplace_back(actualTask);
REQUIRE(actualTasks == options.m_executor.getExecutedTasks());
}
}
}
SCENARIO("Make combinations of different configurations for the pmd plugin", "[plugins][pmd]") {
MAKE_COMBINATIONS("Of several settings") {
const string command("pmd-command");
OptionsStub options;
for(const auto& pattern : PATTERNS) {
options.m_patternsHandler->addPattern(pattern);
}
SettingsNode& rootSettings = options.m_settings;
rootSettings.add({PLUGIN_CONFIG_KEY, "patterns"}, {PATTERN1.getKey(), PATTERN2.getKey()});
// Add the settings of an other command to make sure we take the expected ones
const string otherCommandKey("other-command");
Pmd plugin;
Task task;
Task expectedTask;
TaskCollection exec({"pmd.sh"});
TaskCollection tool({"tool1"});
TaskCollection minimumTokens;
TaskCollection files;
TaskCollection verbosity;
TaskCollection language;
TaskCollection commandLine;
SettingsNode::SettingsKeys baseSettingsKeys = {PLUGIN_CONFIG_KEY};
SettingsNode::SettingsKeys otherBaseSettingsKeys = {PLUGIN_CONFIG_KEY, otherCommandKey};
COMBINATIONS("Toggle between general and specific command settings") {
baseSettingsKeys.push_back(command);
}
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, EXEC_CONFIG_KEY), "other-exec");
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, TOOL_CONFIG_KEY), "other-tool");
COMBINATIONS("Switch off verbosity") {
options.m_verbosity = false;
}
COMBINATIONS("Switch on verbosity") {
options.m_verbosity = true;
verbosity.emplace_back("-verbose");
}
COMBINATIONS("Switch on the cpd tool") {
tool.clear();
tool = {"cpd"};
}
COMBINATIONS("Switch on minimum tokens") {
const string minimumTokensValue("100");
rootSettings.add(copyAndAppend(baseSettingsKeys, MINIMUM_TOKENS_CONFIG_KEY), minimumTokensValue);
if(tool[0] == "cpd") {
minimumTokens.emplace_back("--minimum-tokens");
minimumTokens.emplace_back("100");
}
}
COMBINATIONS("Switch on files") {
const vector<string> filesValue({"file1", "file2", "file*"});
rootSettings.add(copyAndAppend(baseSettingsKeys, FILES_CONFIG_KEY), filesValue);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, FILES_CONFIG_KEY), "other-file");
if(tool[0] == "cpd") {
for(const auto& file : filesValue) {
files.emplace_back("--files");
files.emplace_back(file);
}
}
}
COMBINATIONS("Add a language") {
const string languageValue("language1");
language.emplace_back("--language");
language.push_back(languageValue);
rootSettings.add(copyAndAppend(baseSettingsKeys, LANGUAGE_CONFIG_KEY), languageValue);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, LANGUAGE_CONFIG_KEY), "other-language");
}
COMBINATIONS("Add a command line") {
commandLine = {"{" + PATTERN2.getKey() + "}", "{" + PATTERN2.getKey() + "}"};
rootSettings.add(copyAndAppend(baseSettingsKeys, "command-line"), commandLine);
rootSettings.add(copyAndAppend(otherBaseSettingsKeys, "command-line"), "--some-command");
}
rootSettings.add(copyAndAppend(baseSettingsKeys, EXEC_CONFIG_KEY), exec);
rootSettings.add(copyAndAppend(baseSettingsKeys, TOOL_CONFIG_KEY), tool);
expectedTask.append(exec);
expectedTask.append(tool);
expectedTask.append(minimumTokens);
expectedTask.append(files);
expectedTask.append(language);
expectedTask.append(verbosity);
expectedTask.append(commandLine);
ExecutorStub::TaskQueue expectedTasks;
for(const std::map<string, string>& target : options.makePatternPermutator(PATTERN_KEYS)) {
Task replacedExpectedTask = replacePatternCombinations(expectedTask, target);
expectedTasks.emplace_back(replacedExpectedTask);
}
bool returnCode = plugin.apply(command, task, options);
THEN_CHECK("It should succeed") {
REQUIRE(returnCode);
}
THEN_CHECK("It called the right commands") {
REQUIRE(expectedTasks == options.m_executor.getExecutedTasks());
}
}
}
} } }
<|endoftext|> |
<commit_before><commit_msg>added more outputs to diamond<commit_after><|endoftext|> |
<commit_before><commit_msg>Add whitespace between the string literal and the macro<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 10 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation_thread(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
void *userInterface(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Holds the latest temperature value from the temperature temperature sensor
float temperature;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
// setmotor intialization
float portmotorspeed = 0;
float starmotorspeed = 0;
// Start time for stop timer
time_t start;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// capture ctrl+c and exit
signal(SIGINT, ctrl_c);
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
pthread_t navigationThread;
pthread_t depthThread;
//pthread_t safetyThread;
//pthread_t disarmlaserThread;
pthread_t uiThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL);
pthread_create (&uiThread, &tattrmed, userInterface, NULL);
// Destroy the thread attributes
destroyTAttr();
printf("Threads started\n");
// Start timer!
start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = PAUSED;
// Sleep a little
auv_usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or not
******************************************************************************/
void *depth_thread(void* arg)
{
printf("Depth Thread Started\n");
while(substate.mode!=STOPPED)
{
// Read pressure values
ms5837 = read_pressure_fifo();
// read IMU values from fifo file
substate.imu = read_imu_fifo();
// Only print while RUNNING
if(substate.mode == RUNNING)
{
printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n",
ms5837.depth, ms5837.water_temp);
printf("Current battery temp:\t %.2f\n", read_temp_fifo());
// Write IMU data
printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: "
"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
substate.imu.yaw, substate.imu.roll, substate.imu.pitch,
substate.imu.p, substate.imu.q, substate.imu.r,
substate.imu.sys, substate.imu.gyro, substate.imu.accel,
substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
substate.imu.z_acc);
}
auv_usleep(1000000);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
void *navigation_thread(void* arg)
{
printf("Nav Thread Started\n");
initialize_motors(motor_channels, HERTZ);
float yaw = 0; //Local variable for if statements
float motorpercent;
float basespeed = 0.2;
////////////////////////////////
// Yaw Control Initialization //
////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.sat = YAW_SAT;
yaw_pid.dt = DT; // initialize time step
//////////////////////////////////
// Depth Control Initialization //
//////////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.dt = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; // Depth controller saturation values
depth_pid.sat = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) // AUV pointed right
{
yaw = substate.imu.yaw;
}
else // AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
// Only tell motors to run if we are RUNNING
if( substate.mode == RUNNING)
{
//calculate yaw controller output
motorpercent = marchPID(yaw_pid, yaw);
// Set port and starboard
portmotorspeed = basespeed + motorpercent;
starmotorspeed = basespeed - motorpercent;
// Set port motor
set_motor(0, portmotorspeed);
// Set starboard motor
set_motor(1, starmotorspeed);
} // end if RUNNING
else if( substate.mode == PAUSED)
{
// Stop horizontal motors
set_motor(0, 0);
set_motor(1, 0);
// Wipe integral error
yaw_pid.ierr = 0;
// Sleep a while (we're not doing anything anyways)
auv_usleep(100000);
} // end if PAUSED
// Sleep for 5 ms
auv_usleep(DT);
}
// Turn motors off
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
/*void *safety_thread(void* arg)
{
printf("Safety Thread Started\n");
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
temperature = read_temp_fifo();
printf("Temperature: %f degC\n", temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check for leak
leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
/******************************************************************************
* User Interface Thread
* void* userInterface(void* arg)
*
* Interfaces with the user, asks for input
*****************************************************************************/
void* userInterface(void* arg)
{
// Declare local constant variables
float _kp, _ki, _kd;
// Wait a until everything is initialized before starting
while(substate.mode == INITIALIZING)
{
// Waiting...
auv_usleep(100000);
}
// Prompt user for values continuously until the program exits
while(substate.mode != STOPPED)
{
// Prompt for kp
std::cout << "Kp: ";
std::cin >> _kp;
// Prompt for ki
std::cout << "Ki: ";
std::cin >> _ki;
// Prompt for kd
std::cout << "Kd: ";
std::cin >> _kd;
// Give a newline
std::cout << std::endl;
// Reset gain values
yaw_pid.kp = _kp;
yaw_pid.ki = _ki;
yaw_pid.kd = _kd;
// Clear errors
yaw_pid.perr = 0;
yaw_pid.ierr = 0;
yaw_pid.derr = 0;
// Start RUNNING again
substate.mode = RUNNING;
// Restart timer!
start = time(0);
// Aaaaaaand, WAIT!
auv_usleep(10*1000000);
}
// Exit thread
pthread_exit(NULL);
}
<commit_msg>Set to running<commit_after>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 10 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation_thread(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
void *userInterface(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Holds the latest temperature value from the temperature temperature sensor
float temperature;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
// setmotor intialization
float portmotorspeed = 0;
float starmotorspeed = 0;
// Start time for stop timer
time_t start;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// capture ctrl+c and exit
signal(SIGINT, ctrl_c);
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
pthread_t navigationThread;
pthread_t depthThread;
//pthread_t safetyThread;
//pthread_t disarmlaserThread;
pthread_t uiThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL);
pthread_create (&uiThread, &tattrmed, userInterface, NULL);
// Destroy the thread attributes
destroyTAttr();
printf("Threads started\n");
// Start timer!
start = time(0);
// We're ready to run.
substate.mode = RUNNING;
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = PAUSED;
// Sleep a little
auv_usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or not
******************************************************************************/
void *depth_thread(void* arg)
{
printf("Depth Thread Started\n");
while(substate.mode!=STOPPED)
{
// Read pressure values
ms5837 = read_pressure_fifo();
// read IMU values from fifo file
substate.imu = read_imu_fifo();
// Only print while RUNNING
if(substate.mode == RUNNING)
{
printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n",
ms5837.depth, ms5837.water_temp);
printf("Current battery temp:\t %.2f\n", read_temp_fifo());
// Write IMU data
printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: "
"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
substate.imu.yaw, substate.imu.roll, substate.imu.pitch,
substate.imu.p, substate.imu.q, substate.imu.r,
substate.imu.sys, substate.imu.gyro, substate.imu.accel,
substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
substate.imu.z_acc);
}
auv_usleep(1000000);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
void *navigation_thread(void* arg)
{
printf("Nav Thread Started\n");
initialize_motors(motor_channels, HERTZ);
float yaw = 0; //Local variable for if statements
float motorpercent;
float basespeed = 0.2;
////////////////////////////////
// Yaw Control Initialization //
////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.sat = YAW_SAT;
yaw_pid.dt = DT; // initialize time step
//////////////////////////////////
// Depth Control Initialization //
//////////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.dt = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; // Depth controller saturation values
depth_pid.sat = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) // AUV pointed right
{
yaw = substate.imu.yaw;
}
else // AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
// Only tell motors to run if we are RUNNING
if( substate.mode == RUNNING)
{
//calculate yaw controller output
motorpercent = marchPID(yaw_pid, yaw);
// Set port and starboard
portmotorspeed = basespeed + motorpercent;
starmotorspeed = basespeed - motorpercent;
// Set port motor
set_motor(0, portmotorspeed);
// Set starboard motor
set_motor(1, starmotorspeed);
} // end if RUNNING
else if( substate.mode == PAUSED)
{
// Stop horizontal motors
set_motor(0, 0);
set_motor(1, 0);
// Wipe integral error
yaw_pid.ierr = 0;
// Sleep a while (we're not doing anything anyways)
auv_usleep(100000);
} // end if PAUSED
// Sleep for 5 ms
auv_usleep(DT);
}
// Turn motors off
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
/*void *safety_thread(void* arg)
{
printf("Safety Thread Started\n");
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
temperature = read_temp_fifo();
printf("Temperature: %f degC\n", temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check for leak
leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
/******************************************************************************
* User Interface Thread
* void* userInterface(void* arg)
*
* Interfaces with the user, asks for input
*****************************************************************************/
void* userInterface(void* arg)
{
// Declare local constant variables
float _kp, _ki, _kd;
// Wait a until everything is initialized before starting
while(substate.mode == INITIALIZING)
{
// Waiting...
auv_usleep(100000);
}
// Prompt user for values continuously until the program exits
while(substate.mode != STOPPED)
{
// Prompt for kp
std::cout << "Kp: ";
std::cin >> _kp;
// Prompt for ki
std::cout << "Ki: ";
std::cin >> _ki;
// Prompt for kd
std::cout << "Kd: ";
std::cin >> _kd;
// Give a newline
std::cout << std::endl;
// Reset gain values
yaw_pid.kp = _kp;
yaw_pid.ki = _ki;
yaw_pid.kd = _kd;
// Clear errors
yaw_pid.perr = 0;
yaw_pid.ierr = 0;
yaw_pid.derr = 0;
// Start RUNNING again
substate.mode = RUNNING;
// Restart timer!
start = time(0);
// Aaaaaaand, WAIT!
auv_usleep(12*1000000);
}
// Exit thread
pthread_exit(NULL);
}
<|endoftext|> |
<commit_before>#ifndef MAZE_ALGORITHM_C
#define MAZE_ALGORITHM_C
#include <stdio.h>
#include <string.h>
#include "MazeAlgorithm.h"
#include "MazeMap.h"
// computes the flood fill for the first time (center is the target)
void malgo_floodfill_compute(MazeMap* mm, ff_map* in)
{
// blanks out the array to null values
memset(in, MALGO_FF_BAD, sizeof(ff_map));
// set the inner four values to 0 (this is the target)
int centerRow = MAZE_HEIGHT / 2 - 1;
int centerCol = MAZE_WIDTH / 2 - 1;
in->array[centerRow][centerCol] = 0;
in->array[centerRow][centerCol + 1] = 0;
in->array[centerRow + 1][centerCol] = 0;
in->array[centerRow + 1][centerCol + 1] = 0;
// now keep looping in each direction until the values have been populated
bool isPopulated = false;
//while(!isPopulated) {
for (int dumbshit = 0; dumbshit < 100000; dumbshit++) {
// SOUTH to NORTH
for (int row = 0; row < (MAZE_HEIGHT-1); row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, NORTH); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get the value of the next column
int nextVal = in->array[row + 1][col];
// if the next value isn't bad, set the current one to it + 1
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// NORTH to SOUTH
for (int row = MAZE_HEIGHT-1; row > 0; row--) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, SOUTH); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get next value
int nextVal = in->array[row - 1][col];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// WEST to EAST
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < (MAZE_WIDTH-1); col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, EAST); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get next val
int nextVal = in->array[row][col + 1];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// EAST to WEST
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = MAZE_WIDTH-1; col > 0; col--) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, WEST); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get the next val
int nextVal = in->array[row][col - 1];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
}
}
// retargets the flood fill map
// ** UNTESTED ** -- this will be wrong with the middle zero blocks
void malgo_floodfill_recompute_target(int targetX, int targetY, ff_map* in)
{
// find the current target
int currentX = MALGO_FF_BAD;
int currentY = MALGO_FF_BAD;
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int value = in->array[row][col];
if (value == 0) {
currentX = col;
currentY = row;
break;
}
}
// if inner forloop found a match, break out of this one
if (currentX != MALGO_FF_BAD) {
break;
}
}
// the new difference will be the current value of the new target
int difference = in->array[currentY][currentX];
// displace the rest of the array
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
// make sure the value is always positive
int curValue = in->array[row][col];
if (difference > curValue) {
in->array[row][col] = difference - curValue;
}
else {
in->array[row][col] = curValue - difference;
}
}
}
}
// uses floodfill to determine where to go
Direction malgo_floodfill_suggest_turn(int xPos, int yPos, MazeMap *mazeMap, ff_map* ffMap)
{
int minVal = 100000;
Direction minDir = EAST;
bool eastWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, EAST);
bool southWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, SOUTH);
bool westWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, WEST);
bool northWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, NORTH);
int eastVal = 10000; int southVal = 10000; int westVal = 10000; int northVal = 10000;
if (!eastWall) {
eastVal = ffMap->array[yPos][xPos + 1];
}
if (!southWall) {
southVal = ffMap->array[yPos - 1][xPos];
}
if (!westWall) {
westVal = ffMap->array[yPos][xPos - 1];
}
if (!northWall) {
northVal = ffMap->array[yPos + 1][xPos];
}
//printf("East: %d", eastWall);
//printf("South: %d", southWall);
//printf("West: %d", westWall);
//printf("North: %d", northWall);
printf("E: %d, S: %d, W: %d, N: %d\n", eastWall, southWall, westWall, northWall);
printf("E: %d, S: %d, W: %d, N: %d\n", eastVal, southVal, westVal, northVal);
if (!eastWall && eastVal < minVal) {
printf("east is min\n");
minDir = EAST;
minVal = eastVal;
}
if (!southWall && southVal < minVal) {
printf("south is min\n");
minDir = SOUTH;
minVal = southVal;
}
if (!westWall && westVal < minVal) {
printf("west is min\n");
minDir = WEST;
minVal = westVal;
}
if (!northWall && northVal < minVal) {
printf("north is min\n");
minDir = NORTH;
}
return minDir;
}
#endif
<commit_msg>cleaning up the code literally<commit_after>#ifndef MAZE_ALGORITHM_C
#define MAZE_ALGORITHM_C
#include <stdio.h>
#include <string.h>
#include "MazeAlgorithm.h"
#include "MazeMap.h"
// computes the flood fill for the first time (center is the target)
void malgo_floodfill_compute(MazeMap* mm, ff_map* in)
{
// blanks out the array to null values
memset(in, MALGO_FF_BAD, sizeof(ff_map));
// set the inner four values to 0 (this is the target)
int centerRow = MAZE_HEIGHT / 2 - 1;
int centerCol = MAZE_WIDTH / 2 - 1;
in->array[centerRow][centerCol] = 0;
in->array[centerRow][centerCol + 1] = 0;
in->array[centerRow + 1][centerCol] = 0;
in->array[centerRow + 1][centerCol + 1] = 0;
// now keep looping in each direction until the values have been populated
bool isPopulated = false;
//while(!isPopulated) {
for (int stupid = 0; stupid < 100000; stupid++) {
// SOUTH to NORTH
for (int row = 0; row < (MAZE_HEIGHT-1); row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, NORTH); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get the value of the next column
int nextVal = in->array[row + 1][col];
// if the next value isn't bad, set the current one to it + 1
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// NORTH to SOUTH
for (int row = MAZE_HEIGHT-1; row > 0; row--) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, SOUTH); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get next value
int nextVal = in->array[row - 1][col];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// WEST to EAST
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < (MAZE_WIDTH-1); col++) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, EAST); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get next val
int nextVal = in->array[row][col + 1];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
// EAST to WEST
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = MAZE_WIDTH-1; col > 0; col--) {
int curVal = in->array[row][col];
if (curVal != MALGO_FF_BAD || curVal == 0) {
continue;
}
bool wallExists = mazemap_does_wall_exist(mm, col, row, WEST); // bottom left is (0,0)
if (wallExists) {
continue;
}
// get the next val
int nextVal = in->array[row][col - 1];
if (nextVal != MALGO_FF_BAD) {
in->array[row][col] = nextVal + 1;
}
}
}
}
}
// retargets the flood fill map
// ** UNTESTED ** -- this will be wrong with the middle zero blocks
void malgo_floodfill_recompute_target(int targetX, int targetY, ff_map* in)
{
// find the current target
int currentX = MALGO_FF_BAD;
int currentY = MALGO_FF_BAD;
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
int value = in->array[row][col];
if (value == 0) {
currentX = col;
currentY = row;
break;
}
}
// if inner forloop found a match, break out of this one
if (currentX != MALGO_FF_BAD) {
break;
}
}
// the new difference will be the current value of the new target
int difference = in->array[currentY][currentX];
// displace the rest of the array
for (int row = 0; row < MAZE_HEIGHT; row++) {
for (int col = 0; col < MAZE_WIDTH; col++) {
// make sure the value is always positive
int curValue = in->array[row][col];
if (difference > curValue) {
in->array[row][col] = difference - curValue;
}
else {
in->array[row][col] = curValue - difference;
}
}
}
}
// uses floodfill to determine where to go
Direction malgo_floodfill_suggest_turn(int xPos, int yPos, MazeMap *mazeMap, ff_map* ffMap)
{
int minVal = 100000;
Direction minDir = EAST;
bool eastWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, EAST);
bool southWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, SOUTH);
bool westWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, WEST);
bool northWall = mazemap_does_wall_exist(mazeMap, xPos, yPos, NORTH);
int eastVal = 10000; int southVal = 10000; int westVal = 10000; int northVal = 10000;
if (!eastWall) {
eastVal = ffMap->array[yPos][xPos + 1];
}
if (!southWall) {
southVal = ffMap->array[yPos - 1][xPos];
}
if (!westWall) {
westVal = ffMap->array[yPos][xPos - 1];
}
if (!northWall) {
northVal = ffMap->array[yPos + 1][xPos];
}
//printf("East: %d", eastWall);
//printf("South: %d", southWall);
//printf("West: %d", westWall);
//printf("North: %d", northWall);
printf("E: %d, S: %d, W: %d, N: %d\n", eastWall, southWall, westWall, northWall);
printf("E: %d, S: %d, W: %d, N: %d\n", eastVal, southVal, westVal, northVal);
if (!eastWall && eastVal < minVal) {
printf("east is min\n");
minDir = EAST;
minVal = eastVal;
}
if (!southWall && southVal < minVal) {
printf("south is min\n");
minDir = SOUTH;
minVal = southVal;
}
if (!westWall && westVal < minVal) {
printf("west is min\n");
minDir = WEST;
minVal = westVal;
}
if (!northWall && northVal < minVal) {
printf("north is min\n");
minDir = NORTH;
}
return minDir;
}
#endif
<|endoftext|> |
<commit_before>/**
* Tests of str_rope and rope_node.
*
* @author Jean-Claude Paquin
**/
#include <catch.hpp>
#include <primitives/str_rope.h>
TEST_CASE("Empty rope_node", "[rope_node]") {
rope_node node;
SECTION("Empty node has nullptr left & right") {
REQUIRE(!node.data.left);
REQUIRE(!node.data.right);
}
SECTION("Empty node to string") {
REQUIRE(*node.to_string() == "");
}
SECTION("Empty node is not a leaf") {
REQUIRE(!node.is_leaf);
}
}
TEST_CASE("String rope_node", "[rope_node]") {
rope_node node(std::string("wow!"));
SECTION("String node is a leaf") {
REQUIRE(node.is_leaf);
}
}
TEST_CASE("Copy constructor for rope_node", "[rope_node]") {
SECTION("Copied node is a leaf node") {
rope_node node(std::string("that's a low price!"));
rope_node dupl(node);
REQUIRE(*dupl.to_string() == *node.to_string());
REQUIRE(dupl.is_leaf);
}
SECTION("Copied node is not a leaf node") {
rope_node node;
rope_node dupl(node);
REQUIRE(!dupl.is_leaf);
}
}
<commit_msg>More test file cleaning<commit_after>/**
* Tests of str_rope and rope_node.
*
* @author Jean-Claude Paquin
**/
#include <catch.hpp>
#include <primitives/str_rope.h>
TEST_CASE("Empty rope_node", "[rope_node]") {
rope_node node;
REQUIRE(!node.data.left);
REQUIRE(!node.data.right);
REQUIRE(*node.to_string() == "");
REQUIRE(!node.is_leaf);
REQUIRE(node.actual_size == 0);
}
TEST_CASE("String rope_node", "[rope_node]") {
rope_node node(std::string("wow!"));
REQUIRE(*node.to_string() == "wow!");
REQUIRE(node.is_leaf);
REQUIRE(node.actual_size == 4);
}
TEST_CASE("Copy constructor for rope_node", "[rope_node]") {
SECTION("Copied node is a leaf node") {
rope_node node(std::string("that's a low price!"));
rope_node dupl(node);
REQUIRE(*dupl.to_string() == *node.to_string());
REQUIRE(dupl.is_leaf);
}
SECTION("Copied node is not a leaf node") {
rope_node node;
rope_node dupl(node);
REQUIRE(!dupl.is_leaf);
}
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_TEST_UTIL_STUB_POTENTIAL_HPP
#define MJOLNIR_TEST_UTIL_STUB_POTENTIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/forcefield/global/ParameterList.hpp>
namespace mjolnir
{
namespace test
{
template<typename realT>
class StubPotential
{
public:
using real_type = realT;
using parameter_type = std::pair<std::size_t, std::size_t>;
using self_type = StubPotential<real_type>;
static constexpr real_type default_cutoff() noexcept
{
return real_type(2.0);
}
static constexpr parameter_type default_parameter() noexcept
{
return parameter_type{0, 0};
}
static void set_cutoff_ratio(const real_type rc)
{
return;
}
static constexpr real_type cutoff_ratio = real_type(1);
static constexpr real_type coef_at_cutoff = real_type(0);
public:
explicit StubPotential(const parameter_type& para) noexcept
: para_(para)
{}
~StubPotential() = default;
real_type potential(const real_type) const noexcept
{
return 0.0;
}
real_type derivative(const real_type) const noexcept
{
return 0.0;
}
template<typename T>
void initialize(const System<T>&) noexcept {return;}
template<typename T>
void update(const System<T>&) noexcept {return;}
static const char* name() noexcept {return "Stub";}
parameter_type parameter() const noexcept {return this->para_;}
real_type cutoff() const noexcept
{
return 0.0;
}
public:
// To culculate cutoff distance, we need to find the maximum sigma in the
// existing parameters. But the list of parameters will be given in a variety
// of ways, like Lorentz-Bertherot rule, combination table, or another way
// of combination rules.
// To find the maximum parameter, we need to provide a way to compare
// parameters. But the way depends on the functional form of a potential.
// So this comparator should be defined in a Potential class.
struct parameter_comparator
{
constexpr bool
operator()(const parameter_type& lhs, const parameter_type& rhs) const noexcept
{
return lhs.first < rhs.first;
}
};
private:
parameter_type para_;
};
template<typename realT>
constexpr typename StubPotential<realT>::real_type StubPotential<realT>::cutoff_ratio;
template<typename realT>
constexpr typename StubPotential<realT>::real_type StubPotential<realT>::coef_at_cutoff;
template<typename traitsT>
struct StubParameterList
: public ParameterListBase<traitsT, StubPotential<typename traitsT::real_type>>
{
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using potential_type = StubPotential<real_type>;
using base_type = ParameterListBase<traits_type, potential_type>;
using pair_parameter_type = typename potential_type::parameter_type;
using system_type = System<traits_type>;
using topology_type = Topology;
using molecule_id_type = typename topology_type::molecule_id_type;
using group_id_type = typename topology_type::group_id_type;
using connection_kind_type = typename topology_type::connection_kind_type;
using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;
using ignore_group_type = IgnoreGroup <group_id_type>;
using exclusion_list_type = ExclusionList<traits_type>;
explicit StubParameterList(const real_type cutoff_ratio,
const std::vector<std::size_t>& parameters,
const std::map<connection_kind_type, std::size_t>& exclusions,
ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)
: cutoff_(cutoff_ratio), participants_(parameters),
exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))
{}
real_type max_cutoff_length() const noexcept override {return this->cutoff_;}
pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept override
{
return pair_parameter_type{i, j};
}
void initialize(const system_type& sys, const topology_type& topol) noexcept override
{
this->update(sys, topol);
return;
}
void update(const system_type& sys, const topology_type& topol) noexcept override
{
// update exclusion list based on sys.topology()
exclusion_list_.make(sys, topol);
return;
}
std::vector<std::size_t> const& participants() const noexcept override
{
return this->participants_;
}
mjolnir::range<typename std::vector<std::size_t>::const_iterator>
leading_participants() const noexcept override
{
return mjolnir::make_range(participants_.begin(), std::prev(participants_.end()));
}
mjolnir::range<typename std::vector<std::size_t>::const_iterator>
possible_partners_of(const std::size_t participant_idx,
const std::size_t /*particle_idx*/) const noexcept override
{
return mjolnir::make_range(participants_.begin() + participant_idx + 1,
participants_.end());
}
bool has_interaction(const std::size_t i, const std::size_t j) const noexcept override
{
return (i < j);
}
std::string name() const {return "Stub";}
exclusion_list_type const& exclusion_list() const noexcept override
{
return exclusion_list_; // for testing
}
base_type* clone() const override
{
return new StubParameterList(*this);
}
private:
real_type cutoff_;
std::vector<std::size_t> participants_;
exclusion_list_type exclusion_list_;
};
} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<commit_msg>test: update stub_potential<commit_after>#ifndef MJOLNIR_TEST_UTIL_STUB_POTENTIAL_HPP
#define MJOLNIR_TEST_UTIL_STUB_POTENTIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/forcefield/global/ParameterList.hpp>
namespace mjolnir
{
namespace test
{
template<typename realT>
class StubPotential
{
public:
using real_type = realT;
struct parameter_type
{
std::size_t i;
std::size_t j;
};
static constexpr real_type default_cutoff() noexcept
{
return real_type(2.0);
}
public:
StubPotential() noexcept {}
~StubPotential() = default;
real_type potential(const real_type, const parameter_type&) const noexcept
{
return 0.0;
}
real_type derivative(const real_type, const parameter_type&) const noexcept
{
return 0.0;
}
template<typename T>
void initialize(const System<T>&) noexcept {return;}
template<typename T>
void update(const System<T>&) noexcept {return;}
template<typename InputIterator>
real_type max_cutoff(const InputIterator, const InputIterator) const noexcept
{
return 2.0;
}
real_type absolute_cutoff(const parameter_type&) const noexcept
{
return 2.0;
}
static const char* name() noexcept {return "Stub";}
};
template<typename traitsT>
struct StubParameterList
: public ParameterListBase<traitsT, StubPotential<typename traitsT::real_type>>
{
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using potential_type = StubPotential<real_type>;
using base_type = ParameterListBase<traits_type, potential_type>;
using pair_parameter_type = typename potential_type::parameter_type;
using system_type = System<traits_type>;
using topology_type = Topology;
using molecule_id_type = typename topology_type::molecule_id_type;
using group_id_type = typename topology_type::group_id_type;
using connection_kind_type = typename topology_type::connection_kind_type;
using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;
using ignore_group_type = IgnoreGroup <group_id_type>;
using exclusion_list_type = ExclusionList<traits_type>;
explicit StubParameterList(const double cutoff,
const std::vector<std::size_t>& parameters,
const std::map<connection_kind_type, std::size_t>& exclusions,
ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)
: cutoff_(cutoff), participants_(parameters),
exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))
{}
real_type max_cutoff_length() const noexcept override {return cutoff_;}
pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept override
{
return pair_parameter_type{i, j};
}
void initialize(const system_type& sys, const topology_type& topol,
const potential_type& pot) noexcept override
{
this->update(sys, topol, pot);
return;
}
void update(const system_type& sys, const topology_type& topol,
const potential_type&) noexcept override
{
// update exclusion list based on sys.topology()
exclusion_list_.make(sys, topol);
return;
}
std::vector<std::size_t> const& participants() const noexcept override
{
return this->participants_;
}
mjolnir::range<typename std::vector<std::size_t>::const_iterator>
leading_participants() const noexcept override
{
return mjolnir::make_range(participants_.begin(), std::prev(participants_.end()));
}
mjolnir::range<typename std::vector<std::size_t>::const_iterator>
possible_partners_of(const std::size_t participant_idx,
const std::size_t /*particle_idx*/) const noexcept override
{
return mjolnir::make_range(participants_.begin() + participant_idx + 1,
participants_.end());
}
bool has_interaction(const std::size_t i, const std::size_t j) const noexcept override
{
return (i < j);
}
std::string name() const {return "Stub";}
exclusion_list_type const& exclusion_list() const noexcept override
{
return exclusion_list_; // for testing
}
base_type* clone() const override
{
return new StubParameterList(*this);
}
private:
real_type cutoff_;
std::vector<std::size_t> participants_;
exclusion_list_type exclusion_list_;
};
} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "PIDController.h"
//------------------------------------------------------------------------------
// Constructors
//------------------------------------------------------------------------------
// Default constructor
PIDController::PIDController() {
this->setGains(0, 0, 0);
this->setInputLimits(-1, -1);
this->setOutputLimits(-1, -1);
this->reset();
}
// Just gains, no limits
PIDController::PIDController(double kp, double ki, double kd) {
this->setGains(kp, ki, kd);
this->setInputLimits(-1, -1);
this->setOutputLimits(-1, -1);
this->reset();
}
// Gains and output limits
PIDController::PIDController(double kp, double ki, double kd, double lowerOutputLimit, double upperOutputLimit) {
this->setGains(kp, ki, kd);
this->setInputLimits(-1, -1);
this->setOutputLimits(lowerOutputLimit, upperOutputLimit);
this->reset();
}
// All gains and limits
PIDController::PIDController(double kp, double ki, double kd, double lowerInputLimit, double upperInputLimit, double lowerOutputLimit, double upperOutputLimit) {
this->setGains(kp, ki, kd);
this->setInputLimits(lowerInputLimit, upperInputLimit);
this->setOutputLimits(lowerOutputLimit, upperOutputLimit);
this->reset();
}
// Copy constructor
PIDController::PIDController(const PIDController& orig) {
this->setGains(orig.kp, orig.ki, orig.kd);
this->setInputLimits(orig.lowerInputLimit, orig.upperInputLimit);
this->setOutputLimits(orig.lowerOutputLimit, orig.lowerInputLimit);
integrator = orig.integrator;
lastError = orig.lastError;
peakTime = orig.peakTime;
settlingTime = orig.settlingTime;
percentOvershoot = orig.percentOvershoot;
}
// Destructor
PIDController::~PIDController() {
}
//------------------------------------------------------------------------------
// Accessors
//------------------------------------------------------------------------------
double PIDController::getSetpoint() {
return setpoint;
}
double PIDController::getKp() {
return kp;
}
double PIDController::getKi() {
return ki;
}
double PIDController::getKd() {
return kd;
}
//------------------------------------------------------------------------------
// Mutators
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// targetSetpoint
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : setpoint
//
// This function sets the desired setpoint that the PID controller will
// attempt to track.
//------------------------------------------------------------------------------
void PIDController::targetSetpoint(double setpoint) {
this->setpoint = limiter(setpoint, lowerInputLimit, upperInputLimit);
peakTime = -1;
settlingTime = -1;
percentOvershoot = 0;
sample_timer.start();
performance_timer.start();
}
//------------------------------------------------------------------------------
// setGains
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : kp, ki, kd
//
// This function sets the control gains of the PID controller in order to
// achieve the desired performance characteristics.
//------------------------------------------------------------------------------
void PIDController::setGains(double kp, double ki, double kd) {
this->kp = kp;
this->ki = ki;
this->kd = kd;
}
//------------------------------------------------------------------------------
// setInputLimits
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : lowerInputLimit, upperInputLimit
//
// This function allows the user to set bounds on the setpoint to prevent
// undesirable behavior of the system.
//------------------------------------------------------------------------------
void PIDController::setInputLimits(double lowerInputLimit, double upperInputLimit) {
this->lowerInputLimit = lowerInputLimit;
this->upperInputLimit = upperInputLimit;
}
//------------------------------------------------------------------------------
// setOutputLimits
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : lowerOutputLimit, upperOutputLimit
//
// This function allows to user to set bounds on the control variable to prevent
// undesirable behavior of the system.
//------------------------------------------------------------------------------
void PIDController::setOutputLimits(double lowerOutputLimit, double upperOutputLimit) {
this->lowerOutputLimit = lowerOutputLimit;
this->upperOutputLimit = upperOutputLimit;
}
double PIDController::limiter(double value, double lowerLimit, double upperLimit) {
if (lowerLimit == upperLimit) {
return value;
}
else if(value < lowerLimit) {
return lowerLimit;
}
else if(value > upperLimit) {
return upperLimit;
}
else
return value;
}
void PIDController::reset() {
setpoint = 0;
integrator = 0;
lastError = 0;
peakTime = -1;
settlingTime = -1;
percentOvershoot = 0;
sample_timer.stop();
performance_timer.stop();
}
bool PIDController::hasSettled() {
if(settlingTime != -1) {
return true;
}
else {
return false;
}
}
double PIDController::calc(double processVariable) {
sample_timer.stop();
double percent = (processVariable/setpoint) - 1;
if(percent > percentOvershoot && percent > 0)
{
percentOvershoot = processVariable/setpoint;
peakTime = (performance_timer.elapsed().wall)/1e9;
}
if(abs(percent) < 0.05 && settlingTime == -1)
{
performance_timer.stop();
settlingTime = (performance_timer.elapsed().wall)/1e9;
std::cout << "Peak Time Tp: " << peakTime << std::endl;
std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl;
std::cout << "Settling Time Ts" << settlingTime << std::endl;
}
double error = setpoint - processVariable;
double samplingTime = (sample_timer.elapsed().wall)/1e9;
double differentiator = (error - lastError)/samplingTime;
integrator += (error * samplingTime);
double controlVariable = kp * error + ki * integrator + kd * differentiator;
controlVariable = limiter(controlVariable, lowerOutputLimit, upperOutputLimit);
lastError = error;
sample_timer.start();
return controlVariable;
}
<commit_msg>Finish adding member function comments<commit_after>//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "PIDController.h"
//------------------------------------------------------------------------------
// Constructors
//------------------------------------------------------------------------------
// Default constructor
PIDController::PIDController() {
this->setGains(0, 0, 0);
this->setInputLimits(-1, -1);
this->setOutputLimits(-1, -1);
this->reset();
}
// Just gains, no limits
PIDController::PIDController(double kp, double ki, double kd) {
this->setGains(kp, ki, kd);
this->setInputLimits(-1, -1);
this->setOutputLimits(-1, -1);
this->reset();
}
// Gains and output limits
PIDController::PIDController(double kp, double ki, double kd, double lowerOutputLimit, double upperOutputLimit) {
this->setGains(kp, ki, kd);
this->setInputLimits(-1, -1);
this->setOutputLimits(lowerOutputLimit, upperOutputLimit);
this->reset();
}
// All gains and limits
PIDController::PIDController(double kp, double ki, double kd, double lowerInputLimit, double upperInputLimit, double lowerOutputLimit, double upperOutputLimit) {
this->setGains(kp, ki, kd);
this->setInputLimits(lowerInputLimit, upperInputLimit);
this->setOutputLimits(lowerOutputLimit, upperOutputLimit);
this->reset();
}
// Copy constructor
PIDController::PIDController(const PIDController& orig) {
this->setGains(orig.kp, orig.ki, orig.kd);
this->setInputLimits(orig.lowerInputLimit, orig.upperInputLimit);
this->setOutputLimits(orig.lowerOutputLimit, orig.lowerInputLimit);
integrator = orig.integrator;
lastError = orig.lastError;
peakTime = orig.peakTime;
settlingTime = orig.settlingTime;
percentOvershoot = orig.percentOvershoot;
}
// Destructor
PIDController::~PIDController() {
}
//------------------------------------------------------------------------------
// Accessors
//------------------------------------------------------------------------------
double PIDController::getSetpoint() {
return setpoint;
}
double PIDController::getKp() {
return kp;
}
double PIDController::getKi() {
return ki;
}
double PIDController::getKd() {
return kd;
}
//------------------------------------------------------------------------------
// Mutators
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// targetSetpoint
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : setpoint
//
// This function sets the desired setpoint that the PID controller will
// attempt to track.
//------------------------------------------------------------------------------
void PIDController::targetSetpoint(double setpoint) {
this->setpoint = limiter(setpoint, lowerInputLimit, upperInputLimit);
peakTime = -1;
settlingTime = -1;
percentOvershoot = 0;
sample_timer.start();
performance_timer.start();
}
//------------------------------------------------------------------------------
// setGains
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : kp, ki, kd
//
// This function sets the control gains of the PID controller in order to
// achieve the desired performance characteristics.
//------------------------------------------------------------------------------
void PIDController::setGains(double kp, double ki, double kd) {
this->kp = kp;
this->ki = ki;
this->kd = kd;
}
//------------------------------------------------------------------------------
// setInputLimits
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : lowerInputLimit, upperInputLimit
//
// This function allows the user to set bounds on the setpoint to prevent
// undesirable behavior of the system.
//------------------------------------------------------------------------------
void PIDController::setInputLimits(double lowerInputLimit, double upperInputLimit) {
this->lowerInputLimit = lowerInputLimit;
this->upperInputLimit = upperInputLimit;
}
//------------------------------------------------------------------------------
// setOutputLimits
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : lowerOutputLimit, upperOutputLimit
//
// This function allows the user to set bounds on the control variable to
// prevent undesirable behavior of the system.
//------------------------------------------------------------------------------
void PIDController::setOutputLimits(double lowerOutputLimit, double upperOutputLimit) {
this->lowerOutputLimit = lowerOutputLimit;
this->upperOutputLimit = upperOutputLimit;
}
//------------------------------------------------------------------------------
// Other Functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// limiter
//------------------------------------------------------------------------------
//
// Return Value : double
// Parameters : value, lowerLimit, upperLimit
//
// This function compares the input 'value' to the specified limits. If the
// value exceeds the limits, the value is capped to one of the limits.
//------------------------------------------------------------------------------
double PIDController::limiter(double value, double lowerLimit, double upperLimit) {
if (lowerLimit == upperLimit) {
return value;
}
else if(value < lowerLimit) {
return lowerLimit;
}
else if(value > upperLimit) {
return upperLimit;
}
else
return value;
}
//------------------------------------------------------------------------------
// reset
//------------------------------------------------------------------------------
//
// Return Value : None
// Parameters : None
//
// This function initializes the PID controller to the default values.
//------------------------------------------------------------------------------
void PIDController::reset() {
setpoint = 0;
integrator = 0;
lastError = 0;
peakTime = -1;
settlingTime = -1;
percentOvershoot = 0;
sample_timer.stop();
performance_timer.stop();
}
//------------------------------------------------------------------------------
// hasSettled
//------------------------------------------------------------------------------
//
// Return Value : bool
// Parameters : None
//
// This function returns true only when the PID controller has stabilized to
// within 5% of its final value.
//------------------------------------------------------------------------------
bool PIDController::hasSettled() {
if(settlingTime != -1) {
return true;
}
else {
return false;
}
}
//------------------------------------------------------------------------------
// calc
//------------------------------------------------------------------------------
//
// Return Value : double
// Parameters : processVariable
//
// This function calculates the next output value of the PID controller, given
// the current setpoint, elasped time, and feedback (processVariable). It also
// keeps track of peak time, settling time, and percent overshoot for quickly
// assessing the current performance of the controller.
//------------------------------------------------------------------------------
double PIDController::calc(double processVariable) {
sample_timer.stop();
double percent = (processVariable/setpoint) - 1;
if(percent > percentOvershoot && percent > 0)
{
percentOvershoot = processVariable/setpoint;
peakTime = (performance_timer.elapsed().wall)/1e9;
}
if(abs(percent) < 0.05 && settlingTime == -1)
{
performance_timer.stop();
settlingTime = (performance_timer.elapsed().wall)/1e9;
std::cout << "Peak Time Tp: " << peakTime << std::endl;
std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl;
std::cout << "Settling Time Ts" << settlingTime << std::endl;
}
double error = setpoint - processVariable;
double samplingTime = (sample_timer.elapsed().wall)/1e9;
double differentiator = (error - lastError)/samplingTime;
integrator += (error * samplingTime);
double controlVariable = kp * error + ki * integrator + kd * differentiator;
controlVariable = limiter(controlVariable, lowerOutputLimit, upperOutputLimit);
lastError = error;
sample_timer.start();
return controlVariable;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adminpages.hxx,v $
*
* $Revision: 1.31 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:24:24 $
*
* 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 _DBAUI_ADMINPAGES_HXX_
#define _DBAUI_ADMINPAGES_HXX_
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
class NumericField;
class Edit;
//.........................................................................
namespace dbaui
{
//.........................................................................
/// helper class to wrap the savevalue and disable call
class SAL_NO_VTABLE ISaveValueWrapper
{
public:
virtual bool SaveValue() = 0;
virtual bool Disable() = 0;
};
template < class T > class OSaveValueWrapper : public ISaveValueWrapper
{
T* m_pSaveValue;
public:
OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
{ OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }
virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl
virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
};
template < class T > class ODisableWrapper : public ISaveValueWrapper
{
T* m_pSaveValue;
public:
ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
{ OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }
virtual bool SaveValue() { return true;} // bool return value only for stl
virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
};
struct TSaveValueWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
return lhs->SaveValue();
}
};
struct TDisableWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
return lhs->Disable();
}
};
struct TDeleteWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
delete lhs;
return true;
}
};
//=========================================================================
//= OGenericAdministrationPage
//=========================================================================
class IDatabaseSettingsDialog;
class IItemSetHelper;
class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage
{
private:
Link m_aModifiedHandler; /// to be called if something on the page has been modified
sal_Bool m_abEnableRoadmap;
protected:
IDatabaseSettingsDialog* m_pAdminDialog;
IItemSetHelper* m_pItemSetHelper;
FixedText* m_pFT_HeaderText;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
public:
OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet);
~OGenericAdministrationPage();
/// set a handler which gets called every time something on the page has been modified
void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; }
/** Sets the ParentDialog
@param _pAdminDialog
the ParentDialog
@param _pItemSetHelper
the itemset helper
*/
inline void SetAdminDialog(IDatabaseSettingsDialog* _pDialog,IItemSetHelper* _pItemSetHelper)
{
OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!");
m_pAdminDialog = _pDialog;
m_pItemSetHelper = _pItemSetHelper;
}
/** Sets the ServiceFactory
@param _rxORB
The service factory.
*/
virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
{
m_xORB = _rxORB;
}
/** opens a dialog filled with all data sources available for this type and
returns the selected on.
@param _eType
The type for which the data source dialog should be opened.
@param _sReturn
<OUT/> contains the selected name.
@return
<FALSE/> if an error occured, otherwise <TRUE/>
*/
sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr);
// svt::IWizardPage
virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess );
virtual void initializePage();
virtual sal_Bool commitPage(COMMIT_REASON _eReason);
void SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; }
bool GetRoadmapStateValue() const { return m_abEnableRoadmap; }
protected:
/// default implementation: call FillItemSet, call prepareLeave,
virtual int DeactivatePage(SfxItemSet* pSet);
using SfxTabPage::DeactivatePage;
/// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False
virtual void Reset(const SfxItemSet& _rCoreAttrs);
/// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True
virtual void ActivatePage(const SfxItemSet& _rSet);
// TabPage overridables
virtual void ActivatePage();
protected:
void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); }
/// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True
virtual sal_Bool prepareLeave() { return sal_True; }
/** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set
@param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls
*/
virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);
/// analyze the invalid and the readonly flag which may be present in the set
void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly);
/** will be called inside <method>implInitControls</method> to save the value if necessary
@param _rControlList
The list must be filled with the controls.
It is not allowed to clear the list before pusching data into it.
*/
virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;
/** will be called inside <method>implInitControls</method> to disable if necessary
@param _rControlList
The list must be filled with the controls.
It is not allowed to clear the list before pusching data into it.
*/
virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;
/** fills the Boolean value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pCheckBox
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
*/
void fillBool(SfxItemSet& _rSet,CheckBox* _pCheckBox,USHORT _nID,sal_Bool& _bChangedSomething);
/** fills the int value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pEdit
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
*/
void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);
/** fills the String value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pEdit
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
*/
void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);
// used to set the right Pane header of a wizard to bold
void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD);
void SetHeaderText( USHORT _nFTResId, USHORT _StringResId);
Point MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift);
protected:
/** This link be used for controls where the tabpage does not need to take any special action when the control
is modified. The implementation just calls callModifiedHdl.
*/
DECL_LINK(OnControlModified, Control*);
DECL_LINK(OnTestConnectionClickHdl,PushButton*);
/// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method>
virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); }
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_ADMINPAGES_HXX_
<commit_msg>INTEGRATION: CWS dba24b (1.31.46); FILE MERGED 2007/08/27 10:49:13 fs 1.31.46.1: #i80930# _bRevertValue parameter to fillBool<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adminpages.hxx,v $
*
* $Revision: 1.32 $
*
* last change: $Author: hr $ $Date: 2007-11-01 15:08:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBAUI_ADMINPAGES_HXX_
#define _DBAUI_ADMINPAGES_HXX_
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
class NumericField;
class Edit;
//.........................................................................
namespace dbaui
{
//.........................................................................
/// helper class to wrap the savevalue and disable call
class SAL_NO_VTABLE ISaveValueWrapper
{
public:
virtual bool SaveValue() = 0;
virtual bool Disable() = 0;
};
template < class T > class OSaveValueWrapper : public ISaveValueWrapper
{
T* m_pSaveValue;
public:
OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
{ OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }
virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl
virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
};
template < class T > class ODisableWrapper : public ISaveValueWrapper
{
T* m_pSaveValue;
public:
ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
{ OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }
virtual bool SaveValue() { return true;} // bool return value only for stl
virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
};
struct TSaveValueWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
return lhs->SaveValue();
}
};
struct TDisableWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
return lhs->Disable();
}
};
struct TDeleteWrapperFunctor : public unary_function< ISaveValueWrapper, bool>
{
bool operator() (ISaveValueWrapper* lhs)
{
delete lhs;
return true;
}
};
//=========================================================================
//= OGenericAdministrationPage
//=========================================================================
class IDatabaseSettingsDialog;
class IItemSetHelper;
class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage
{
private:
Link m_aModifiedHandler; /// to be called if something on the page has been modified
sal_Bool m_abEnableRoadmap;
protected:
IDatabaseSettingsDialog* m_pAdminDialog;
IItemSetHelper* m_pItemSetHelper;
FixedText* m_pFT_HeaderText;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
public:
OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet);
~OGenericAdministrationPage();
/// set a handler which gets called every time something on the page has been modified
void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; }
/** Sets the ParentDialog
@param _pAdminDialog
the ParentDialog
@param _pItemSetHelper
the itemset helper
*/
inline void SetAdminDialog(IDatabaseSettingsDialog* _pDialog,IItemSetHelper* _pItemSetHelper)
{
OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!");
m_pAdminDialog = _pDialog;
m_pItemSetHelper = _pItemSetHelper;
}
/** Sets the ServiceFactory
@param _rxORB
The service factory.
*/
virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
{
m_xORB = _rxORB;
}
/** opens a dialog filled with all data sources available for this type and
returns the selected on.
@param _eType
The type for which the data source dialog should be opened.
@param _sReturn
<OUT/> contains the selected name.
@return
<FALSE/> if an error occured, otherwise <TRUE/>
*/
sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr);
// svt::IWizardPage
virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess );
virtual void initializePage();
virtual sal_Bool commitPage(COMMIT_REASON _eReason);
void SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; }
bool GetRoadmapStateValue() const { return m_abEnableRoadmap; }
protected:
/// default implementation: call FillItemSet, call prepareLeave,
virtual int DeactivatePage(SfxItemSet* pSet);
using SfxTabPage::DeactivatePage;
/// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False
virtual void Reset(const SfxItemSet& _rCoreAttrs);
/// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True
virtual void ActivatePage(const SfxItemSet& _rSet);
// TabPage overridables
virtual void ActivatePage();
protected:
void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); }
/// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True
virtual sal_Bool prepareLeave() { return sal_True; }
/** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set
@param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls
*/
virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);
/// analyze the invalid and the readonly flag which may be present in the set
void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly);
/** will be called inside <method>implInitControls</method> to save the value if necessary
@param _rControlList
The list must be filled with the controls.
It is not allowed to clear the list before pusching data into it.
*/
virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;
/** will be called inside <method>implInitControls</method> to disable if necessary
@param _rControlList
The list must be filled with the controls.
It is not allowed to clear the list before pusching data into it.
*/
virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;
/** fills the Boolean value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pCheckBox
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
@param _bRevertValue
set to <TRUE/> if the display value should be reverted before putting it into the set
*/
void fillBool( SfxItemSet& _rSet, CheckBox* _pCheckBox, USHORT _nID, sal_Bool& _bChangedSomething, bool _bRevertValue = false);
/** fills the int value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pEdit
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
*/
void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);
/** fills the String value into the item set when the value changed.
@param _rSet
The item set where to put the new value into.
@param _pEdit
The check box which is checked.
@param _nID
The id in the itemset to set whith the new value.
@param _bChangedSomething
<TRUE/> if something changed otherwise <FALSE/>
*/
void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);
// used to set the right Pane header of a wizard to bold
void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD);
void SetHeaderText( USHORT _nFTResId, USHORT _StringResId);
Point MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift);
protected:
/** This link be used for controls where the tabpage does not need to take any special action when the control
is modified. The implementation just calls callModifiedHdl.
*/
DECL_LINK(OnControlModified, Control*);
DECL_LINK(OnTestConnectionClickHdl,PushButton*);
/// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method>
virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); }
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_ADMINPAGES_HXX_
<|endoftext|> |
<commit_before>/*
*
* Author: Philipp Zschoche, https://zschoche.org
*
*/
#ifndef __FILESYSTEM_HPP__
#define __FILESYSTEM_HPP__
#include "device_io.hpp"
#include <array>
namespace ext2 {
/*
* implements the device concept
*/
template <typename Filesystem> class inode : public inode_base<typename Filesystem::device_type> {
public:
typedef Filesystem fs_type;
private:
fs_type *fs;
uint32_t get_block_id(uint32_t block_index) const {
if (block_index < 12) {
// direct pointer
return this->data.block_pointer_direct[block_index];
} else if (block_index < 268) {
block_index -= 12;
uint32_t result;
auto blockid = this->data.block_pointer_indirect[0];
detail::read_from_device(*fs->device(), fs->to_address(blockid, block_index * sizeof(uint32_t)), result);
return result;
} else {
throw "this is not ready yet";
return 0; // TODO: implement
}
}
public:
inode(fs_type *fs, uint64_t offset) : inode_base<typename Filesystem::device_type>(fs->device(), offset), fs(fs) {}
inline bool is_directory() const { return detail::has_flag(this->data.type, detail::directory); }
inline bool is_regular_file() const { return detail::has_flag(this->data.type, detail::regular_file); }
inline bool is_symbolic_link() const { return detail::has_flag(this->data.type, detail::symbolic_link); }
inline uint64_t size() const {
if (is_regular_file() && fs->large_files()) {
return (static_cast<uint64_t>(this->data.dir_acl) << 32) | (this->data.size);
} else {
return this->data.size;
}
}
void read(uint64_t offset, char *buffer, uint64_t length) {
auto buffer_offset = 0;
do {
auto block_index = offset / fs->block_size();
auto block_offset = offset % fs->block_size();
auto block_length = std::min(fs->block_size() - block_offset, length);
fs->device()->read(fs->to_address(get_block_id(block_index), block_offset), &buffer[buffer_offset], block_length);
buffer_offset += block_length;
offset += block_length;
length -= block_length;
} while (length > 0);
}
void write(uint64_t offset, const char *buffer, uint64_t length) {} // TODO: implement!
inline fs_type *get_fs() { return fs; }
};
template <typename OStream, typename Inode> void read_inode_content(OStream &os, Inode& inode) {
std::array<char, 255> buffer;
auto offset = 0;
const auto size = inode.size();
do {
auto length = std::min<uint64_t>(size - offset, buffer.size());
inode.read(offset, buffer.data(), length);
os << std::string(buffer.data(), length);
offset += length;
} while (offset < size);
}
typedef std::vector<detail::directory_entry> directory_entry_list;
namespace inodes {
template <typename Filesystem> struct file : inode<Filesystem> {
template <typename OStream> void read_full_file(OStream &os) {
read_inode_content(os, *this);
}
};
template <typename OStream, typename Filesystem> OStream &operator<<(OStream &os, file<Filesystem> &f) {
f.read_full_file(os);
return os;
}
template <typename Filesystem> struct character_device : inode<Filesystem> {};
template <typename Filesystem> struct block_device : inode<Filesystem> {};
template <typename Filesystem> struct fifo : inode<Filesystem> {};
template <typename Filesystem> struct symbolic_link : inode<Filesystem> {
std::string get_target() {
/* http://www.nongnu.org/ext2-doc/ext2.html#DEF-SYMBOLIC-LINKS */
if(this->size() < 60) {
const char* cstring = reinterpret_cast<char*>(&(this->data.block_pointer_direct[0]));
std::string result(cstring, this->size());
return result;
}
std::stringstream ss;
read_inode_content(ss, *this);
return ss.str();
}
};
template <typename Filesystem> struct directory : inode<Filesystem> {
directory_entry_list read_entrys() {
auto offset = 0;
directory_entry_list result;
result.reserve(8);
do {
detail::directory_entry entry;
detail::read_from_device(*this, offset, entry, 8);
if (entry.inode_id == 0)
break;
offset += 8;
entry.name.resize(entry.name_size);
this->read(offset, const_cast<char *>(entry.name.c_str()), entry.name_size);
offset += entry.size - 8;
result.push_back(std::move(entry));
} while (offset < this->size());
return result;
}
void write_entrys(const directory_entry_list &entrys) {
// TODO
}
};
} /* namespace inodes */
template <typename Filesystem> inodes::directory<Filesystem> *to_directory(inode<Filesystem> *from) {
if (from->is_directory())
return static_cast<inodes::directory<Filesystem> *>(from);
else
return nullptr;
}
template <typename Filesystem> inodes::file<Filesystem> *to_file(inode<Filesystem> *from) {
if (from->is_regular_file())
return static_cast<inodes::file<Filesystem> *>(from);
else
return nullptr;
}
template <typename Filesystem> inodes::symbolic_link<Filesystem> *to_symbolic_link(inode<Filesystem> *from) {
if (from->is_symbolic_link())
return static_cast<inodes::symbolic_link<Filesystem> *>(from);
else
return nullptr;
}
typedef std::vector<std::pair<uint64_t, std::string *> > path;
template <typename OStream> OStream &operator<<(OStream &os, const path &p) {
for (const auto &item : p) {
os << '/' << *item.second;
}
return os;
}
template <typename Device> class filesystem {
public:
typedef typename superblock<Device>::device_type device_type;
typedef inode<filesystem<Device> > inode_type;
typedef inodes::directory<filesystem<Device> > directory_type;
typedef inodes::file<filesystem<Device> > file_type;
typedef group_descriptor_table<Device> gd_table_type;
private:
superblock<Device> super_block;
gd_table_type gd_table;
uint32_t blocksize;
public:
filesystem(Device &d, uint64_t superblock_offset = 1024) : super_block(d, superblock_offset) {}
inline device_type *device() { return super_block.device(); }
void load() {
super_block.load();
blocksize = super_block.data.block_size();
gd_table = read_group_descriptor_table(super_block);
}
template <typename OStream> OStream &dump(OStream &os) const {
super_block.data.dump(os);
for (const auto &item : gd_table) {
item.data.dump(os);
}
return os;
}
inode_type get_inode(uint32_t inodeid) {
auto block_group_id = (inodeid - 1) / super_block.data.inodes_per_group;
auto index = (inodeid - 1) % super_block.data.inodes_per_group;
auto block_id = (index * super_block.data.inode_size) / block_size();
auto block_offset = (index * super_block.data.inode_size) - (block_id * block_size());
block_id += gd_table[block_group_id].data.address_inode_table;
inode_type result(this, to_address(block_id, block_offset));
result.load();
return result;
}
inode_type get_root() { return get_inode(2); }
inline uint64_t to_address(uint32_t blockid, uint32_t block_offset) const { return (blockid * block_size()) + block_offset; }
inline bool large_files() const { return super_block.data.large_files(); }
inline uint32_t block_size() const { return blocksize; }
};
template <typename Device> filesystem<Device> read_filesystem(Device &d) {
filesystem<Device> result(d);
result.load();
return result;
}
} /* namespace ext2 */
#endif /* __FILESYSTEM_HPP__ */
<commit_msg>Added a type for paths<commit_after>/*
*
* Author: Philipp Zschoche, https://zschoche.org
*
*/
#ifndef __FILESYSTEM_HPP__
#define __FILESYSTEM_HPP__
#include "device_io.hpp"
#include <array>
#include <boost/algorithm/string/split.hpp>
namespace ext2 {
/*
* implements the device concept
*/
template <typename Filesystem> class inode : public inode_base<typename Filesystem::device_type> {
public:
typedef Filesystem fs_type;
private:
fs_type *fs;
uint32_t get_block_id(uint32_t block_index) const {
if (block_index < 12) {
// direct pointer
return this->data.block_pointer_direct[block_index];
} else if (block_index < 268) {
block_index -= 12;
uint32_t result;
auto blockid = this->data.block_pointer_indirect[0];
detail::read_from_device(*fs->device(), fs->to_address(blockid, block_index * sizeof(uint32_t)), result);
return result;
} else {
throw "this is not ready yet";
return 0; // TODO: implement
}
}
public:
inode(fs_type *fs, uint64_t offset) : inode_base<typename Filesystem::device_type>(fs->device(), offset), fs(fs) {}
inline bool is_directory() const { return detail::has_flag(this->data.type, detail::directory); }
inline bool is_regular_file() const { return detail::has_flag(this->data.type, detail::regular_file); }
inline bool is_symbolic_link() const { return detail::has_flag(this->data.type, detail::symbolic_link); }
inline uint64_t size() const {
if (is_regular_file() && fs->large_files()) {
return (static_cast<uint64_t>(this->data.dir_acl) << 32) | (this->data.size);
} else {
return this->data.size;
}
}
void read(uint64_t offset, char *buffer, uint64_t length) {
auto buffer_offset = 0;
do {
auto block_index = offset / fs->block_size();
auto block_offset = offset % fs->block_size();
auto block_length = std::min(fs->block_size() - block_offset, length);
fs->device()->read(fs->to_address(get_block_id(block_index), block_offset), &buffer[buffer_offset], block_length);
buffer_offset += block_length;
offset += block_length;
length -= block_length;
} while (length > 0);
}
void write(uint64_t offset, const char *buffer, uint64_t length) {} // TODO: implement!
inline fs_type *get_fs() { return fs; }
};
template <typename OStream, typename Inode> void read_inode_content(OStream &os, Inode &inode) {
std::array<char, 255> buffer;
auto offset = 0;
const auto size = inode.size();
do {
auto length = std::min<uint64_t>(size - offset, buffer.size());
inode.read(offset, buffer.data(), length);
os << std::string(buffer.data(), length);
offset += length;
} while (offset < size);
}
typedef std::vector<detail::directory_entry> directory_entry_list;
namespace inodes {
template <typename Filesystem> struct file : inode<Filesystem> {
template <typename OStream> void read_full_file(OStream &os) { read_inode_content(os, *this); }
};
template <typename OStream, typename Filesystem> OStream &operator<<(OStream &os, file<Filesystem> &f) {
f.read_full_file(os);
return os;
}
template <typename Filesystem> struct character_device : inode<Filesystem> {};
template <typename Filesystem> struct block_device : inode<Filesystem> {};
template <typename Filesystem> struct fifo : inode<Filesystem> {};
template <typename Filesystem> struct symbolic_link : inode<Filesystem> {
std::string get_target() {
/* http://www.nongnu.org/ext2-doc/ext2.html#DEF-SYMBOLIC-LINKS */
if (this->size() < 60) {
const char *cstring = reinterpret_cast<char *>(&(this->data.block_pointer_direct[0]));
std::string result(cstring, this->size());
return result;
}
std::stringstream ss;
read_inode_content(ss, *this);
return ss.str();
}
};
template <typename Filesystem> struct directory : inode<Filesystem> {
directory_entry_list read_entrys() {
auto offset = 0;
directory_entry_list result;
result.reserve(8);
do {
detail::directory_entry entry;
detail::read_from_device(*this, offset, entry, 8);
if (entry.inode_id == 0)
break;
offset += 8;
entry.name.resize(entry.name_size);
this->read(offset, const_cast<char *>(entry.name.c_str()), entry.name_size);
offset += entry.size - 8;
result.push_back(std::move(entry));
} while (offset < this->size());
return result;
}
void write_entrys(const directory_entry_list &entrys) {
// TODO
}
};
} /* namespace inodes */
template <typename Filesystem> inodes::directory<Filesystem> *to_directory(inode<Filesystem> *from) {
if (from->is_directory())
return static_cast<inodes::directory<Filesystem> *>(from);
else
return nullptr;
}
template <typename Filesystem> inodes::file<Filesystem> *to_file(inode<Filesystem> *from) {
if (from->is_regular_file())
return static_cast<inodes::file<Filesystem> *>(from);
else
return nullptr;
}
template <typename Filesystem> inodes::symbolic_link<Filesystem> *to_symbolic_link(inode<Filesystem> *from) {
if (from->is_symbolic_link())
return static_cast<inodes::symbolic_link<Filesystem> *>(from);
else
return nullptr;
}
struct path {
// typedef boost::iterator_range<std::string::iterator> range_type;
typedef std::vector<std::string> vec_type;
std::string str;
vec_type vec;
inline bool is_relative() const { return !(!str.empty() && str[0] == '/'); }
};
inline path path_from_string(const std::string &p) {
path result{p};
if (result.str.size() > 3) {
auto first = result.str.begin();
auto last = --(result.str.end());
if (*first == '/')
first++;
if (*last != '/')
last++;
auto range = boost::make_iterator_range(first, last);
boost::split(result.vec, range, [](auto c) { return c == '/'; });
}
return result;
}
template <typename Device> class filesystem {
public:
typedef typename superblock<Device>::device_type device_type;
typedef inode<filesystem<Device> > inode_type;
typedef inodes::directory<filesystem<Device> > directory_type;
typedef inodes::file<filesystem<Device> > file_type;
typedef group_descriptor_table<Device> gd_table_type;
private:
superblock<Device> super_block;
gd_table_type gd_table;
uint32_t blocksize;
public:
filesystem(Device &d, uint64_t superblock_offset = 1024) : super_block(d, superblock_offset) {}
inline device_type *device() { return super_block.device(); }
void load() {
super_block.load();
blocksize = super_block.data.block_size();
gd_table = read_group_descriptor_table(super_block);
}
template <typename OStream> OStream &dump(OStream &os) const {
super_block.data.dump(os);
for (const auto &item : gd_table) {
item.data.dump(os);
}
return os;
}
inode_type get_inode(uint32_t inodeid) {
auto block_group_id = (inodeid - 1) / super_block.data.inodes_per_group;
auto index = (inodeid - 1) % super_block.data.inodes_per_group;
auto block_id = (index * super_block.data.inode_size) / block_size();
auto block_offset = (index * super_block.data.inode_size) - (block_id * block_size());
block_id += gd_table[block_group_id].data.address_inode_table;
inode_type result(this, to_address(block_id, block_offset));
result.load();
return result;
}
inode_type get_root() { return get_inode(2); }
inline uint64_t to_address(uint32_t blockid, uint32_t block_offset) const { return (blockid * block_size()) + block_offset; }
inline bool large_files() const { return super_block.data.large_files(); }
inline uint32_t block_size() const { return blocksize; }
};
template <typename Device> filesystem<Device> read_filesystem(Device &d) {
filesystem<Device> result(d);
result.load();
return result;
}
} /* namespace ext2 */
#endif /* __FILESYSTEM_HPP__ */
<|endoftext|> |
<commit_before>#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPainter>
#include <QPrinter>
#include <QImage>
#include <qgraphicseffect.h>
#include <copasi.h>
#include <qlayout/qlayoutscene.h>
#include <qlayout/qcopasieffect.h>
#include <qlayout/qlabelgraphicsitem.h>
#include <qlayout/qstyledgraphicsitem.h>
#include <qlayout/qconnectiongraphicsitem.h>
#include <qlayout/qrenderconverter.h>
#include <layout/CLayout.h>
#include <layout/CLGlyphs.h>
#include <layout/CLText.h>
#include <layout/CLReactionGlyph.h>
#include <layout/CLRenderResolver.h>
#include <layout/CLGlobalRenderInformation.h>
#include <layout/CListOfLayouts.h>
#include <layout/CLLocalRenderInformation.h>
#include <CopasiDataModel/CCopasiDataModel.h>
QLayoutScene::QLayoutScene(CLayout* layout, CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
: QGraphicsScene()
, mpLayout(layout)
, mpRender(renderInformation)
, mpResolver(NULL)
{
initializeResolver(model, renderInformation);
}
void QLayoutScene::setLayout(CLayout *layout, CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
mpLayout = layout;
setRenderInformation(model, renderInformation);
}
void QLayoutScene::setRenderInformation(CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
initializeResolver(model, renderInformation);
}
const CLayout* QLayoutScene::getCurrentLayout() const
{
return mpLayout;
}
const CLRenderInformationBase* QLayoutScene::getCurrentRenderInfo() const
{
return mpRender;
}
void QLayoutScene::saveToFile(const std::string& fileName, const std::string& fileType /*= "pdf"*/)
{
if (fileType == "pdf")
{
QPrinter printer (QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName.c_str());
QPainter painter(&printer);
painter.setRenderHints(
QPainter::Antialiasing |QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform);
render(&painter, QRect(), itemsBoundingRect());
painter.end();
}
else
{
const int scale = 2;
QImage image(QSize(width()*scale, height()*scale), QImage::Format_ARGB32);
QPainter painter(&image);
painter.setRenderHints(
QPainter::Antialiasing |QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform);
render(&painter, image.rect(), itemsBoundingRect());
painter.end();
image.save(fileName.c_str(), fileType.c_str());
}
}
void QLayoutScene::initializeResolver(CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
if (model == NULL)
return;
if (renderInformation == NULL)
{
if (mpLayout != NULL && mpLayout->getListOfLocalRenderInformationObjects().size() > 0)
mpRender = mpLayout->getListOfLocalRenderInformationObjects()[0];
else if (model->getListOfLayouts()->getListOfGlobalRenderInformationObjects().size() > 0)
mpRender = model->getListOfLayouts()->getListOfGlobalRenderInformationObjects()[0];
}
else
mpRender = renderInformation;
if (mpLayout == NULL || mpRender == NULL)
return;
CLLocalRenderInformation* local = dynamic_cast<CLLocalRenderInformation*>(mpRender);
if (local != NULL)
mpResolver = new CLRenderResolver(*local, mpLayout->getListOfLocalRenderInformationObjects(), model->getListOfLayouts()->getListOfGlobalRenderInformationObjects());
else
mpResolver = new CLRenderResolver(*dynamic_cast<CLGlobalRenderInformation*>(mpRender), model->getListOfLayouts()->getListOfGlobalRenderInformationObjects());
}
void QLayoutScene::setResolver(const CLRenderResolver* resolver)
{
mpResolver = resolver;
}
const CLRenderResolver* QLayoutScene::getResolver() const
{
return mpResolver;
}
QLayoutScene::~QLayoutScene()
{
}
void QLayoutScene::recreate()
{
fillFromLayout(mpLayout);
invalidate();
}
void QLayoutScene::addGlyph(const CLGraphicalObject* go)
{
if (go == NULL) return;
const CLGlyphWithCurve* curveGlyph = dynamic_cast<const CLGlyphWithCurve*>(go);
const CLReactionGlyph* reaction = dynamic_cast<const CLReactionGlyph*>(go);
const CLTextGlyph* text = dynamic_cast<const CLTextGlyph*>(go);
const CLGeneralGlyph* general = dynamic_cast<const CLGeneralGlyph*>(go);
QGraphicsItem *item = NULL;
if (curveGlyph != NULL)
{
if (curveGlyph->getCurve().getNumCurveSegments() > 0 || reaction != NULL || general != NULL)
item = new QConnectionGraphicsItem(curveGlyph,
mpResolver == NULL ? NULL : mpResolver);
}
else if (text != NULL)
{
item = new QLabelGraphicsItem(text, mpResolver == NULL ? NULL : mpResolver);
}
else
{
item = new QStyledGraphicsItem(go, mpResolver == NULL ? NULL : mpResolver);
}
if (item != NULL)
{
CCopasiObject* obj = go->getModelObject();
if (obj != NULL && text == NULL)
{
item->setData(COPASI_OBJECT_CN, QString(obj->getCN().c_str()));
mItems[obj->getCN()]= item;
}
addItem(item);
}
}
QGraphicsItem* QLayoutScene::getItemFor(const std::string& cn)
{
return mItems[cn];
}
void QLayoutScene::fillFromLayout(const CLayout* layout)
{
if (layout == NULL) return;
clear();
mItems.clear();
if (mpRender != NULL && mpResolver != NULL)
{
QRenderConverter::setBackground(this, mpRender->getBackgroundColor(), mpResolver);
}
const CCopasiVector<CLCompartmentGlyph> & comps = layout->getListOfCompartmentGlyphs();
auto itComp = comps.begin();
while (itComp != comps.end())
{
addGlyph(*itComp);
++itComp;
}
const CCopasiVector<CLReactionGlyph> & reactions = layout->getListOfReactionGlyphs();
auto itReactions = reactions.begin();
while (itReactions != reactions.end())
{
addGlyph(*itReactions);
++itReactions;
}
const CCopasiVector<CLMetabGlyph> & species = layout->getListOfMetaboliteGlyphs();
auto itSpecies = species.begin();
while (itSpecies != species.end())
{
addGlyph(*itSpecies);
++itSpecies;
}
const CCopasiVector<CLTextGlyph> & texts = layout->getListOfTextGlyphs();
auto itTexts = texts.begin();
while (itTexts != texts.end())
{
addGlyph(*itTexts);
++itTexts;
}
const CCopasiVector<CLGeneralGlyph> & list = layout->getListOfGeneralGlyphs();
auto itList = list.begin();
while (itList != list.end())
{
addGlyph(*itList);
++itList;
}
}
void QLayoutScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
qDebug("dragLeaveEvent");
}
<commit_msg>- removed remaining auto keywords, since we are not using c++-11 elsewhere<commit_after>#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPainter>
#include <QPrinter>
#include <QImage>
#include <qgraphicseffect.h>
#include <copasi.h>
#include <qlayout/qlayoutscene.h>
#include <qlayout/qcopasieffect.h>
#include <qlayout/qlabelgraphicsitem.h>
#include <qlayout/qstyledgraphicsitem.h>
#include <qlayout/qconnectiongraphicsitem.h>
#include <qlayout/qrenderconverter.h>
#include <layout/CLayout.h>
#include <layout/CLGlyphs.h>
#include <layout/CLText.h>
#include <layout/CLReactionGlyph.h>
#include <layout/CLRenderResolver.h>
#include <layout/CLGlobalRenderInformation.h>
#include <layout/CListOfLayouts.h>
#include <layout/CLLocalRenderInformation.h>
#include <CopasiDataModel/CCopasiDataModel.h>
QLayoutScene::QLayoutScene(CLayout* layout, CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
: QGraphicsScene()
, mpLayout(layout)
, mpRender(renderInformation)
, mpResolver(NULL)
{
initializeResolver(model, renderInformation);
}
void QLayoutScene::setLayout(CLayout *layout, CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
mpLayout = layout;
setRenderInformation(model, renderInformation);
}
void QLayoutScene::setRenderInformation(CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
initializeResolver(model, renderInformation);
}
const CLayout* QLayoutScene::getCurrentLayout() const
{
return mpLayout;
}
const CLRenderInformationBase* QLayoutScene::getCurrentRenderInfo() const
{
return mpRender;
}
void QLayoutScene::saveToFile(const std::string& fileName, const std::string& fileType /*= "pdf"*/)
{
if (fileType == "pdf")
{
QPrinter printer (QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName.c_str());
QPainter painter(&printer);
painter.setRenderHints(
QPainter::Antialiasing |QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform);
render(&painter, QRect(), itemsBoundingRect());
painter.end();
}
else
{
const int scale = 2;
QImage image(QSize(width()*scale, height()*scale), QImage::Format_ARGB32);
QPainter painter(&image);
painter.setRenderHints(
QPainter::Antialiasing |QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform);
render(&painter, image.rect(), itemsBoundingRect());
painter.end();
image.save(fileName.c_str(), fileType.c_str());
}
}
void QLayoutScene::initializeResolver(CCopasiDataModel* model, CLRenderInformationBase* renderInformation)
{
if (model == NULL)
return;
if (renderInformation == NULL)
{
if (mpLayout != NULL && mpLayout->getListOfLocalRenderInformationObjects().size() > 0)
mpRender = mpLayout->getListOfLocalRenderInformationObjects()[0];
else if (model->getListOfLayouts()->getListOfGlobalRenderInformationObjects().size() > 0)
mpRender = model->getListOfLayouts()->getListOfGlobalRenderInformationObjects()[0];
}
else
mpRender = renderInformation;
if (mpLayout == NULL || mpRender == NULL)
return;
CLLocalRenderInformation* local = dynamic_cast<CLLocalRenderInformation*>(mpRender);
if (local != NULL)
mpResolver = new CLRenderResolver(*local, mpLayout->getListOfLocalRenderInformationObjects(), model->getListOfLayouts()->getListOfGlobalRenderInformationObjects());
else
mpResolver = new CLRenderResolver(*dynamic_cast<CLGlobalRenderInformation*>(mpRender), model->getListOfLayouts()->getListOfGlobalRenderInformationObjects());
}
void QLayoutScene::setResolver(const CLRenderResolver* resolver)
{
mpResolver = resolver;
}
const CLRenderResolver* QLayoutScene::getResolver() const
{
return mpResolver;
}
QLayoutScene::~QLayoutScene()
{
}
void QLayoutScene::recreate()
{
fillFromLayout(mpLayout);
invalidate();
}
void QLayoutScene::addGlyph(const CLGraphicalObject* go)
{
if (go == NULL) return;
const CLGlyphWithCurve* curveGlyph = dynamic_cast<const CLGlyphWithCurve*>(go);
const CLReactionGlyph* reaction = dynamic_cast<const CLReactionGlyph*>(go);
const CLTextGlyph* text = dynamic_cast<const CLTextGlyph*>(go);
const CLGeneralGlyph* general = dynamic_cast<const CLGeneralGlyph*>(go);
QGraphicsItem *item = NULL;
if (curveGlyph != NULL)
{
if (curveGlyph->getCurve().getNumCurveSegments() > 0 || reaction != NULL || general != NULL)
item = new QConnectionGraphicsItem(curveGlyph,
mpResolver == NULL ? NULL : mpResolver);
}
else if (text != NULL)
{
item = new QLabelGraphicsItem(text, mpResolver == NULL ? NULL : mpResolver);
}
else
{
item = new QStyledGraphicsItem(go, mpResolver == NULL ? NULL : mpResolver);
}
if (item != NULL)
{
CCopasiObject* obj = go->getModelObject();
if (obj != NULL && text == NULL)
{
item->setData(COPASI_OBJECT_CN, QString(obj->getCN().c_str()));
mItems[obj->getCN()]= item;
}
addItem(item);
}
}
QGraphicsItem* QLayoutScene::getItemFor(const std::string& cn)
{
return mItems[cn];
}
void QLayoutScene::fillFromLayout(const CLayout* layout)
{
if (layout == NULL) return;
clear();
mItems.clear();
if (mpRender != NULL && mpResolver != NULL)
{
QRenderConverter::setBackground(this, mpRender->getBackgroundColor(), mpResolver);
}
const CCopasiVector<CLCompartmentGlyph> & comps = layout->getListOfCompartmentGlyphs();
CCopasiVector<CLCompartmentGlyph>::const_iterator itComp = comps.begin();
while (itComp != comps.end())
{
addGlyph(*itComp);
++itComp;
}
const CCopasiVector<CLReactionGlyph> & reactions = layout->getListOfReactionGlyphs();
CCopasiVector<CLReactionGlyph>::const_iterator itReactions = reactions.begin();
while (itReactions != reactions.end())
{
addGlyph(*itReactions);
++itReactions;
}
const CCopasiVector<CLMetabGlyph> & species = layout->getListOfMetaboliteGlyphs();
CCopasiVector<CLMetabGlyph>::const_iterator itSpecies = species.begin();
while (itSpecies != species.end())
{
addGlyph(*itSpecies);
++itSpecies;
}
const CCopasiVector<CLTextGlyph> & texts = layout->getListOfTextGlyphs();
CCopasiVector<CLTextGlyph>::const_iterator itTexts = texts.begin();
while (itTexts != texts.end())
{
addGlyph(*itTexts);
++itTexts;
}
const CCopasiVector<CLGeneralGlyph> & list = layout->getListOfGeneralGlyphs();
CCopasiVector<CLGeneralGlyph>::const_iterator itList = list.begin();
while (itList != list.end())
{
addGlyph(*itList);
++itList;
}
}
void QLayoutScene::dragLeaveEvent ( QGraphicsSceneDragDropEvent * event )
{
qDebug("dragLeaveEvent");
}
<|endoftext|> |
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CTableCell.cpp,v $
$Revision: 1.1 $
$Name: $
$Author: shoops $
$Date: 2005/09/23 18:59:12 $
End CVS Header */
#include <limits>
#include <iostream>
#include <sstream>
#include "copasi.h"
#include "CTableCell.h"
CTableCell::CTableCell(const char & separator):
mSeparator(separator),
mName(""),
mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()),
mIsValue(false)
{}
CTableCell::CTableCell(const CTableCell & src):
mSeparator(src.mSeparator),
mName(src.mName),
mValue(src.mValue),
mIsValue(src.mIsValue)
{}
CTableCell::~CTableCell();
bool CTableCell::setSeparator(const char & separator)
{
mSeparator = separator;
return true;
}
const char & CTableCell::getSeparator() const {return mSeparator;}
const bool & CTableCell::isValue() const {return mIsValue;}
const std::string & CTableCell::getName() const {return mName;}
const C_FLOAT64 & CTableCell::getValue() const {return mValue;}
#ifdef WIN32
// warning C4056: overflow in floating-point constant arithmetic
// warning C4756: overflow in constant arithmetic
# pragma warning (disable: 4056 4756)
#endif
std::istream & operator >> (std::istream &is, CTableCell & cell)
{
static char buffer[256];
cell.mName = "";
do
{
is.getline(buffer, 256, cell.mSeparator);
cell.mName += buffer;
}
while (strlen(buffer) == 255 && !is.fail());
/* Trim leading and trailing whitespaces from the string */
std::string::size_type begin = cell.mName.find_first_not_of("\x20\x09\x0d\x0a");
if (begin == std::string::npos)
{
cell.mName = "";
cell.mIsValue = false;
cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
return is;
}
else
{
std::string::size_type end = cell.mName.find_last_not_of("\x20\x09\x0d\x0a");
if (end == std::string::npos)
cell.mName = cell.mName.substr(begin);
else
cell.mName = cell.mName.substr(begin, end - begin + 1);
}
/* Try to convert the string into a number */
char * Tail;
cell.mValue = strtod(cell.mName.c_str(), & Tail);
if (!*Tail)
{
cell.mIsValue = true;
}
else if (cell.mName.c_str() == "INF")
{
cell.mIsValue = true;
cell.mValue = DBL_MAX * 2;
}
else if (cell.mName.c_str() == "-INF")
{
cell.mIsValue = true;
cell.mValue = - DBL_MAX * 2;
}
else
{
cell.mIsValue = false;
cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
}
return is;
}
#ifdef WIN32
# pragma warning (default: 4056 4756)
#endif
CTableRow::CTableRow(const unsigned C_INT32 & size,
const char & separator):
mCells(0),
mSeparator(separator)
{resize(size);}
CTableRow::CTableRow(const CTableRow & src):
mCells(src.mCells),
mSeparator(src.mSeparator)
{}
CTableRow::~CTableRow() {}
const std::vector< CTableCell > & CTableRow::getCells() const
{return mCells;}
bool CTableRow::resize(const unsigned C_INT32 & size)
{
mCells.resize(size);
std::vector< CTableCell >::iterator it = mCells.begin();
std::vector< CTableCell >::iterator end = mCells.end();
for (; it != end; ++it)
it->setSeparator(mSeparator);
return true;
}
const unsigned C_INT32 CTableRow::size() const
{return mCells.size();}
std::istream & operator >> (std::istream &is, CTableRow & row)
{
std::stringstream line;
is.get(*line.rdbuf(), '\x0a');
is.ignore(1);
std::vector< CTableCell >::iterator it = row.mCells.begin();
std::vector< CTableCell >::iterator end = row.mCells.end();
for (; it != end && !line.fail(); ++it)
line >> *it;
if (it == end) return is;
CTableCell Unread(row.mSeparator);
for (; it != end; ++it)
*it = Unread;
return is;
}
<commit_msg>Fixed missing inlcude.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CTableCell.cpp,v $
$Revision: 1.2 $
$Name: $
$Author: shoops $
$Date: 2005/09/23 19:08:21 $
End CVS Header */
#include <limits>
#include <iostream>
#include <sstream>
#include <float.h>
#include "copasi.h"
#include "CTableCell.h"
CTableCell::CTableCell(const char & separator):
mSeparator(separator),
mName(""),
mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()),
mIsValue(false)
{}
CTableCell::CTableCell(const CTableCell & src):
mSeparator(src.mSeparator),
mName(src.mName),
mValue(src.mValue),
mIsValue(src.mIsValue)
{}
CTableCell::~CTableCell() {}
bool CTableCell::setSeparator(const char & separator)
{
mSeparator = separator;
return true;
}
const char & CTableCell::getSeparator() const {return mSeparator;}
const bool & CTableCell::isValue() const {return mIsValue;}
const std::string & CTableCell::getName() const {return mName;}
const C_FLOAT64 & CTableCell::getValue() const {return mValue;}
#ifdef WIN32
// warning C4056: overflow in floating-point constant arithmetic
// warning C4756: overflow in constant arithmetic
# pragma warning (disable: 4056 4756)
#endif
std::istream & operator >> (std::istream &is, CTableCell & cell)
{
static char buffer[256];
cell.mName = "";
do
{
is.getline(buffer, 256, cell.mSeparator);
cell.mName += buffer;
}
while (strlen(buffer) == 255 && !is.fail());
/* Trim leading and trailing whitespaces from the string */
std::string::size_type begin = cell.mName.find_first_not_of("\x20\x09\x0d\x0a");
if (begin == std::string::npos)
{
cell.mName = "";
cell.mIsValue = false;
cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
return is;
}
else
{
std::string::size_type end = cell.mName.find_last_not_of("\x20\x09\x0d\x0a");
if (end == std::string::npos)
cell.mName = cell.mName.substr(begin);
else
cell.mName = cell.mName.substr(begin, end - begin + 1);
}
/* Try to convert the string into a number */
char * Tail;
cell.mValue = strtod(cell.mName.c_str(), & Tail);
if (!*Tail)
{
cell.mIsValue = true;
}
else if (cell.mName.c_str() == "INF")
{
cell.mIsValue = true;
cell.mValue = DBL_MAX * 2;
}
else if (cell.mName.c_str() == "-INF")
{
cell.mIsValue = true;
cell.mValue = - DBL_MAX * 2;
}
else
{
cell.mIsValue = false;
cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
}
return is;
}
#ifdef WIN32
# pragma warning (default: 4056 4756)
#endif
CTableRow::CTableRow(const unsigned C_INT32 & size,
const char & separator):
mCells(0),
mSeparator(separator)
{resize(size);}
CTableRow::CTableRow(const CTableRow & src):
mCells(src.mCells),
mSeparator(src.mSeparator)
{}
CTableRow::~CTableRow() {}
const std::vector< CTableCell > & CTableRow::getCells() const
{return mCells;}
bool CTableRow::resize(const unsigned C_INT32 & size)
{
mCells.resize(size);
std::vector< CTableCell >::iterator it = mCells.begin();
std::vector< CTableCell >::iterator end = mCells.end();
for (; it != end; ++it)
it->setSeparator(mSeparator);
return true;
}
const unsigned C_INT32 CTableRow::size() const
{return mCells.size();}
std::istream & operator >> (std::istream &is, CTableRow & row)
{
std::stringstream line;
is.get(*line.rdbuf(), '\x0a');
is.ignore(1);
std::vector< CTableCell >::iterator it = row.mCells.begin();
std::vector< CTableCell >::iterator end = row.mCells.end();
for (; it != end && !line.fail(); ++it)
line >> *it;
if (it == end) return is;
CTableCell Unread(row.mSeparator);
for (; it != end; ++it)
*it = Unread;
return is;
}
<|endoftext|> |
<commit_before>// ffmpeg player output (portaudio)
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include "PyUtils.h"
#include <portaudio.h>
#include <boost/bind.hpp>
#ifdef __APPLE__
// PortAudio specific Mac stuff
#include "pa_mac_core.h"
#endif
// For setting the thread priority to realtime on MacOSX.
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated...
#include <pthread.h>
#include <mach/mach_error.h>
#include <mach/mach_time.h>
#endif
static void setRealtime();
/*
The implementation with the PortAudio callback was there first.
For testing, I implemented also the blocking PortAudio interface.
I had some issues which small hiccups in the audio output -
maybe the blocking PortAudio implementation can avoid them better.
For the callback, we need to minimize the locks - or better, avoid
them fully. I'm not sure it is good to depend on thread context
switches in case it is locked. This however needs some heavy redesign.
*/
#define USE_PORTAUDIO_CALLBACK 0
int initPlayerOutput() {
PaError ret = Pa_Initialize();
if(ret != paNoError)
Py_FatalError("PortAudio init failed");
return 0;
}
template<typename T> struct OutPaSampleFormat{};
template<> struct OutPaSampleFormat<int16_t> {
static const PaSampleFormat format = paInt16;
};
template<> struct OutPaSampleFormat<float32_t> {
static const PaSampleFormat format = paFloat32;
};
#define LATENCY_IN_MS 100
struct PlayerObject::OutStream {
PlayerObject* const player;
PaStream* stream;
bool needRealtimeReset; // PortAudio callback thread must set itself to realtime
OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {
mlock(this, sizeof(*this));
}
~OutStream() { close(); }
#if USE_PORTAUDIO_CALLBACK
static int paStreamCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
OutStream* outStream = (OutStream*) userData;
// We must not hold the PyGIL here!
PyScopedLock lock(outStream->player->lock);
if(outStream->needRealtimeReset) {
outStream->needRealtimeReset = false;
setRealtime();
}
outStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);
return paContinue;
}
#else
PyThread audioThread;
void audioThreadProc(PyMutex& threadLock, bool& stopSignal) {
while(true) {
{
PyScopedLock l(threadLock);
if(stopSignal) return;
}
if(needRealtimeReset) {
needRealtimeReset = false;
setRealtime();
}
OUTSAMPLE_t buffer[48 * 2 * 10]; // 10ms stereo in 48khz
size_t frameCount = 0;
{
PyScopedLock lock(player->lock);
if(stopSignal) return;
player->readOutStream(buffer, sizeof(buffer)/sizeof(OUTSAMPLE_t), NULL);
frameCount = sizeof(buffer)/sizeof(OUTSAMPLE_t) / player->outNumChannels;
}
PaError ret = Pa_WriteStream(stream, buffer, frameCount);
if(ret == paOutputUnderflowed)
printf("warning: paOutputUnderflowed\n");
else if(ret != paNoError) {
printf("Pa_WriteStream error %i (%s)\n", ret, Pa_GetErrorText(ret));
// sleep half a second to avoid spamming
for(int i = 0; i < 50; ++i) {
usleep(10 * 1000);
PyScopedLock l(threadLock);
if(stopSignal) return;
}
}
}
}
#endif
bool open() {
if(stream) close();
assert(stream == NULL);
PaStreamParameters outputParameters;
#if defined(__APPLE__)
PaMacCoreStreamInfo macInfo;
PaMacCore_SetupStreamInfo( &macInfo,
paMacCorePlayNice | paMacCorePro );
outputParameters.hostApiSpecificStreamInfo = &macInfo;
#elif defined(__LINUX__)
// TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,
// we can call that to enable RT priority with ALSA.
// We could check dynamically via dsym.
outputParameters.hostApiSpecificStreamInfo = NULL;
#else
outputParameters.hostApiSpecificStreamInfo = NULL;
#endif
outputParameters.device = Pa_GetDefaultOutputDevice();
if (outputParameters.device == paNoDevice) {
PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device");
return false;
}
outputParameters.channelCount = player->outNumChannels;
outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;
unsigned long bufferSize = (player->outSamplerate * player->outNumChannels / 1000) * LATENCY_IN_MS / 4;
if(bufferSize == paFramesPerBufferUnspecified)
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
else
outputParameters.suggestedLatency = LATENCY_IN_MS / 1000.0;
// Note about framesPerBuffer:
// Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused
// some random more or less rare cracking noises.
// See here: https://github.com/albertz/music-player/issues/35
// This doesn't seem to happen with paFramesPerBufferUnspecified.
PaError ret = Pa_OpenStream(
&stream,
NULL, // no input
&outputParameters,
player->outSamplerate, // sampleRate
bufferSize,
paClipOff | paDitherOff,
#if USE_PORTAUDIO_CALLBACK
&paStreamCallback,
#else
NULL,
#endif
this //void *userData
);
if(ret != paNoError) {
PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret));
if(stream)
close();
return false;
}
needRealtimeReset = true;
Pa_StartStream(stream);
#if !USE_PORTAUDIO_CALLBACK
audioThread.func = boost::bind(&OutStream::audioThreadProc, this, _1, _2);
audioThread.start();
#endif
return true;
}
void close() {
if(this->stream == NULL) return;
// we expect that we have the player lock here.
// reset fader.
player->fader.init(0,0);
// we must release the player lock so that any thread-join can be done.
PaStream* stream = NULL;
std::swap(stream, this->stream);
PyScopedUnlock unlock(player->lock);
audioThread.stop();
Pa_CloseStream(stream);
}
bool isOpen() const { return stream != NULL; }
};
int PlayerObject::setPlaying(bool playing) {
PlayerObject* player = this;
bool oldplayingstate = false;
PyScopedGIL gil;
{
PyScopedGIUnlock gunlock;
player->workerThread.start(); // if not running yet, start
if(!player->outStream.get())
player->outStream.reset(new OutStream(this));
assert(player->outStream.get() != NULL);
if(soundcardOutputEnabled) {
if(playing && !player->outStream->isOpen()) {
if(!player->outStream->open())
playing = false;
}
}
oldplayingstate = player->playing;
if(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing)
fader.init(playing ? 1 : -1, outSamplerate);
player->playing = playing;
}
if(!PyErr_Occurred() && player->dict) {
Py_INCREF(player->dict);
PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange");
if(onPlayingStateChange && onPlayingStateChange != Py_None) {
Py_INCREF(onPlayingStateChange);
PyObject* kwargs = PyDict_New();
assert(kwargs);
PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate));
PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing));
PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);
Py_XDECREF(retObj);
// errors are not fatal from the callback, so handle it now and go on
if(PyErr_Occurred())
PyErr_Print();
Py_DECREF(kwargs);
Py_DECREF(onPlayingStateChange);
}
Py_DECREF(player->dict);
}
return PyErr_Occurred() ? -1 : 0;
}
void PlayerObject::resetPlaying() {
if(this->playing)
this->setPlaying(false);
if(this->outStream.get() != NULL)
this->outStream.reset();
}
#ifdef __APPLE__
// https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
// Also, from Google Native Client, osx/nacl_thread_nice.c has some related code.
// Or, from Google Chrome, platform_thread_mac.mm.
void setRealtime() {
kern_return_t ret;
thread_port_t threadport = pthread_mach_thread_np(pthread_self());
thread_extended_policy_data_t policy;
policy.timeshare = 0;
ret = thread_policy_set(threadport,
THREAD_EXTENDED_POLICY,
(thread_policy_t)&policy,
THREAD_EXTENDED_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
thread_precedence_policy_data_t precedence;
precedence.importance = 63;
ret = thread_policy_set(threadport,
THREAD_PRECEDENCE_POLICY,
(thread_policy_t)&precedence,
THREAD_PRECEDENCE_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
mach_timebase_info_data_t tb_info;
mach_timebase_info(&tb_info);
double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000;
thread_time_constraint_policy_data_t ttcpolicy;
ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz
ttcpolicy.computation = 0.75 * 2.9 * timeFact;
ttcpolicy.constraint = 0.85 * 2.9 * timeFact;
ttcpolicy.preemptible = 1;
ret = thread_policy_set(threadport,
THREAD_TIME_CONSTRAINT_POLICY,
(thread_policy_t)&ttcpolicy,
THREAD_TIME_CONSTRAINT_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
}
#else
void setRealtime() {} // not implemented yet
#endif
<commit_msg>use PortAudio callback again<commit_after>// ffmpeg player output (portaudio)
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include "PyUtils.h"
#include <portaudio.h>
#include <boost/bind.hpp>
#include <boost/atomic.hpp>
#ifdef __APPLE__
// PortAudio specific Mac stuff
#include "pa_mac_core.h"
#endif
// For setting the thread priority to realtime on MacOSX.
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated...
#include <pthread.h>
#include <mach/mach_error.h>
#include <mach/mach_time.h>
#endif
static void setRealtime();
/*
The implementation with the PortAudio callback was there first.
For testing, I implemented also the blocking PortAudio interface.
I had some issues which small hiccups in the audio output -
maybe the blocking PortAudio implementation can avoid them better.
For the callback, we need to minimize the locks - or better, avoid
them fully. I'm not sure it is good to depend on thread context
switches in case it is locked. This however needs some heavy redesign.
*/
#define USE_PORTAUDIO_CALLBACK 1
int initPlayerOutput() {
PaError ret = Pa_Initialize();
if(ret != paNoError)
Py_FatalError("PortAudio init failed");
return 0;
}
template<typename T> struct OutPaSampleFormat{};
template<> struct OutPaSampleFormat<int16_t> {
static const PaSampleFormat format = paInt16;
};
template<> struct OutPaSampleFormat<float32_t> {
static const PaSampleFormat format = paFloat32;
};
#define LATENCY_IN_MS 100
struct PlayerObject::OutStream {
PlayerObject* const player;
PaStream* stream;
boost::atomic<bool> needRealtimeReset; // PortAudio callback thread must set itself to realtime
OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {
mlock(this, sizeof(*this));
}
~OutStream() { close(); }
#if USE_PORTAUDIO_CALLBACK
static int paStreamCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
OutStream* outStream = (OutStream*) userData;
// We must not hold the PyGIL here!
PyScopedLock lock(outStream->player->lock);
if(outStream->needRealtimeReset.exchange(false)) {
setRealtime();
}
outStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);
return paContinue;
}
#else
PyThread audioThread;
void audioThreadProc(PyMutex& threadLock, bool& stopSignal) {
while(true) {
{
PyScopedLock l(threadLock);
if(stopSignal) return;
}
if(needRealtimeReset) {
needRealtimeReset = false;
setRealtime();
}
OUTSAMPLE_t buffer[48 * 2 * 10]; // 10ms stereo in 48khz
size_t frameCount = 0;
{
PyScopedLock lock(player->lock);
if(stopSignal) return;
player->readOutStream(buffer, sizeof(buffer)/sizeof(OUTSAMPLE_t), NULL);
frameCount = sizeof(buffer)/sizeof(OUTSAMPLE_t) / player->outNumChannels;
}
PaError ret = Pa_WriteStream(stream, buffer, frameCount);
if(ret == paOutputUnderflowed)
printf("warning: paOutputUnderflowed\n");
else if(ret != paNoError) {
printf("Pa_WriteStream error %i (%s)\n", ret, Pa_GetErrorText(ret));
// sleep half a second to avoid spamming
for(int i = 0; i < 50; ++i) {
usleep(10 * 1000);
PyScopedLock l(threadLock);
if(stopSignal) return;
}
}
}
}
#endif
bool open() {
if(stream) close();
assert(stream == NULL);
PaStreamParameters outputParameters;
#if defined(__APPLE__)
PaMacCoreStreamInfo macInfo;
PaMacCore_SetupStreamInfo( &macInfo,
paMacCorePlayNice | paMacCorePro );
outputParameters.hostApiSpecificStreamInfo = &macInfo;
#elif defined(__LINUX__)
// TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,
// we can call that to enable RT priority with ALSA.
// We could check dynamically via dsym.
outputParameters.hostApiSpecificStreamInfo = NULL;
#else
outputParameters.hostApiSpecificStreamInfo = NULL;
#endif
outputParameters.device = Pa_GetDefaultOutputDevice();
if (outputParameters.device == paNoDevice) {
PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device");
return false;
}
outputParameters.channelCount = player->outNumChannels;
outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;
unsigned long bufferSize = (player->outSamplerate * player->outNumChannels / 1000) * LATENCY_IN_MS / 4;
if(bufferSize == paFramesPerBufferUnspecified)
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
else
outputParameters.suggestedLatency = LATENCY_IN_MS / 1000.0;
// Note about framesPerBuffer:
// Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused
// some random more or less rare cracking noises.
// See here: https://github.com/albertz/music-player/issues/35
// This doesn't seem to happen with paFramesPerBufferUnspecified.
PaError ret = Pa_OpenStream(
&stream,
NULL, // no input
&outputParameters,
player->outSamplerate, // sampleRate
bufferSize,
paClipOff | paDitherOff,
#if USE_PORTAUDIO_CALLBACK
&paStreamCallback,
#else
NULL,
#endif
this //void *userData
);
if(ret != paNoError) {
PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret));
if(stream)
close();
return false;
}
needRealtimeReset = true;
Pa_StartStream(stream);
#if !USE_PORTAUDIO_CALLBACK
audioThread.func = boost::bind(&OutStream::audioThreadProc, this, _1, _2);
audioThread.start();
#endif
return true;
}
void close() {
if(this->stream == NULL) return;
// we expect that we have the player lock here.
// reset fader.
player->fader.init(0,0);
// we must release the player lock so that any thread-join can be done.
PaStream* stream = NULL;
std::swap(stream, this->stream);
PyScopedUnlock unlock(player->lock);
#if !USE_PORTAUDIO_CALLBACK
audioThread.stop();
#endif
Pa_CloseStream(stream);
}
bool isOpen() const { return stream != NULL; }
};
int PlayerObject::setPlaying(bool playing) {
PlayerObject* player = this;
bool oldplayingstate = false;
PyScopedGIL gil;
{
PyScopedGIUnlock gunlock;
player->workerThread.start(); // if not running yet, start
if(!player->outStream.get())
player->outStream.reset(new OutStream(this));
assert(player->outStream.get() != NULL);
if(soundcardOutputEnabled) {
if(playing && !player->outStream->isOpen()) {
if(!player->outStream->open())
playing = false;
}
}
oldplayingstate = player->playing;
if(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing)
fader.init(playing ? 1 : -1, outSamplerate);
player->playing = playing;
}
if(!PyErr_Occurred() && player->dict) {
Py_INCREF(player->dict);
PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange");
if(onPlayingStateChange && onPlayingStateChange != Py_None) {
Py_INCREF(onPlayingStateChange);
PyObject* kwargs = PyDict_New();
assert(kwargs);
PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate));
PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing));
PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);
Py_XDECREF(retObj);
// errors are not fatal from the callback, so handle it now and go on
if(PyErr_Occurred())
PyErr_Print();
Py_DECREF(kwargs);
Py_DECREF(onPlayingStateChange);
}
Py_DECREF(player->dict);
}
return PyErr_Occurred() ? -1 : 0;
}
void PlayerObject::resetPlaying() {
if(this->playing)
this->setPlaying(false);
if(this->outStream.get() != NULL)
this->outStream.reset();
}
#ifdef __APPLE__
// https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
// Also, from Google Native Client, osx/nacl_thread_nice.c has some related code.
// Or, from Google Chrome, platform_thread_mac.mm.
void setRealtime() {
kern_return_t ret;
thread_port_t threadport = pthread_mach_thread_np(pthread_self());
thread_extended_policy_data_t policy;
policy.timeshare = 0;
ret = thread_policy_set(threadport,
THREAD_EXTENDED_POLICY,
(thread_policy_t)&policy,
THREAD_EXTENDED_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
thread_precedence_policy_data_t precedence;
precedence.importance = 63;
ret = thread_policy_set(threadport,
THREAD_PRECEDENCE_POLICY,
(thread_policy_t)&precedence,
THREAD_PRECEDENCE_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
mach_timebase_info_data_t tb_info;
mach_timebase_info(&tb_info);
double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000;
thread_time_constraint_policy_data_t ttcpolicy;
ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz
ttcpolicy.computation = 0.75 * 2.9 * timeFact;
ttcpolicy.constraint = 0.85 * 2.9 * timeFact;
ttcpolicy.preemptible = 1;
ret = thread_policy_set(threadport,
THREAD_TIME_CONSTRAINT_POLICY,
(thread_policy_t)&ttcpolicy,
THREAD_TIME_CONSTRAINT_POLICY_COUNT);
if(ret != KERN_SUCCESS) {
fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
return;
}
}
#else
void setRealtime() {} // not implemented yet
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* exit */
//#include <string> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h>
#include "std_msgs/Int16.h"
#include <geometry_msgs/Twist.h> /* Message keeps encoder-values as Vector3.x (left) and .y (right) */
#include <geometry_msgs/Vector3.h>
#include <sensor_msgs/JointState.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
const char* serialport="/dev/ttyAMA0";
int serialport_bps=B38400;
int16_t EncoderL;
int16_t EncoderR;
int16_t previous_EncoderL;
int16_t previous_EncoderR;
double deltaLeft;
double deltaRight;
double meter_per_tick = 0.001;
double x = 0.0;
double y = 0.0;
double th = 0.0;
double vx;
double vy;
double vth;
double Kettenabstand = 0.4;
double Antriebsrolle_Radius=0.03;
double vl = 0.0;
double vr = 0.0;
ros::Time current_time_encoder, last_time_encoder;
geometry_msgs::Quaternion odom_quat;
struct termios orig;
int filedesc;
int fd; // serial port file descriptor
unsigned char serialBuffer[16]; // Serial buffer to store data for I/O
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z);
//ANFANG Alternative
double vel_linear_x = vel_cmd.linear.x;
double vel_angular_z = vel_cmd.angular.z;
double right_vel = 0.0;
double left_vel = 0.0;
if(vel_linear_x == 0){
// turning
right_vel = vel_angular_z * Kettenabstand / 2.0;
left_vel = (-1) * right_vel;
}
else if(vel_angular_z == 0){
// forward / backward
left_vel = right_vel = vel_linear_x;
}
else{
// moving doing arcs
left_vel = vel_linear_x - vel_angular_z * Kettenabstand / 2.0;
right_vel = vel_linear_x + vel_angular_z * Kettenabstand / 2.0;
}
vl = left_vel;
vr = right_vel;
//ENDE Alternative
if (vel_cmd.linear.x>0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 255; // speed1
serialBuffer[3] = 255; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.linear.x<0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 0; // speed1
serialBuffer[3] = 0; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 128; // speed1
serialBuffer[3] = 128; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.angular.z>0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 0; // speed1
serialBuffer[3] = 255; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.angular.z<0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 255; // speed1
serialBuffer[3] = 0; // speed2
writeBytes(fd, 4);
}
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<geometry_msgs::Vector3>("/encoders", 100);
//ros::Publisher encoder_l_pub = n.advertise<std_msgs::Int16>("encoder_l", 100);
//ros::Publisher encoder_r_pub = n.advertise<std_msgs::Int16>("encoder_r", 100);
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom", 50);
tf::TransformBroadcaster odom_broadcaster;
filedesc = openSerialPort("/dev/ttyAMA0", B38400);
if (filedesc == -1) exit(1);
usleep(40000);// Sleep for UART to power up and set options
ROS_DEBUG("Serial Port opened \n");
//ros::Time current_time, last_time;
current_time_encoder = ros::Time::now();
last_time_encoder = ros::Time::now();
ros::Rate loop_rate(10);
while( n.ok() )
{
// Read encoder and other data from MD49
// *************************************
read_MD49_Data();
current_time_encoder = ros::Time::now();
// calculate odomety
// *****************
deltaLeft = EncoderL - previous_EncoderL;
deltaRight = EncoderR - previous_EncoderR;
vx = deltaLeft * meter_per_tick;
vy = deltaRight * meter_per_tick;
previous_EncoderL = EncoderL;
previous_EncoderR = EncoderR;
//last_time_encoder = current_time_encoder;
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time_encoder - last_time_encoder).toSec();
double delta_x = (vx * cos(th) - vy * sin(th)) * dt;
double delta_y = (vx * sin(th) + vy * cos(th)) * dt;
double delta_th = vth * dt;
x += delta_x;
y += delta_y;
th += delta_th;
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time_encoder;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_link";
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time_encoder;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vth;
//publish the message
odom_pub.publish(odom);
last_time_encoder = current_time_encoder;
// Publish EncoderL and EncoderR to topics encoder_l and encoder_r
// ***************************************************************
// std_msgs::Int16 encoder_l;
// std_msgs::Int16 encoder_r;
// encoder_l.data = EncoderL;
// encoder_r.data=EncoderR;
// encoder_l_pub.publish(encoder_l);
// encoder_r_pub.publish(encoder_r);
geometry_msgs::Vector3 encoders;
encoders.x=EncoderL;
encoders.y=EncoderR;
encoders_pub.publish(encoders);
// Loop
// ****
ros::spinOnce();
loop_rate.sleep();
}
return 1;
}
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
//write(fd,serialBuffer, count);
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
//printf("Encoder1 Byte1: %i ",serialBuffer[0]);
//printf("Byte2: %i ",serialBuffer[1]);
//printf("Byte3: % i ",serialBuffer[2]);
//printf("Byte4: %i \n",serialBuffer[3]);
//printf("Encoder2 Byte1: %i ",serialBuffer[4]);
//printf("Byte2: %i ",serialBuffer[5]);
//printf("Byte3: %i ",serialBuffer[6]);
//printf("Byte4: %i \n",serialBuffer[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
//printf("vl= %f \n", vl);
//printf("vr= %f \n", vr);
}
<commit_msg>Update code<commit_after>#include <iostream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* exit */
//#include <string> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h>
#include "std_msgs/Int16.h"
#include <geometry_msgs/Twist.h> /* Message keeps encoder-values as Vector3.x (left) and .y (right) */
#include <base_controller/encoders.h>
#include <geometry_msgs/Vector3.h>
#include <sensor_msgs/JointState.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
const char* serialport="/dev/ttyAMA0";
int serialport_bps=B38400;
int16_t EncoderL;
int16_t EncoderR;
int16_t previous_EncoderL;
int16_t previous_EncoderR;
double deltaLeft;
double deltaRight;
double meter_per_tick = 0.001;
double x = 0.0;
double y = 0.0;
double th = 0.0;
double vx;
double vy;
double vth;
double Kettenabstand = 0.4;
double Antriebsrolle_Radius=0.03;
double vl = 0.0;
double vr = 0.0;
ros::Time current_time_encoder, last_time_encoder;
geometry_msgs::Quaternion odom_quat;
struct termios orig;
int filedesc;
int fd; // serial port file descriptor
unsigned char serialBuffer[16]; // Serial buffer to store data for I/O
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z);
//ANFANG Alternative
double vel_linear_x = vel_cmd.linear.x;
double vel_angular_z = vel_cmd.angular.z;
double right_vel = 0.0;
double left_vel = 0.0;
if(vel_linear_x == 0){
// turning
right_vel = vel_angular_z * Kettenabstand / 2.0;
left_vel = (-1) * right_vel;
}
else if(vel_angular_z == 0){
// forward / backward
left_vel = right_vel = vel_linear_x;
}
else{
// moving doing arcs
left_vel = vel_linear_x - vel_angular_z * Kettenabstand / 2.0;
right_vel = vel_linear_x + vel_angular_z * Kettenabstand / 2.0;
}
vl = left_vel;
vr = right_vel;
//ENDE Alternative
if (vel_cmd.linear.x>0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 255; // speed1
serialBuffer[3] = 255; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.linear.x<0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 0; // speed1
serialBuffer[3] = 0; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 128; // speed1
serialBuffer[3] = 128; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.angular.z>0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 0; // speed1
serialBuffer[3] = 255; // speed2
writeBytes(fd, 4);
}
if (vel_cmd.angular.z<0){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = 255; // speed1
serialBuffer[3] = 0; // speed2
writeBytes(fd, 4);
}
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<geometry_msgs::Vector3>("/encoders", 100);
//ros::Publisher encoder_l_pub = n.advertise<std_msgs::Int16>("encoder_l", 100);
//ros::Publisher encoder_r_pub = n.advertise<std_msgs::Int16>("encoder_r", 100);
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom", 50);
tf::TransformBroadcaster odom_broadcaster;
filedesc = openSerialPort("/dev/ttyAMA0", B38400);
if (filedesc == -1) exit(1);
usleep(40000);// Sleep for UART to power up and set options
ROS_DEBUG("Serial Port opened \n");
//ros::Time current_time, last_time;
current_time_encoder = ros::Time::now();
last_time_encoder = ros::Time::now();
ros::Rate loop_rate(10);
while( n.ok() )
{
// Read encoder and other data from MD49
// *************************************
read_MD49_Data();
current_time_encoder = ros::Time::now();
// calculate odomety
// *****************
deltaLeft = EncoderL - previous_EncoderL;
deltaRight = EncoderR - previous_EncoderR;
vx = deltaLeft * meter_per_tick;
vy = deltaRight * meter_per_tick;
previous_EncoderL = EncoderL;
previous_EncoderR = EncoderR;
//last_time_encoder = current_time_encoder;
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time_encoder - last_time_encoder).toSec();
double delta_x = (vx * cos(th) - vy * sin(th)) * dt;
double delta_y = (vx * sin(th) + vy * cos(th)) * dt;
double delta_th = vth * dt;
x += delta_x;
y += delta_y;
th += delta_th;
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time_encoder;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_link";
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time_encoder;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vth;
//publish the message
odom_pub.publish(odom);
last_time_encoder = current_time_encoder;
// Publish EncoderL and EncoderR to topics encoder_l and encoder_r
// ***************************************************************
// std_msgs::Int16 encoder_l;
// std_msgs::Int16 encoder_r;
// encoder_l.data = EncoderL;
// encoder_r.data=EncoderR;
// encoder_l_pub.publish(encoder_l);
// encoder_r_pub.publish(encoder_r);
geometry_msgs::Vector3 encoders;
encoders.x=EncoderL;
encoders.y=EncoderR;
encoders_pub.publish(encoders);
// Loop
// ****
ros::spinOnce();
loop_rate.sleep();
}
return 1;
}
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
//write(fd,serialBuffer, count);
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
//printf("Encoder1 Byte1: %i ",serialBuffer[0]);
//printf("Byte2: %i ",serialBuffer[1]);
//printf("Byte3: % i ",serialBuffer[2]);
//printf("Byte4: %i \n",serialBuffer[3]);
//printf("Encoder2 Byte1: %i ",serialBuffer[4]);
//printf("Byte2: %i ",serialBuffer[5]);
//printf("Byte3: %i ",serialBuffer[6]);
//printf("Byte4: %i \n",serialBuffer[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
//printf("vl= %f \n", vl);
//printf("vr= %f \n", vr);
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/memdiags_fir.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file memdiags_fir.C
/// @brief Subroutines for memdiags/prd FIR
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/utils/scom.H>
#include <lib/fir/memdiags_fir.H>
using fapi2::TARGET_TYPE_MCBIST;
namespace mss
{
///
/// @brief Unmask and setup actions for memdiags related FIR
/// @param[in] i_target the fapi2::Target
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template<>
fapi2::ReturnCode unmask_memdiags_errors( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("unmask_memdiags_errors");
// Fill our buffer with F's as we're going to clear the bits we want to
// unmask and then drop the result in to the _AND register.
fapi2::buffer<uint64_t> l_mcbistfir_mask(~0);
fapi2::buffer<uint64_t> l_mcbistfir_action0;
fapi2::buffer<uint64_t> l_mcbistfir_action1;
FAPI_TRY( mss::getScom(i_target, MCBIST_MCBISTFIRACT0, l_mcbistfir_action0) );
FAPI_TRY( mss::getScom(i_target, MCBIST_MCBISTFIRACT1, l_mcbistfir_action1) );
// There's not much to do here right now as Marc needs to work out the new FIR
// and whatnot for Nimbus. Lets make sure we setup everything as PRD needs it
// for sim, and we'll circle back to add the other FIR as the design completes.
// Don't unmask the main address skipped FIR. First, we rely on the skipping so
// we probably don't want any one to see it and second it's broken per Shelton 5/16.
// Unmask the program complete bit and setup the actions for an attention
l_mcbistfir_action0.setBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>();
l_mcbistfir_action1.clearBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>();
l_mcbistfir_mask.clearBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>();
// Hit the and register of the fir mask
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBISTFIRACT0, l_mcbistfir_action0) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBISTFIRACT1, l_mcbistfir_action1) );
FAPI_TRY( mss::putScom(i_target, MCBIST_MCBISTFIRMASK_AND, l_mcbistfir_mask) );
fapi_try_exit:
return fapi2::current_err;
}
}
<commit_msg>Add Memory Subsystem FIR support<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/memdiags_fir.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file memdiags_fir.C
/// @brief Subroutines for memdiags/prd FIR
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/utils/scom.H>
#include <lib/utils/find.H>
#include <lib/fir/fir.H>
#include <lib/fir/memdiags_fir.H>
#include <lib/mc/port.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
namespace mss
{
namespace unmask
{
///
/// @brief Unmask and setup actions for memdiags related FIR
/// @param[in] i_target the fapi2::Target MCBIST
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template<>
fapi2::ReturnCode after_memdiags( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
fapi2::ReturnCode l_rc;
for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))
{
fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc);
FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR);
fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc);
FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ);
l_ecc64_fir_reg.checkstop<MCA_FIR_MAINLINE_AUE>()
.recoverable_error<MCA_FIR_MAINLINE_UE>()
.checkstop<MCA_FIR_MAINLINE_IAUE>()
.recoverable_error<MCA_FIR_MAINLINE_IUE>();
// TODO RTC:165157 check for manufacturing flags and don't unmask this if
// thresholds policy is enabled.
l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINTENANCE_IUE>();
l_cal_fir_reg.recoverable_error<MCA_MBACALFIRQ_PORT_FAIL>();
FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR);
FAPI_TRY(l_cal_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ);
// Note: We also want to include the following setup RCD recovery and port fail
FAPI_TRY( mss::change_port_fail_disable(p, mss::LOW) );
FAPI_TRY( mss::change_rcd_recovery_disable(p, mss::LOW) );
}
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Unmask and setup actions for scrub related FIR
/// @param[in] i_target the fapi2::Target MCBIST
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
template<>
fapi2::ReturnCode after_background_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))
{
fapi2::ReturnCode l_rc;
fir::reg<MCA_FIR> l_ecc64_fir_reg(p, l_rc);
FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR);
l_ecc64_fir_reg.recoverable_error<MCA_FIR_MAINLINE_MPE_RANK_0_TO_7,
MCA_FIR_MAINLINE_MPE_RANK_0_TO_7_LEN>()
.recoverable_error<MCA_FIR_MAINLINE_NCE>()
.recoverable_error<MCA_FIR_MAINLINE_TCE>()
.recoverable_error<MCA_FIR_MAINLINE_IMPE>()
.recoverable_error<MCA_FIR_MAINTENANCE_IMPE>();
FAPI_TRY(l_ecc64_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR);
}
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
}
}
<|endoftext|> |
<commit_before>
#include "../utility.hpp"
#include "../String.hpp"
#include "./FlatDatastore.hpp"
#include <Hord/Error.hpp>
#include <Hord/IO/PropStream.hpp>
#include <ceformat/print.hpp>
#include <cstdio>
#include <type_traits>
#include <utility>
#include <new>
namespace Onsang {
namespace IO {
// class FlatDatastore implementation
#define HORD_SCOPE_CLASS_IDENT__ Onsang::IO::FlatDatastore
namespace {
HORD_FMT_UNSCOPED(
s_err_object_not_found,
"%s: object %08x does not exist"
);
/*static constexpr ceformat::Format const
s_fmt_object_id{
ONSANG_STR_LIT("%08x")
};*/
static char const* const
s_prop_type_abbr[]{
ONSANG_STR_LIT("i"),
ONSANG_STR_LIT("m"),
ONSANG_STR_LIT("s"),
ONSANG_STR_LIT("p"),
ONSANG_STR_LIT("a"),
};
static_assert(
static_cast<std::size_t>(Hord::IO::PropType::LAST)
== std::extent<decltype(s_prop_type_abbr)>::value,
"PropType abbreviation list is incomplete"
);
}; // anonymous namespace
static bool
type_supplies_prop(
Hord::Object::Type const type
) noexcept {
// FIXME: When datastores can contain other objects, this needs
// to be implemented properly.
// Currently containing only Node, which supplies all props
return Hord::Object::Type::Node == type;
}
static bool
prop_info_equal(
Hord::IO::PropInfo const& x,
Hord::IO::PropInfo const& y
) {
return
x.object_id == y.object_id &&
x.prop_type == y.prop_type;
}
Hord::IO::Datastore*
FlatDatastore::construct(
Hord::String root_path
) noexcept {
return new(std::nothrow) FlatDatastore(std::move(root_path));
}
FlatDatastore::type_info const
FlatDatastore::s_type_info{
FlatDatastore::construct
};
FlatDatastore::FlatDatastore(
Hord::String root_path
)
: base(std::move(root_path))
, m_lock()
, m_index()
, m_prop{
{},
{Hord::Object::NULL_ID, Hord::IO::PropType::metadata},
{},
false
}
{}
void
FlatDatastore::assign_prop(
Hord::IO::PropInfo const& prop_info,
bool const is_trash,
bool const is_input
) {
m_prop.info = prop_info;
m_prop.is_input = is_input;
String& path = m_prop.path;
Hord::String const& root_path = get_root_path();
path.reserve(
root_path.size() + // root
8u + // ID
(is_trash ? 6u : 0u) + // "/trash"
6u + // "/data/"
1u // prop name
);
// Taking runtime parsing cost over dynamic memory allocation
// (which would be ceformat which could do this more simply with a
// memstream which would be terrible... but actually safer... but
// also evil... I should do it <- ceformat TODO)
char obj_id_str[9u]; // uses 8 bytes (+1 for NUL)
std::snprintf(
obj_id_str,
static_cast<signed>(std::extent<decltype(obj_id_str)>::value),
"%08x",
prop_info.object_id
);
path
.assign(root_path)
.append(
(is_trash)
? "/trash/data/"
: "/data/"
)
.append(obj_id_str)
.append(s_prop_type_abbr[
enum_cast(prop_info.prop_type)
])
;
}
#define HORD_SCOPE_FUNC_IDENT__ acquire_stream
namespace {
HORD_FMT_SCOPED_FQN(
s_err_acquire_prop_unsupplied,
"prop %08x -> %s is not supplied for type %s"
);
HORD_FMT_SCOPED_FQN(
s_err_acquire_prop_open_failed,
"prop %08x -> %s is void (or open otherwise failed)"
);
} // anonymous namespace
void
FlatDatastore::acquire_stream(
Hord::IO::PropInfo const& prop_info,
bool const is_input
) {
auto const it = make_const(m_index).find(
prop_info.object_id
);
if (m_index.cend() == it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_not_found,
s_err_object_not_found,
HORD_SCOPE_FQN,
prop_info.object_id
);
}
Index::Entry const& entry = *it;
if (!type_supplies_prop(entry.type)) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_unsupplied,
s_err_acquire_prop_unsupplied,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type),
Hord::Object::get_type_name(entry.type)
);
}
// TODO: stat() path, throw other custom/standard error if
// non-existent
assign_prop(prop_info, entry.is_trash, is_input);
m_prop.stream.open(
m_prop.path,
std::ios_base::binary
| (is_input)
? std::ios_base::in
: std::ios_base::out
);
if (!m_prop.stream.is_open()) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_void,
s_err_acquire_prop_open_failed,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type)
);
}
base::enable_state(State::locked);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ release_stream
namespace {
HORD_FMT_SCOPED_FQN(
s_err_release_prop_not_locked,
"prop %08x -> %s is not locked"
);
} // anonymous namespace
void
FlatDatastore::release_stream(
Hord::IO::PropInfo const& prop_info,
bool const is_input
) {
// NB: Base checks is_locked() for us, which essentially ensures
// true==m_prop.stream.is_open(), but we want to unlock if the
// fstream somehow became closed in the interim.
// This implementation knows which object the prop belongs to,
// so there is no need to handle EC datastore_object_not_found
// from the spec (because we don't need to lookup anything to
// get at our representation of the prop).
if (
!prop_info_equal(m_prop.info, prop_info) ||
is_input != m_prop.is_input
) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_not_locked,
s_err_release_prop_not_locked,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type)
);
}
try {
// Ignore exceptions during close
m_prop.stream.close();
} catch (...) {}
m_prop.reset();
base::disable_state(State::locked);
}
#undef HORD_SCOPE_FUNC_IDENT__
// Hord::IO::Datastore implementation
#define HORD_SCOPE_FUNC_IDENT__ open_impl
void
FlatDatastore::open_impl() {
// NB: open() protects us from the ill logic of trying to open
// when the datastore is already open
// Path could've changed (and we don't assign it in the ctor)
m_lock.set_path(get_root_path());
try {
m_lock.acquire();
base::enable_state(State::opened);
} catch (Hord::Error&) {
HORD_THROW_ERROR_SCOPED_FQN(
Hord::ErrorCode::datastore_open_failed,
"failed to obtain hive lockfile"
);
} catch (...) {
throw;
}
}
#undef HORD_SCOPE_FUNC_IDENT__
void
FlatDatastore::close_impl() {
// NB: close() protects us from is_locked()
m_lock.release();
base::disable_state(State::opened);
}
// acquire
std::istream&
FlatDatastore::acquire_input_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
acquire_stream(prop_info, true);
return m_prop.stream;
}
std::ostream&
FlatDatastore::acquire_output_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
acquire_stream(prop_info, false);
return m_prop.stream;
}
// release
void
FlatDatastore::release_input_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
release_stream(prop_info, true);
}
void
FlatDatastore::release_output_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
release_stream(prop_info, false);
}
// objects
Hord::Object::ID
FlatDatastore::generate_id_impl(
Hord::System::IDGenerator& id_generator
) const noexcept {
// TODO: seed()? Are we allowed to mutate id_generator?
return id_generator.generate_unique(m_index);
}
#define HORD_SCOPE_FUNC_IDENT__ create_object_impl
namespace {
HORD_FMT_SCOPED_FQN(
s_err_create_object_already_exists,
"object %08x (of type %s) already exists"
);
} // anonymous namespace
void
FlatDatastore::create_object_impl(
Hord::Object::ID const object_id,
Hord::Object::Type const /*object_type*/
) {
// NB: Base protects us from prohibited types
auto const it = make_const(m_index).find(object_id);
if (m_index.cend() != it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_already_exists,
s_err_create_object_already_exists,
object_id,
Hord::Object::get_type_name(it->type)
);
}
// Currently only nodes are supported
m_index.insert(object_id);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ destroy_object_impl
void
FlatDatastore::destroy_object_impl(
Hord::Object::ID const object_id
) {
auto const it = m_index.find(object_id);
if (m_index.cend() == it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_not_found,
s_err_object_not_found,
HORD_SCOPE_FQN,
object_id
);
}
// Sending to trash; will purge later
// NB: is_trash has no bearing on hash, so this should not
// affect the container
const_cast<Index::Entry&>(*it).is_trash = true;
}
#undef HORD_SCOPE_FUNC_IDENT__
#undef HORD_SCOPE_CLASS_IDENT__ // FlatDatastore
} // namespace IO
} // namespace Onsang
<commit_msg>IO::FlatDatastore: bound-append obj_id_str instead of relying on NUL.<commit_after>
#include "../utility.hpp"
#include "../String.hpp"
#include "./FlatDatastore.hpp"
#include <Hord/Error.hpp>
#include <Hord/IO/PropStream.hpp>
#include <ceformat/print.hpp>
#include <cstdio>
#include <type_traits>
#include <utility>
#include <new>
namespace Onsang {
namespace IO {
// class FlatDatastore implementation
#define HORD_SCOPE_CLASS_IDENT__ Onsang::IO::FlatDatastore
namespace {
HORD_FMT_UNSCOPED(
s_err_object_not_found,
"%s: object %08x does not exist"
);
/*static constexpr ceformat::Format const
s_fmt_object_id{
ONSANG_STR_LIT("%08x")
};*/
static char const* const
s_prop_type_abbr[]{
ONSANG_STR_LIT("i"),
ONSANG_STR_LIT("m"),
ONSANG_STR_LIT("s"),
ONSANG_STR_LIT("p"),
ONSANG_STR_LIT("a"),
};
static_assert(
static_cast<std::size_t>(Hord::IO::PropType::LAST)
== std::extent<decltype(s_prop_type_abbr)>::value,
"PropType abbreviation list is incomplete"
);
}; // anonymous namespace
static bool
type_supplies_prop(
Hord::Object::Type const type
) noexcept {
// FIXME: When datastores can contain other objects, this needs
// to be implemented properly.
// Currently containing only Node, which supplies all props
return Hord::Object::Type::Node == type;
}
static bool
prop_info_equal(
Hord::IO::PropInfo const& x,
Hord::IO::PropInfo const& y
) {
return
x.object_id == y.object_id &&
x.prop_type == y.prop_type;
}
Hord::IO::Datastore*
FlatDatastore::construct(
Hord::String root_path
) noexcept {
return new(std::nothrow) FlatDatastore(std::move(root_path));
}
FlatDatastore::type_info const
FlatDatastore::s_type_info{
FlatDatastore::construct
};
FlatDatastore::FlatDatastore(
Hord::String root_path
)
: base(std::move(root_path))
, m_lock()
, m_index()
, m_prop{
{},
{Hord::Object::NULL_ID, Hord::IO::PropType::metadata},
{},
false
}
{}
void
FlatDatastore::assign_prop(
Hord::IO::PropInfo const& prop_info,
bool const is_trash,
bool const is_input
) {
m_prop.info = prop_info;
m_prop.is_input = is_input;
String& path = m_prop.path;
Hord::String const& root_path = get_root_path();
path.reserve(
root_path.size() + // root
8u + // ID
(is_trash ? 6u : 0u) + // "/trash"
6u + // "/data/"
1u // prop name
);
// Taking runtime parsing cost over dynamic memory allocation
// (which would be ceformat which could do this more simply with a
// memstream which would be terrible... but actually safer... but
// also evil... I should do it <- ceformat TODO)
char obj_id_str[9u]; // uses 8 bytes (+1 for NUL)
std::snprintf(
obj_id_str,
static_cast<signed>(std::extent<decltype(obj_id_str)>::value),
"%08x",
prop_info.object_id
);
path
.assign(root_path)
.append(
(is_trash)
? "/trash/data/"
: "/data/"
)
.append(obj_id_str, std::extent<decltype(obj_id_str)>::value)
.append(s_prop_type_abbr[
enum_cast(prop_info.prop_type)
])
;
}
#define HORD_SCOPE_FUNC_IDENT__ acquire_stream
namespace {
HORD_FMT_SCOPED_FQN(
s_err_acquire_prop_unsupplied,
"prop %08x -> %s is not supplied for type %s"
);
HORD_FMT_SCOPED_FQN(
s_err_acquire_prop_open_failed,
"prop %08x -> %s is void (or open otherwise failed)"
);
} // anonymous namespace
void
FlatDatastore::acquire_stream(
Hord::IO::PropInfo const& prop_info,
bool const is_input
) {
auto const it = make_const(m_index).find(
prop_info.object_id
);
if (m_index.cend() == it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_not_found,
s_err_object_not_found,
HORD_SCOPE_FQN,
prop_info.object_id
);
}
Index::Entry const& entry = *it;
if (!type_supplies_prop(entry.type)) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_unsupplied,
s_err_acquire_prop_unsupplied,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type),
Hord::Object::get_type_name(entry.type)
);
}
// TODO: stat() path, throw other custom/standard error if
// non-existent
assign_prop(prop_info, entry.is_trash, is_input);
m_prop.stream.open(
m_prop.path,
std::ios_base::binary
| (is_input)
? std::ios_base::in
: std::ios_base::out
);
if (!m_prop.stream.is_open()) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_void,
s_err_acquire_prop_open_failed,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type)
);
}
base::enable_state(State::locked);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ release_stream
namespace {
HORD_FMT_SCOPED_FQN(
s_err_release_prop_not_locked,
"prop %08x -> %s is not locked"
);
} // anonymous namespace
void
FlatDatastore::release_stream(
Hord::IO::PropInfo const& prop_info,
bool const is_input
) {
// NB: Base checks is_locked() for us, which essentially ensures
// true==m_prop.stream.is_open(), but we want to unlock if the
// fstream somehow became closed in the interim.
// This implementation knows which object the prop belongs to,
// so there is no need to handle EC datastore_object_not_found
// from the spec (because we don't need to lookup anything to
// get at our representation of the prop).
if (
!prop_info_equal(m_prop.info, prop_info) ||
is_input != m_prop.is_input
) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_prop_not_locked,
s_err_release_prop_not_locked,
prop_info.object_id,
Hord::IO::get_prop_type_name(prop_info.prop_type)
);
}
try {
// Ignore exceptions during close
m_prop.stream.close();
} catch (...) {}
m_prop.reset();
base::disable_state(State::locked);
}
#undef HORD_SCOPE_FUNC_IDENT__
// Hord::IO::Datastore implementation
#define HORD_SCOPE_FUNC_IDENT__ open_impl
void
FlatDatastore::open_impl() {
// NB: open() protects us from the ill logic of trying to open
// when the datastore is already open
// Path could've changed (and we don't assign it in the ctor)
m_lock.set_path(get_root_path());
try {
m_lock.acquire();
base::enable_state(State::opened);
} catch (Hord::Error&) {
HORD_THROW_ERROR_SCOPED_FQN(
Hord::ErrorCode::datastore_open_failed,
"failed to obtain hive lockfile"
);
} catch (...) {
throw;
}
}
#undef HORD_SCOPE_FUNC_IDENT__
void
FlatDatastore::close_impl() {
// NB: close() protects us from is_locked()
m_lock.release();
base::disable_state(State::opened);
}
// acquire
std::istream&
FlatDatastore::acquire_input_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
acquire_stream(prop_info, true);
return m_prop.stream;
}
std::ostream&
FlatDatastore::acquire_output_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
acquire_stream(prop_info, false);
return m_prop.stream;
}
// release
void
FlatDatastore::release_input_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
release_stream(prop_info, true);
}
void
FlatDatastore::release_output_stream_impl(
Hord::IO::PropInfo const& prop_info
) {
release_stream(prop_info, false);
}
// objects
Hord::Object::ID
FlatDatastore::generate_id_impl(
Hord::System::IDGenerator& id_generator
) const noexcept {
// TODO: seed()? Are we allowed to mutate id_generator?
return id_generator.generate_unique(m_index);
}
#define HORD_SCOPE_FUNC_IDENT__ create_object_impl
namespace {
HORD_FMT_SCOPED_FQN(
s_err_create_object_already_exists,
"object %08x (of type %s) already exists"
);
} // anonymous namespace
void
FlatDatastore::create_object_impl(
Hord::Object::ID const object_id,
Hord::Object::Type const /*object_type*/
) {
// NB: Base protects us from prohibited types
auto const it = make_const(m_index).find(object_id);
if (m_index.cend() != it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_already_exists,
s_err_create_object_already_exists,
object_id,
Hord::Object::get_type_name(it->type)
);
}
// Currently only nodes are supported
m_index.insert(object_id);
}
#undef HORD_SCOPE_FUNC_IDENT__
#define HORD_SCOPE_FUNC_IDENT__ destroy_object_impl
void
FlatDatastore::destroy_object_impl(
Hord::Object::ID const object_id
) {
auto const it = m_index.find(object_id);
if (m_index.cend() == it) {
HORD_THROW_ERROR_F(
Hord::ErrorCode::datastore_object_not_found,
s_err_object_not_found,
HORD_SCOPE_FQN,
object_id
);
}
// Sending to trash; will purge later
// NB: is_trash has no bearing on hash, so this should not
// affect the container
const_cast<Index::Entry&>(*it).is_trash = true;
}
#undef HORD_SCOPE_FUNC_IDENT__
#undef HORD_SCOPE_CLASS_IDENT__ // FlatDatastore
} // namespace IO
} // namespace Onsang
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include "Runtime/rstl.hpp"
#include "Runtime/Weapon/CProjectileInfo.hpp"
#include "Runtime/World/CPatterned.hpp"
#include "Runtime/World/CPathFindSearch.hpp"
namespace urde::MP1 {
class CAtomicAlpha : public CPatterned {
static constexpr u32 skBombCount = 4;
struct SBomb {
std::string x0_locatorName;
pas::ELocomotionType x10_locomotionType;
float x14_scaleTime = FLT_MAX;
SBomb(const std::string_view locator, pas::ELocomotionType locomotionType)
: x0_locatorName(locator.data()), x10_locomotionType(locomotionType) {}
};
bool x568_24_inRange : 1;
bool x568_25_invisible : 1;
bool x568_26_applyBeamAttraction : 1;
float x56c_bomdDropDelay;
float x570_bombReappearDelay;
float x574_bombRappearTime;
float x578_bombTime = 0.f;
u32 x57c_curBomb = 0;
CPathFindSearch x580_pathFind;
CSteeringBehaviors x664_steeringBehaviors;
CProjectileInfo x668_bombProjectile;
CModelData x690_bombModel;
rstl::reserved_vector<SBomb, skBombCount> x6dc_bombLocators;
public:
DEFINE_PATTERNED(AtomicAlpha)
CAtomicAlpha(TUniqueId, std::string_view, const CEntityInfo&, const zeus::CTransform&, CModelData&&,
const CActorParameters&, const CPatternedInfo&, CAssetId, const CDamageInfo&, float, float, float,
CAssetId, bool, bool);
void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;
void Render(const CStateManager&) const override;
void AddToRenderer(const zeus::CFrustum& frustum, const CStateManager& mgr) const override;
void Think(float, CStateManager&) override;
void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override;
CPathFindSearch* GetSearchPath() override { return &x580_pathFind; }
EWeaponCollisionResponseTypes GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&,
const CWeaponMode& wMode, EProjectileAttrib) const override {
return GetDamageVulnerability()->WeaponHits(wMode, false) ? EWeaponCollisionResponseTypes::AtomicAlpha
: EWeaponCollisionResponseTypes::AtomicAlphaReflect;
}
bool Leash(CStateManager& mgr, float) override;
bool AggressionCheck(CStateManager&, float) override;
void CollidedWith(TUniqueId, const CCollisionInfoList&, CStateManager&) override;
void Patrol(CStateManager&, EStateMsg, float) override;
void Attack(CStateManager&, EStateMsg, float) override;
CProjectileInfo* GetProjectileInfo() override { return &x668_bombProjectile; }
};
} // namespace urde::MP1
<commit_msg>CAtomicAlpha: Remove .data() call in SBomb constructor<commit_after>#pragma once
#include <string>
#include "Runtime/rstl.hpp"
#include "Runtime/Weapon/CProjectileInfo.hpp"
#include "Runtime/World/CPatterned.hpp"
#include "Runtime/World/CPathFindSearch.hpp"
namespace urde::MP1 {
class CAtomicAlpha : public CPatterned {
static constexpr u32 skBombCount = 4;
struct SBomb {
std::string x0_locatorName;
pas::ELocomotionType x10_locomotionType;
float x14_scaleTime = FLT_MAX;
SBomb(const std::string_view locator, pas::ELocomotionType locomotionType)
: x0_locatorName(locator), x10_locomotionType(locomotionType) {}
};
bool x568_24_inRange : 1;
bool x568_25_invisible : 1;
bool x568_26_applyBeamAttraction : 1;
float x56c_bomdDropDelay;
float x570_bombReappearDelay;
float x574_bombRappearTime;
float x578_bombTime = 0.f;
u32 x57c_curBomb = 0;
CPathFindSearch x580_pathFind;
CSteeringBehaviors x664_steeringBehaviors;
CProjectileInfo x668_bombProjectile;
CModelData x690_bombModel;
rstl::reserved_vector<SBomb, skBombCount> x6dc_bombLocators;
public:
DEFINE_PATTERNED(AtomicAlpha)
CAtomicAlpha(TUniqueId, std::string_view, const CEntityInfo&, const zeus::CTransform&, CModelData&&,
const CActorParameters&, const CPatternedInfo&, CAssetId, const CDamageInfo&, float, float, float,
CAssetId, bool, bool);
void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;
void Render(const CStateManager&) const override;
void AddToRenderer(const zeus::CFrustum& frustum, const CStateManager& mgr) const override;
void Think(float, CStateManager&) override;
void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override;
CPathFindSearch* GetSearchPath() override { return &x580_pathFind; }
EWeaponCollisionResponseTypes GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&,
const CWeaponMode& wMode, EProjectileAttrib) const override {
return GetDamageVulnerability()->WeaponHits(wMode, false) ? EWeaponCollisionResponseTypes::AtomicAlpha
: EWeaponCollisionResponseTypes::AtomicAlphaReflect;
}
bool Leash(CStateManager& mgr, float) override;
bool AggressionCheck(CStateManager&, float) override;
void CollidedWith(TUniqueId, const CCollisionInfoList&, CStateManager&) override;
void Patrol(CStateManager&, EStateMsg, float) override;
void Attack(CStateManager&, EStateMsg, float) override;
CProjectileInfo* GetProjectileInfo() override { return &x668_bombProjectile; }
};
} // namespace urde::MP1
<|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.
*/
#include "tscore/ink_config.h"
#include <unistd.h>
#include <getopt.h>
#include <cstdlib>
#include "sni_selector.h"
#include "sni_limiter.h"
// This holds the VC user arg index for the SNI limiters.
int gVCIdx = -1;
///////////////////////////////////////////////////////////////////////////////
// These continuations are "helpers" to the SNI limiter object. Putting them
// outside the class implementation is just cleaner.
//
int
sni_limit_cont(TSCont contp, TSEvent event, void *edata)
{
TSVConn vc = static_cast<TSVConn>(edata);
SniSelector *selector = static_cast<SniSelector *>(TSContDataGet(contp));
TSReleaseAssert(selector);
switch (event) {
case TS_EVENT_SSL_CLIENT_HELLO: {
int len;
const char *server_name = TSVConnSslSniGet(vc, &len);
std::string_view sni_name(server_name, len);
if (!sni_name.empty()) { // This should likely always succeed, but without it we can't do anything
SniRateLimiter *limiter = selector->find(sni_name);
TSDebug(PLUGIN_NAME, "CLIENT_HELLO on %.*s", static_cast<int>(sni_name.length()), sni_name.data());
if (limiter && !limiter->reserve()) {
if (!limiter->max_queue || limiter->full()) {
// We are running at limit, and the queue has reached max capacity, give back an error and be done.
TSVConnReenableEx(vc, TS_EVENT_ERROR);
TSDebug(PLUGIN_NAME, "Rejecting connection, we're at capacity and queue is full");
TSUserArgSet(vc, gVCIdx, nullptr);
limiter->incrementMetric(RATE_LIMITER_METRIC_REJECTED);
return TS_ERROR;
} else {
TSUserArgSet(vc, gVCIdx, reinterpret_cast<void *>(limiter));
limiter->push(vc, contp);
TSDebug(PLUGIN_NAME, "Queueing the VC, we are at capacity");
limiter->incrementMetric(RATE_LIMITER_METRIC_QUEUED);
}
} else {
// Not at limit on the handshake, we can re-enable
TSUserArgSet(vc, gVCIdx, reinterpret_cast<void *>(limiter));
TSVConnReenable(vc);
}
}
break;
}
case TS_EVENT_VCONN_CLOSE: {
SniRateLimiter *limiter = static_cast<SniRateLimiter *>(TSUserArgGet(vc, gVCIdx));
if (limiter) {
TSUserArgSet(vc, gVCIdx, nullptr);
limiter->release();
}
TSVConnReenable(vc);
break;
}
default:
TSDebug(PLUGIN_NAME, "Unknown event %d", static_cast<int>(event));
TSError("Unknown event in %s", PLUGIN_NAME);
break;
}
return TS_EVENT_CONTINUE;
}
///////////////////////////////////////////////////////////////////////////////
// Parse the configurations for the TXN limiter.
//
bool
SniRateLimiter::initialize(int argc, const char *argv[])
{
static const struct option longopt[] = {
{const_cast<char *>("limit"), required_argument, nullptr, 'l'},
{const_cast<char *>("queue"), required_argument, nullptr, 'q'},
{const_cast<char *>("maxage"), required_argument, nullptr, 'm'},
{const_cast<char *>("prefix"), required_argument, nullptr, 'p'},
{const_cast<char *>("tag"), required_argument, nullptr, 't'},
// EOF
{nullptr, no_argument, nullptr, '\0'},
};
while (true) {
int opt = getopt_long(argc, const_cast<char *const *>(argv), "", longopt, nullptr);
switch (opt) {
case 'l':
this->limit = strtol(optarg, nullptr, 10);
break;
case 'q':
this->max_queue = strtol(optarg, nullptr, 10);
break;
case 'm':
this->max_age = std::chrono::milliseconds(strtol(optarg, nullptr, 10));
break;
case 'p':
this->prefix = std::string(optarg);
break;
case 't':
this->tag = std::string(optarg);
break;
}
if (opt == -1) {
break;
}
}
return true;
}
<commit_msg>Rate Limit Plugin: Re-enable VConnection when SNI is empty (#8625)<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.
*/
#include "tscore/ink_config.h"
#include <unistd.h>
#include <getopt.h>
#include <cstdlib>
#include "sni_selector.h"
#include "sni_limiter.h"
// This holds the VC user arg index for the SNI limiters.
int gVCIdx = -1;
///////////////////////////////////////////////////////////////////////////////
// These continuations are "helpers" to the SNI limiter object. Putting them
// outside the class implementation is just cleaner.
//
int
sni_limit_cont(TSCont contp, TSEvent event, void *edata)
{
TSVConn vc = static_cast<TSVConn>(edata);
SniSelector *selector = static_cast<SniSelector *>(TSContDataGet(contp));
TSReleaseAssert(selector);
switch (event) {
case TS_EVENT_SSL_CLIENT_HELLO: {
int len;
const char *server_name = TSVConnSslSniGet(vc, &len);
std::string_view sni_name(server_name, len);
if (!sni_name.empty()) { // This should likely always succeed, but without it we can't do anything
SniRateLimiter *limiter = selector->find(sni_name);
TSDebug(PLUGIN_NAME, "CLIENT_HELLO on %.*s", static_cast<int>(sni_name.length()), sni_name.data());
if (limiter && !limiter->reserve()) {
if (!limiter->max_queue || limiter->full()) {
// We are running at limit, and the queue has reached max capacity, give back an error and be done.
TSVConnReenableEx(vc, TS_EVENT_ERROR);
TSDebug(PLUGIN_NAME, "Rejecting connection, we're at capacity and queue is full");
TSUserArgSet(vc, gVCIdx, nullptr);
limiter->incrementMetric(RATE_LIMITER_METRIC_REJECTED);
return TS_ERROR;
} else {
TSUserArgSet(vc, gVCIdx, reinterpret_cast<void *>(limiter));
limiter->push(vc, contp);
TSDebug(PLUGIN_NAME, "Queueing the VC, we are at capacity");
limiter->incrementMetric(RATE_LIMITER_METRIC_QUEUED);
}
} else {
// Not at limit on the handshake, we can re-enable
TSUserArgSet(vc, gVCIdx, reinterpret_cast<void *>(limiter));
TSVConnReenable(vc);
}
} else {
TSVConnReenable(vc);
}
break;
}
case TS_EVENT_VCONN_CLOSE: {
SniRateLimiter *limiter = static_cast<SniRateLimiter *>(TSUserArgGet(vc, gVCIdx));
if (limiter) {
TSUserArgSet(vc, gVCIdx, nullptr);
limiter->release();
}
TSVConnReenable(vc);
break;
}
default:
TSDebug(PLUGIN_NAME, "Unknown event %d", static_cast<int>(event));
TSError("Unknown event in %s", PLUGIN_NAME);
break;
}
return TS_EVENT_CONTINUE;
}
///////////////////////////////////////////////////////////////////////////////
// Parse the configurations for the TXN limiter.
//
bool
SniRateLimiter::initialize(int argc, const char *argv[])
{
static const struct option longopt[] = {
{const_cast<char *>("limit"), required_argument, nullptr, 'l'},
{const_cast<char *>("queue"), required_argument, nullptr, 'q'},
{const_cast<char *>("maxage"), required_argument, nullptr, 'm'},
{const_cast<char *>("prefix"), required_argument, nullptr, 'p'},
{const_cast<char *>("tag"), required_argument, nullptr, 't'},
// EOF
{nullptr, no_argument, nullptr, '\0'},
};
while (true) {
int opt = getopt_long(argc, const_cast<char *const *>(argv), "", longopt, nullptr);
switch (opt) {
case 'l':
this->limit = strtol(optarg, nullptr, 10);
break;
case 'q':
this->max_queue = strtol(optarg, nullptr, 10);
break;
case 'm':
this->max_age = std::chrono::milliseconds(strtol(optarg, nullptr, 10));
break;
case 'p':
this->prefix = std::string(optarg);
break;
case 't':
this->tag = std::string(optarg);
break;
}
if (opt == -1) {
break;
}
}
return true;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
// stl
#include <string>
#include <vector>
#include <fstream>
// boost
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include "topojson_featureset.hpp"
namespace mapnik { namespace topojson {
template <typename Context>
struct feature_generator : public boost::static_visitor<mapnik::feature_ptr>
{
feature_generator(Context & ctx, topology const& topo, std::size_t feature_id)
: ctx_(ctx),
topo_(topo),
feature_id_(feature_id) {}
feature_ptr operator() (point const& pt) const
{
return feature_ptr();
}
feature_ptr operator() (linestring const& line) const
{
return feature_ptr();
}
feature_ptr operator() (polygon const& poly) const
{
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx_,feature_id_));
std::unique_ptr<geometry_type> poly_ptr(new geometry_type(geometry_type::types::Polygon));
for (auto const& ring : poly.rings)
{
bool first = true;
for (auto const& index : ring)
{
double px = 0, py = 0;
bool reversed = index < 0;
index_type arc_index = reversed ? std::abs(index) - 1 : index;
auto const& coords = topo_.arcs[arc_index].coordinates;
std::deque<mapnik::topojson::coordinate> processed_coords;
for (auto const& pt : coords )
{
double x = pt.x;
double y = pt.y;
if (topo_.tr)
{
x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x;
y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y;
}
if (reversed)
processed_coords.emplace_front(coordinate{x,y});
else
processed_coords.emplace_back(coordinate{x,y});
}
for (auto const& c : processed_coords)
{
if (first)
{
first = false;
poly_ptr->move_to(c.x,c.y);
}
else poly_ptr->line_to(c.x,c.y);
}
}
poly_ptr->close_path();
}
feature->paths().push_back(poly_ptr.release());
if (poly.props)
{
for (auto const& p : *poly.props)
{
feature->put_new(std::get<0>(p), mapnik::value(1LL)/*std::get<1>(p)*/);
}
}
return feature;
}
template<typename T>
feature_ptr operator() (T const& ) const
{
return feature_ptr();
}
Context & ctx_;
topology const& topo_;
std::size_t feature_id_;
};
}}
topojson_featureset::topojson_featureset(mapnik::topojson::topology const& topo,
std::deque<std::size_t>::const_iterator index_itr,
std::deque<std::size_t>::const_iterator index_end)
: ctx_(std::make_shared<mapnik::context_type>()),
topo_(topo),
index_itr_(index_itr),
index_end_(index_end),
feature_id_ (0) {}
topojson_featureset::~topojson_featureset() {}
mapnik::feature_ptr topojson_featureset::next()
{
if (index_itr_ != index_end_)
{
std::size_t index = *index_itr_++;
if ( index < topo_.geometries.size())
{
mapnik::topojson::geometry const& geom = topo_.geometries[index];
mapnik::feature_ptr feature = boost::apply_visitor(
mapnik::topojson::feature_generator<mapnik::context_ptr>(ctx_, topo_, feature_id_++),
geom);
return feature;
}
}
return mapnik::feature_ptr();
}
<commit_msg>== topojson ==<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
// stl
#include <string>
#include <vector>
#include <fstream>
// boost
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include "topojson_featureset.hpp"
namespace mapnik { namespace topojson {
template <typename Context>
struct feature_generator : public boost::static_visitor<mapnik::feature_ptr>
{
feature_generator(Context & ctx, topology const& topo, std::size_t feature_id)
: ctx_(ctx),
topo_(topo),
feature_id_(feature_id) {}
feature_ptr operator() (point const& pt) const
{
return feature_ptr();
}
feature_ptr operator() (linestring const& line) const
{
return feature_ptr();
}
feature_ptr operator() (polygon const& poly) const
{
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx_,feature_id_));
std::unique_ptr<geometry_type> poly_ptr(new geometry_type(geometry_type::types::Polygon));
for (auto const& ring : poly.rings)
{
bool first = true;
for (auto const& index : ring)
{
double px = 0, py = 0;
bool reversed = index < 0;
index_type arc_index = reversed ? std::abs(index) - 1 : index;
auto const& coords = topo_.arcs[arc_index].coordinates;
std::deque<mapnik::topojson::coordinate> processed_coords;
for (auto const& pt : coords )
{
double x = pt.x;
double y = pt.y;
if (topo_.tr)
{
x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x;
y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y;
}
if (reversed)
processed_coords.emplace_front(coordinate{x,y});
else
processed_coords.emplace_back(coordinate{x,y});
}
for (auto const& c : processed_coords)
{
if (first)
{
first = false;
poly_ptr->move_to(c.x,c.y);
}
else poly_ptr->line_to(c.x,c.y);
}
}
poly_ptr->close_path();
}
feature->paths().push_back(poly_ptr.release());
if (poly.props)
{
for (auto const& p : *poly.props)
{
feature->put_new(std::get<0>(p), mapnik::value(1LL)/*std::get<1>(p)*/); // TODO
}
}
return feature;
}
template<typename T>
feature_ptr operator() (T const& ) const
{
return feature_ptr();
}
Context & ctx_;
topology const& topo_;
std::size_t feature_id_;
};
}}
topojson_featureset::topojson_featureset(mapnik::topojson::topology const& topo,
std::deque<std::size_t>::const_iterator index_itr,
std::deque<std::size_t>::const_iterator index_end)
: ctx_(std::make_shared<mapnik::context_type>()),
topo_(topo),
index_itr_(index_itr),
index_end_(index_end),
feature_id_ (0) {}
topojson_featureset::~topojson_featureset() {}
mapnik::feature_ptr topojson_featureset::next()
{
if (index_itr_ != index_end_)
{
std::size_t index = *index_itr_++;
if ( index < topo_.geometries.size())
{
mapnik::topojson::geometry const& geom = topo_.geometries[index];
mapnik::feature_ptr feature = boost::apply_visitor(
mapnik::topojson::feature_generator<mapnik::context_ptr>(ctx_, topo_, feature_id_++),
geom);
return feature;
}
}
return mapnik::feature_ptr();
}
<|endoftext|> |
<commit_before>/******************************************************
SENSOR LIBRARY:
Written by Enrico Formenti.
BSD license, check license.txt for more information
All text above must be included in any redistribution.
******************************************************/
/* Sensor library
DHT11.CPP: class methods for DHT11 class
written by Enrico Formenti
*/
#include "DHT11.h"
/**
\file DHT11.cpp
\brief Implementation of DHT11 class.
\author Enrico Formenti
\version 0.1
\date 2012-2013
\warning This software is provided "as is". The author is
not responsible for any damage of any kind caused by this
software. Use it at your own risk.
\copyright BSD license. See license.txt for more details.
All text above must be included in any redistribution.
*/
void DHT11::begin(void) {
uint8_t i;
firstreading = true;
// clear data bits
for(i=0;i<5;i++)
_data[i]=0;
// set up the pins!
pinMode(_pin, INPUT);
digitalWrite(_pin, HIGH);
_lastreadtime = 0;
}
void DHT11::read(void) {
uint8_t laststate = HIGH;
uint8_t counter;
uint8_t i;
unsigned long currenttime;
setError(ERROR_NONE);
currenttime = millis();
if (currenttime < _lastreadtime) // ie there was a rollover
_lastreadtime = 0;
if (!firstreading && ((currenttime - _lastreadtime) < 2000))
return; // return last correct measurement
firstreading = false;
_lastreadtime = millis();
// pull the pin high and wait 250 milliseconds
digitalWrite(_pin, HIGH);
delay(250);
// now pull it low for ~20 milliseconds
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delay(20);
cli();
digitalWrite(_pin, HIGH);
delayMicroseconds(40);
pinMode(_pin, INPUT);
// read in bits
for ( i=0; i<40; i++) {
// we should check how much time exactly it is lost here
for (counter=0; (counter<255)&&(digitalRead(_pin) == laststate); counter++)
delayMicroseconds(1);
laststate = digitalRead(_pin);
if (counter == 255) {
Error::setError(ERROR_TIME_OUT);
return;
}
if (counter > 6) // this value should be tried out !!!!
_data[i/5] |= (1 << (i%8));
}
sei();
// check we read 40 bits and that the checksum matches
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
if (counter != 40) {
Error::setError(ERROR_READ_FAILURE);
return;
}
if (_data[4] == ((_data[0] + _data[2]) & 0xFF)) {
Error::setError(ERROR_INVALID_CRC);
return;
}
}
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
float DHT11::getHumidity(void) {
read();
return (float)_data[1];
}
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
float DHT11::getTemperature(void) {
read();
return (float)_data[3];
}
<commit_msg>Implementation of DHT11 class (temperature sensor)<commit_after>/******************************************************
SENSOR LIBRARY:
Written by Enrico Formenti.
BSD license, check license.txt for more information
All text above must be included in any redistribution.
See License.txt
******************************************************/
/* Sensor library
DHT11.CPP: class methods for DHT11 class
written by Enrico Formenti
*/
#include "DHT11.h"
/**
\file DHT11.cpp
\brief Implementation of DHT11 class.
\author Enrico Formenti
\version 0.1
\date 2012-2013
\warning This software is provided "as is". The author is
not responsible for any damage of any kind caused by this
software. Use it at your own risk.
\copyright BSD license. See license.txt for more details.
All text above must be included in any redistribution.
*/
void DHT11::begin(void) {
uint8_t i;
firstreading = true;
// clear data bits
for(i=0;i<5;i++)
_data[i]=0;
// set up the pins!
pinMode(_pin, INPUT);
digitalWrite(_pin, HIGH);
_lastreadtime = 0;
}
void DHT11::read(void) {
uint8_t laststate = HIGH;
uint8_t counter;
uint8_t i;
unsigned long currenttime;
setError(ERROR_NONE);
currenttime = millis();
if (currenttime < _lastreadtime) // ie there was a rollover
_lastreadtime = 0;
if (!firstreading && ((currenttime - _lastreadtime) < 2000))
return; // return last correct measurement
firstreading = false;
_lastreadtime = millis();
// pull the pin high and wait 250 milliseconds
digitalWrite(_pin, HIGH);
delay(250);
// now pull it low for ~20 milliseconds
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delay(20);
cli();
digitalWrite(_pin, HIGH);
delayMicroseconds(40);
pinMode(_pin, INPUT);
// read in bits
for ( i=0; i<40; i++) {
// we should check how much time exactly it is lost here
for (counter=0; (counter<255)&&(digitalRead(_pin) == laststate); counter++)
delayMicroseconds(1);
laststate = digitalRead(_pin);
if (counter == 255) {
Error::setError(ERROR_TIME_OUT);
return;
}
if (counter > 6) // this value should be tried out !!!!
_data[i/5] |= (1 << (i%8));
}
sei();
// check we read 40 bits and that the checksum matches
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
if (counter != 40) {
Error::setError(ERROR_READ_FAILURE);
return;
}
if (_data[4] == ((_data[0] + _data[2]) & 0xFF)) {
Error::setError(ERROR_INVALID_CRC);
return;
}
}
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
float DHT11::getHumidity(void) {
read();
return (float)_data[1];
}
// pay attention that some guys say that _data[1] and _data[3] are always 0 on DHT11
// thus I've simplified the formula...
float DHT11::getTemperature(void) {
read();
return (float)_data[3];
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include "rtabmap_ros/MapData.h"
#include "rtabmap_ros/MsgConversion.h"
#include "rtabmap_ros/MapsManager.h"
#include <rtabmap/core/util3d_transforms.h>
#include <rtabmap/core/util3d.h>
#include <rtabmap/core/util3d_filtering.h>
#include <rtabmap/core/util3d_mapping.h>
#include <rtabmap/core/Compression.h>
#include <rtabmap/core/Graph.h>
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/utilite/UFile.h>
#include <pcl_ros/transforms.h>
#include <pcl_conversions/pcl_conversions.h>
#include <nav_msgs/OccupancyGrid.h>
#include <std_srvs/Empty.h>
using namespace rtabmap;
class MapAssembler
{
public:
MapAssembler(int & argc, char** argv)
{
ros::NodeHandle pnh("~");
ros::NodeHandle nh;
std::string configPath;
pnh.param("config_path", configPath, configPath);
//parameters
rtabmap::ParametersMap parameters;
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("Grid"));
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("StereoBM"));
if(!configPath.empty())
{
if(UFile::exists(configPath.c_str()))
{
ROS_INFO( "%s: Loading parameters from %s", ros::this_node::getName().c_str(), configPath.c_str());
rtabmap::ParametersMap allParameters;
Parameters::readINI(configPath.c_str(), allParameters);
// only update odometry parameters
for(ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
ParametersMap::iterator jter = allParameters.find(iter->first);
if(jter!=allParameters.end())
{
iter->second = jter->second;
}
}
}
else
{
ROS_ERROR( "Config file \"%s\" not found!", configPath.c_str());
}
}
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string vStr;
bool vBool;
int vInt;
double vDouble;
if(pnh.getParam(iter->first, vStr))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), vStr.c_str());
iter->second = vStr;
}
else if(pnh.getParam(iter->first, vBool))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uBool2Str(vBool).c_str());
iter->second = uBool2Str(vBool);
}
else if(pnh.getParam(iter->first, vDouble))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uNumber2Str(vDouble).c_str());
iter->second = uNumber2Str(vDouble);
}
else if(pnh.getParam(iter->first, vInt))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uNumber2Str(vInt).c_str());
iter->second = uNumber2Str(vInt);
}
if(iter->first.compare(Parameters::kVisMinInliers()) == 0 && atoi(iter->second.c_str()) < 8)
{
ROS_WARN( "Parameter min_inliers must be >= 8, setting to 8...");
iter->second = uNumber2Str(8);
}
}
rtabmap::ParametersMap argParameters = rtabmap::Parameters::parseArguments(argc, argv);
for(rtabmap::ParametersMap::iterator iter=argParameters.begin(); iter!=argParameters.end(); ++iter)
{
rtabmap::ParametersMap::iterator jter = parameters.find(iter->first);
if(jter!=parameters.end())
{
ROS_INFO( "Update %s parameter \"%s\"=\"%s\" from arguments", ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.c_str());
jter->second = iter->second;
}
}
// Backward compatibility
for(std::map<std::string, std::pair<bool, std::string> >::const_iterator iter=Parameters::getRemovedParameters().begin();
iter!=Parameters::getRemovedParameters().end();
++iter)
{
std::string vStr;
if(pnh.getParam(iter->first, vStr))
{
if(iter->second.first && parameters.find(iter->second.second) != parameters.end())
{
// can be migrated
parameters.at(iter->second.second)= vStr;
ROS_WARN( "%s: Parameter name changed: \"%s\" -> \"%s\". Please update your launch file accordingly. Value \"%s\" is still set to the new parameter name.",
ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.second.c_str(), vStr.c_str());
}
else
{
if(iter->second.second.empty())
{
ROS_ERROR( "%s: Parameter \"%s\" doesn't exist anymore!",
ros::this_node::getName().c_str(), iter->first.c_str());
}
else
{
ROS_ERROR( "%s: Parameter \"%s\" doesn't exist anymore! You may look at this similar parameter: \"%s\"",
ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.second.c_str());
}
}
}
}
mapsManager_.init(nh, pnh, ros::this_node::getName(), false);
mapsManager_.setParameters(parameters);
mapDataTopic_ = nh.subscribe("mapData", 1, &MapAssembler::mapDataReceivedCallback, this);
// private service
resetService_ = pnh.advertiseService("reset", &MapAssembler::reset, this);
}
~MapAssembler()
{
}
void mapDataReceivedCallback(const rtabmap_ros::MapDataConstPtr & msg)
{
UTimer timer;
std::map<int, Transform> poses;
std::multimap<int, Link> constraints;
Transform mapOdom;
rtabmap_ros::mapGraphFromROS(msg->graph, poses, constraints, mapOdom);
for(unsigned int i=0; i<msg->nodes.size(); ++i)
{
if(msg->nodes[i].image.size() ||
msg->nodes[i].depth.size() ||
msg->nodes[i].laserScan.size())
{
uInsert(nodes_, std::make_pair(msg->nodes[i].id, rtabmap_ros::nodeDataFromROS(msg->nodes[i])));
}
}
// create a tmp signature with latest sensory data
if(poses.size() && nodes_.find(poses.rbegin()->first) != nodes_.end())
{
Signature tmpS = nodes_.at(poses.rbegin()->first);
SensorData tmpData = tmpS.sensorData();
tmpData.setId(-1);
uInsert(nodes_, std::make_pair(-1, Signature(-1, -1, 0, tmpS.getStamp(), "", tmpS.getPose(), Transform(), tmpData)));
poses.insert(std::make_pair(-1, poses.rbegin()->second));
}
// Update maps
poses = mapsManager_.updateMapCaches(
poses,
0,
false,
false,
nodes_);
mapsManager_.publishMaps(poses, msg->header.stamp, msg->header.frame_id);
ROS_INFO("map_assembler: Publishing data = %fs", timer.ticks());
}
bool reset(std_srvs::Empty::Request&, std_srvs::Empty::Response&)
{
ROS_INFO("map_assembler: reset!");
mapsManager_.clear();
return true;
}
private:
MapsManager mapsManager_;
std::map<int, Signature> nodes_;
ros::Subscriber mapDataTopic_;
ros::ServiceServer resetService_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "map_assembler");
// process "--params" argument
for(int i=1;i<argc;++i)
{
if(strcmp(argv[i], "--params") == 0)
{
rtabmap::ParametersMap parameters;
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("Grid"));
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("StereoBM"));
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string str = "Param: " + iter->first + " = \"" + iter->second + "\"";
std::cout <<
str <<
std::setw(60 - str.size()) <<
" [" <<
rtabmap::Parameters::getDescription(iter->first).c_str() <<
"]" <<
std::endl;
}
ROS_WARN("Node will now exit after showing default parameters because "
"argument \"--params\" is detected!");
exit(0);
}
else if(strcmp(argv[i], "--udebug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
}
else if(strcmp(argv[i], "--uinfo") == 0)
{
ULogger::setLevel(ULogger::kInfo);
}
}
MapAssembler assembler(argc, argv);
ros::spin();
return 0;
}
<commit_msg>map_assembler: added backward compatibility parameters update from MapsManager<commit_after>/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include "rtabmap_ros/MapData.h"
#include "rtabmap_ros/MsgConversion.h"
#include "rtabmap_ros/MapsManager.h"
#include <rtabmap/core/util3d_transforms.h>
#include <rtabmap/core/util3d.h>
#include <rtabmap/core/util3d_filtering.h>
#include <rtabmap/core/util3d_mapping.h>
#include <rtabmap/core/Compression.h>
#include <rtabmap/core/Graph.h>
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/utilite/UFile.h>
#include <pcl_ros/transforms.h>
#include <pcl_conversions/pcl_conversions.h>
#include <nav_msgs/OccupancyGrid.h>
#include <std_srvs/Empty.h>
using namespace rtabmap;
class MapAssembler
{
public:
MapAssembler(int & argc, char** argv)
{
ros::NodeHandle pnh("~");
ros::NodeHandle nh;
std::string configPath;
pnh.param("config_path", configPath, configPath);
//parameters
rtabmap::ParametersMap parameters;
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("Grid"));
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("StereoBM"));
if(!configPath.empty())
{
if(UFile::exists(configPath.c_str()))
{
ROS_INFO( "%s: Loading parameters from %s", ros::this_node::getName().c_str(), configPath.c_str());
rtabmap::ParametersMap allParameters;
Parameters::readINI(configPath.c_str(), allParameters);
// only update odometry parameters
for(ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
ParametersMap::iterator jter = allParameters.find(iter->first);
if(jter!=allParameters.end())
{
iter->second = jter->second;
}
}
}
else
{
ROS_ERROR( "Config file \"%s\" not found!", configPath.c_str());
}
}
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string vStr;
bool vBool;
int vInt;
double vDouble;
if(pnh.getParam(iter->first, vStr))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), vStr.c_str());
iter->second = vStr;
}
else if(pnh.getParam(iter->first, vBool))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uBool2Str(vBool).c_str());
iter->second = uBool2Str(vBool);
}
else if(pnh.getParam(iter->first, vDouble))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uNumber2Str(vDouble).c_str());
iter->second = uNumber2Str(vDouble);
}
else if(pnh.getParam(iter->first, vInt))
{
ROS_INFO( "Setting %s parameter \"%s\"=\"%s\"", ros::this_node::getName().c_str(), iter->first.c_str(), uNumber2Str(vInt).c_str());
iter->second = uNumber2Str(vInt);
}
if(iter->first.compare(Parameters::kVisMinInliers()) == 0 && atoi(iter->second.c_str()) < 8)
{
ROS_WARN( "Parameter min_inliers must be >= 8, setting to 8...");
iter->second = uNumber2Str(8);
}
}
rtabmap::ParametersMap argParameters = rtabmap::Parameters::parseArguments(argc, argv);
for(rtabmap::ParametersMap::iterator iter=argParameters.begin(); iter!=argParameters.end(); ++iter)
{
rtabmap::ParametersMap::iterator jter = parameters.find(iter->first);
if(jter!=parameters.end())
{
ROS_INFO( "Update %s parameter \"%s\"=\"%s\" from arguments", ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.c_str());
jter->second = iter->second;
}
}
// Backward compatibility
for(std::map<std::string, std::pair<bool, std::string> >::const_iterator iter=Parameters::getRemovedParameters().begin();
iter!=Parameters::getRemovedParameters().end();
++iter)
{
std::string vStr;
if(pnh.getParam(iter->first, vStr))
{
if(iter->second.first && parameters.find(iter->second.second) != parameters.end())
{
// can be migrated
parameters.at(iter->second.second)= vStr;
ROS_WARN( "%s: Parameter name changed: \"%s\" -> \"%s\". Please update your launch file accordingly. Value \"%s\" is still set to the new parameter name.",
ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.second.c_str(), vStr.c_str());
}
else
{
if(iter->second.second.empty())
{
ROS_ERROR( "%s: Parameter \"%s\" doesn't exist anymore!",
ros::this_node::getName().c_str(), iter->first.c_str());
}
else
{
ROS_ERROR( "%s: Parameter \"%s\" doesn't exist anymore! You may look at this similar parameter: \"%s\"",
ros::this_node::getName().c_str(), iter->first.c_str(), iter->second.second.c_str());
}
}
}
}
mapsManager_.init(nh, pnh, ros::this_node::getName(), false);
mapsManager_.backwardCompatibilityParameters(pnh, parameters);
mapsManager_.setParameters(parameters);
mapDataTopic_ = nh.subscribe("mapData", 1, &MapAssembler::mapDataReceivedCallback, this);
// private service
resetService_ = pnh.advertiseService("reset", &MapAssembler::reset, this);
}
~MapAssembler()
{
}
void mapDataReceivedCallback(const rtabmap_ros::MapDataConstPtr & msg)
{
UTimer timer;
std::map<int, Transform> poses;
std::multimap<int, Link> constraints;
Transform mapOdom;
rtabmap_ros::mapGraphFromROS(msg->graph, poses, constraints, mapOdom);
for(unsigned int i=0; i<msg->nodes.size(); ++i)
{
if(msg->nodes[i].image.size() ||
msg->nodes[i].depth.size() ||
msg->nodes[i].laserScan.size())
{
uInsert(nodes_, std::make_pair(msg->nodes[i].id, rtabmap_ros::nodeDataFromROS(msg->nodes[i])));
}
}
// create a tmp signature with latest sensory data
if(poses.size() && nodes_.find(poses.rbegin()->first) != nodes_.end())
{
Signature tmpS = nodes_.at(poses.rbegin()->first);
SensorData tmpData = tmpS.sensorData();
tmpData.setId(-1);
uInsert(nodes_, std::make_pair(-1, Signature(-1, -1, 0, tmpS.getStamp(), "", tmpS.getPose(), Transform(), tmpData)));
poses.insert(std::make_pair(-1, poses.rbegin()->second));
}
// Update maps
poses = mapsManager_.updateMapCaches(
poses,
0,
false,
false,
nodes_);
mapsManager_.publishMaps(poses, msg->header.stamp, msg->header.frame_id);
ROS_INFO("map_assembler: Publishing data = %fs", timer.ticks());
}
bool reset(std_srvs::Empty::Request&, std_srvs::Empty::Response&)
{
ROS_INFO("map_assembler: reset!");
mapsManager_.clear();
return true;
}
private:
MapsManager mapsManager_;
std::map<int, Signature> nodes_;
ros::Subscriber mapDataTopic_;
ros::ServiceServer resetService_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "map_assembler");
// process "--params" argument
for(int i=1;i<argc;++i)
{
if(strcmp(argv[i], "--params") == 0)
{
rtabmap::ParametersMap parameters;
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("Grid"));
uInsert(parameters, rtabmap::Parameters::getDefaultParameters("StereoBM"));
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string str = "Param: " + iter->first + " = \"" + iter->second + "\"";
std::cout <<
str <<
std::setw(60 - str.size()) <<
" [" <<
rtabmap::Parameters::getDescription(iter->first).c_str() <<
"]" <<
std::endl;
}
ROS_WARN("Node will now exit after showing default parameters because "
"argument \"--params\" is detected!");
exit(0);
}
else if(strcmp(argv[i], "--udebug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
}
else if(strcmp(argv[i], "--uinfo") == 0)
{
ULogger::setLevel(ULogger::kInfo);
}
}
MapAssembler assembler(argc, argv);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#include "Enemy.h"
#include "SDL.h"
#include "InputHandler.h"
Enemy::Enemy(const LoaderParams* pParams) : SDLGameObject(pParams) { }
void Enemy::draw()
{
SDLGameObject::draw(); //now we use SDLGameObject
}
//Update function for Enemy object
void Enemy::update()
{
m_velocity.setX(0);
m_velocity.setY(0);
handleInput(); //handles the input from joystick [2nd controller]
m_currentFrame = int(((SDL_GetTicks() / 100) % 6));
SDLGameObject::update();
}
void Enemy::clean()
{
//blank clean() function
}
//Enemy class uses the Second Joystick
void Enemy::handleInput()
{
//check if a second controller is available and use it for enemy object
if ((TheInputHandler::Instance()->joysticksInitialised()) && (SDL_NumJoysticks() > 1))
{
//for analog sticks of the second joystick
if ((TheInputHandler::Instance()->xvalue(1, 1) > 0) || (TheInputHandler::Instance()->xvalue(1, 1) < 0))
{
//if we are moving the player with analog stick while pressing Y
//it will get an acceleration of 2 in that direction
m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(1, 1));
if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow)
{
//give the player some acceleration
m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->yvalue(1, 1) > 0) || (TheInputHandler::Instance()->yvalue(1, 1) < 0))
{
m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(1, 1));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->xvalue(1, 2) > 0) || (TheInputHandler::Instance()->xvalue(1, 2) < 0))
{
m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(1, 2));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->yvalue(1, 2) > 0) || (TheInputHandler::Instance()->yvalue(1, 2) < 0))
{
m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(1, 2));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(1, 1));
}
}
}
//no mouse control for enemy
//keyboard A W S D for movement, Right Shift for acceleration
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_D))
{
m_velocity.setX(2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setX(2.5);
}
}
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_A))
{
m_velocity.setX(-2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setX(-2.5);
}
}
//remember the cartesian plane is inverted along Y Axis
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_W))
{
m_velocity.setY(-2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setY(-2.5);
}
}
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_S))
{
m_velocity.setY(2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setY(2.5);
}
}
}<commit_msg>(Enemy) Acceleration becomes 0 when L Shift if released<commit_after>#include "Enemy.h"
#include "SDL.h"
#include "InputHandler.h"
Enemy::Enemy(const LoaderParams* pParams) : SDLGameObject(pParams) { }
void Enemy::draw()
{
SDLGameObject::draw(); //now we use SDLGameObject
}
//Update function for Enemy object
void Enemy::update()
{
m_velocity.setX(0);
m_velocity.setY(0);
m_acceleration.setX(0);
m_acceleration.setY(0);
handleInput(); //handles the input from joystick [2nd controller]
m_currentFrame = int(((SDL_GetTicks() / 100) % 6));
SDLGameObject::update();
}
void Enemy::clean()
{
//blank clean() function
}
//Enemy class uses the Second Joystick
void Enemy::handleInput()
{
//check if a second controller is available and use it for enemy object
if ((TheInputHandler::Instance()->joysticksInitialised()) && (SDL_NumJoysticks() > 1))
{
//for analog sticks of the second joystick
if ((TheInputHandler::Instance()->xvalue(1, 1) > 0) || (TheInputHandler::Instance()->xvalue(1, 1) < 0))
{
//if we are moving the player with analog stick while pressing Y
//it will get an acceleration of 2 in that direction
m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(1, 1));
if (TheInputHandler::Instance()->getButtonState(0, 3)) //Button 3(Yellow)
{
//give the player some acceleration
m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->yvalue(1, 1) > 0) || (TheInputHandler::Instance()->yvalue(1, 1) < 0))
{
m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(1, 1));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->xvalue(1, 2) > 0) || (TheInputHandler::Instance()->xvalue(1, 2) < 0))
{
m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(1, 2));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(1, 1));
}
}
if ((TheInputHandler::Instance()->yvalue(1, 2) > 0) || (TheInputHandler::Instance()->yvalue(1, 2) < 0))
{
m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(1, 2));
if (TheInputHandler::Instance()->getButtonState(1, 3))
{
m_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(1, 1));
}
}
}
//no mouse control for enemy
//keyboard A W S D for movement, Right Shift for acceleration
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_D))
{
m_velocity.setX(2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setX(2.5);
}
}
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_A))
{
m_velocity.setX(-2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setX(-2.5);
}
}
//remember the cartesian plane is inverted along Y Axis
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_W))
{
m_velocity.setY(-2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setY(-2.5);
}
}
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_S))
{
m_velocity.setY(2);
//check if Right Ctrl is pressed, provide acc. if true
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT))
{
m_acceleration.setY(2.5);
}
}
}<|endoftext|> |
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/linearAlg2D.h" //Distance from point to line.
#include "MergeInfillLines.h"
namespace cura
{
MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan)
{
//Just copy the parameters to their fields.
}
coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const
{
Point previous_point = path_start;
coord_t result = 0;
for (const Point point : path.points)
{
result += vSize(point - previous_point);
previous_point = point;
}
return result;
}
/*
* first_is_already_merged == false
*
* o o
* / /
* / /
* / + / ---> -(t)-o-----o
* / /
* / /
* o o
*
* travel (t) to first location is done through first_path_start_changed and new_first_path_start.
* this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is
* accounted for in the volume.
*
* first_is_already_merged == true
*
* o
* /
* /
* o-----o + / ---> o-----------o or with slight o-----o-----o
* / / / bend /
* / / / /
* o o o o
*
*/
bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
Point average_first_path;
coord_t first_path_length = calcPathLength(first_path_start, first_path);
coord_t first_path_length_flow = first_path_length * first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines.
if (first_is_already_merged)
{
// take second point of path, first_path.points[0]
average_first_path = first_path.points[0];
}
else
{
average_first_path += first_path_start;
for (const Point point : first_path.points)
{
average_first_path += point;
}
average_first_path /= (first_path.points.size() + 1);
}
coord_t second_path_length = calcPathLength(second_path_start, second_path);
Point average_second_path = second_path_start;
for (const Point point : second_path.points)
{
average_second_path += point;
}
coord_t second_path_length_flow = second_path_length *= second_path.flow;
average_second_path /= (second_path.points.size() + 1);
// predict new length and flow, returning false doesn't quite work as expected
// this is to pretend huge blobs, but they don't occur anymore after tweaking
// coord_t new_length = first_path_length;
// if (first_is_already_merged)
// {
// // check if the new point is a good extension of last part of existing polyline
// // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
// if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]) == 0)
// {
// new_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);
// first_path.points[first_path.points.size() - 1] = average_second_path;
// } else {
// first_path.points.push_back(average_second_path);
// }
// new_length += vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);
// }
// else
// {
// new_length -= vSize(first_path.points.back() - first_path_start);
// first_path.points.clear();
// new_first_path_start = average_first_path;
// first_path.points.push_back(average_second_path);
// new_length += vSize(first_path.points.back() - new_first_path_start);
// }
// double new_flow = ((first_path_length_flow + second_path_length_flow) / static_cast<double>(new_length));
// if (new_flow > 3.5)
// {
// std::cout << "new flow:" << new_flow << "\n";
// std::cout << "new length: " << new_length << "\n";
// std::cout << "length factor: " << (first_path_length + second_path_length) / static_cast<double>(new_length) << "\n";
// //return false;
// }
if (first_is_already_merged)
{
// check if the new point is a good extension of last part of existing polyline
// because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]) == 0)
{
first_path.points[first_path.points.size() - 1] = average_second_path;
} else {
first_path.points.push_back(average_second_path);
}
}
else
{
first_path.points.clear();
new_first_path_start = average_first_path;
first_path.points.push_back(average_second_path);
}
coord_t new_path_length = calcPathLength(first_path_start, first_path);
first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length;
std::cout << "new flow:" << first_path.flow << "\n";
return true;
}
bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
const Point first_path_end = first_path.points.back();
const Point second_path_end = second_path.points.back();
const coord_t line_width = first_path.config->getLineWidth();
//Lines may be adjacent side-by-side then.
Point first_path_leave_point;
coord_t merged_size2;
if (first_is_already_merged)
{
first_path_leave_point = first_path.points.back(); // this is the point that's going to merge
} else {
first_path_leave_point = (first_path_start + first_path_end) / 2;
}
const Point second_path_destination_point = (second_path_start + second_path_end) / 2;
const Point merged_direction = second_path_destination_point - first_path_leave_point;
if (first_is_already_merged)
{
merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced
}
else
{
merged_size2 = vSize2(merged_direction);
}
if (merged_size2 > 25 * line_width * line_width)
{
return false; //Lines are too far away from each other.
}
if (merged_direction.X == 0 && merged_direction.Y == 0)
{
return true; // we can just disregard the second point as it's exactly at the leave point of the first path.
}
// Max 1 line width to the side of the merged_direction
if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > 4 * line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > 4 * line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > 4 * line_width * line_width
//|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 // 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes
)
{
return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off.
}
if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen
{
return false;
}
return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start);
}
bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const
{
/* Algorithm overview:
1. Loop over all lines to see if they can be merged.
1a. Check if two adjacent lines can be merged (skipping travel moves in
between).
1b. If they can, merge both lines into the first line.
1c. If they are merged, check next that the first line can be merged
with the line after the second line.
2. Do a second iteration over all paths to remove the tombstones. */
std::vector<size_t> remove_path_indices;
std::set<size_t> is_merged;
std::set<size_t> removed; // keep track of what we already removed, so don't remove it again
//For each two adjacent lines, see if they can be merged.
size_t first_path_index = 0;
Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten
size_t second_path_index = 1;
for (; second_path_index < paths.size(); second_path_index++)
{
GCodePath& first_path = paths[first_path_index];
GCodePath& second_path = paths[second_path_index];
Point second_path_start = paths[second_path_index - 1].points.back();
if (second_path.config->isTravelPath())
{
continue; //Skip travel paths, we're looking for the first non-travel path.
}
bool allow_try_merge = true;
// see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel
// we're checking the travels here
if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere
{
allow_try_merge = false;
}
if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())
{
allow_try_merge = false;
}
if (first_path.config->isTravelPath()) //Don't merge travel moves.
{
allow_try_merge = false;
}
if (first_path.config != second_path.config) //Only merge lines that have the same type.
{
allow_try_merge = false;
}
if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines.
{
allow_try_merge = false;
}
const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();
if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)
{
// For now we only merge simple lines, not polylines, to keep it simple.
// If the first line is already a merged line, then allow it.
allow_try_merge = false;
}
Point new_first_path_start;
if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start))
{
if (!first_is_already_merged)
{
paths[first_path_index - 1].points.back().X = new_first_path_start.X;
paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;
}
/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update
first_path_index. */
for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)
{
if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)
{
remove_path_indices.push_back(to_delete_index);
removed.insert(to_delete_index);
}
}
is_merged.insert(first_path_index);
}
else
{
/* If we do not combine, the next iteration we must simply merge the
second path with the line after it. */
first_path_index = second_path_index;
first_path_start = second_path_start;
}
}
//Delete all removed lines in one pass so that we need to move lines less often.
if (!remove_path_indices.empty())
{
size_t path_index = remove_path_indices[0];
for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)
{
for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)
{
paths[path_index] = paths[path_index + removed_position]; //Shift all paths.
}
}
for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end.
{
paths[path_index] = paths[path_index + remove_path_indices.size()];
}
paths.erase(paths.begin() + path_index, paths.end());
return true;
}
else
{
return false;
}
}
}//namespace cura
<commit_msg>Remove debug print. CURA-5535<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/linearAlg2D.h" //Distance from point to line.
#include "MergeInfillLines.h"
namespace cura
{
MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan)
{
//Just copy the parameters to their fields.
}
coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const
{
Point previous_point = path_start;
coord_t result = 0;
for (const Point point : path.points)
{
result += vSize(point - previous_point);
previous_point = point;
}
return result;
}
/*
* first_is_already_merged == false
*
* o o
* / /
* / /
* / + / ---> -(t)-o-----o
* / /
* / /
* o o
*
* travel (t) to first location is done through first_path_start_changed and new_first_path_start.
* this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is
* accounted for in the volume.
*
* first_is_already_merged == true
*
* o
* /
* /
* o-----o + / ---> o-----------o or with slight o-----o-----o
* / / / bend /
* / / / /
* o o o o
*
*/
bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
Point average_first_path;
coord_t first_path_length = calcPathLength(first_path_start, first_path);
coord_t first_path_length_flow = first_path_length * first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines.
if (first_is_already_merged)
{
// take second point of path, first_path.points[0]
average_first_path = first_path.points[0];
}
else
{
average_first_path += first_path_start;
for (const Point point : first_path.points)
{
average_first_path += point;
}
average_first_path /= (first_path.points.size() + 1);
}
coord_t second_path_length = calcPathLength(second_path_start, second_path);
Point average_second_path = second_path_start;
for (const Point point : second_path.points)
{
average_second_path += point;
}
coord_t second_path_length_flow = second_path_length *= second_path.flow;
average_second_path /= (second_path.points.size() + 1);
// predict new length and flow, returning false doesn't quite work as expected
// this is to pretend huge blobs, but they don't occur anymore after tweaking
// coord_t new_length = first_path_length;
// if (first_is_already_merged)
// {
// // check if the new point is a good extension of last part of existing polyline
// // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
// if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]) == 0)
// {
// new_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);
// first_path.points[first_path.points.size() - 1] = average_second_path;
// } else {
// first_path.points.push_back(average_second_path);
// }
// new_length += vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]);
// }
// else
// {
// new_length -= vSize(first_path.points.back() - first_path_start);
// first_path.points.clear();
// new_first_path_start = average_first_path;
// first_path.points.push_back(average_second_path);
// new_length += vSize(first_path.points.back() - new_first_path_start);
// }
// double new_flow = ((first_path_length_flow + second_path_length_flow) / static_cast<double>(new_length));
// if (new_flow > 3.5)
// {
// std::cout << "new flow:" << new_flow << "\n";
// std::cout << "new length: " << new_length << "\n";
// std::cout << "length factor: " << (first_path_length + second_path_length) / static_cast<double>(new_length) << "\n";
// //return false;
// }
if (first_is_already_merged)
{
// check if the new point is a good extension of last part of existing polyline
// because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]) == 0)
{
first_path.points[first_path.points.size() - 1] = average_second_path;
} else {
first_path.points.push_back(average_second_path);
}
}
else
{
first_path.points.clear();
new_first_path_start = average_first_path;
first_path.points.push_back(average_second_path);
}
coord_t new_path_length = calcPathLength(first_path_start, first_path);
first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length;
return true;
}
bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
const Point first_path_end = first_path.points.back();
const Point second_path_end = second_path.points.back();
const coord_t line_width = first_path.config->getLineWidth();
//Lines may be adjacent side-by-side then.
Point first_path_leave_point;
coord_t merged_size2;
if (first_is_already_merged)
{
first_path_leave_point = first_path.points.back(); // this is the point that's going to merge
} else {
first_path_leave_point = (first_path_start + first_path_end) / 2;
}
const Point second_path_destination_point = (second_path_start + second_path_end) / 2;
const Point merged_direction = second_path_destination_point - first_path_leave_point;
if (first_is_already_merged)
{
merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced
}
else
{
merged_size2 = vSize2(merged_direction);
}
if (merged_size2 > 25 * line_width * line_width)
{
return false; //Lines are too far away from each other.
}
if (merged_direction.X == 0 && merged_direction.Y == 0)
{
return true; // we can just disregard the second point as it's exactly at the leave point of the first path.
}
// Max 1 line width to the side of the merged_direction
if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > 4 * line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > 4 * line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > 4 * line_width * line_width
//|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 // 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes
)
{
return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off.
}
if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen
{
return false;
}
return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start);
}
bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const
{
/* Algorithm overview:
1. Loop over all lines to see if they can be merged.
1a. Check if two adjacent lines can be merged (skipping travel moves in
between).
1b. If they can, merge both lines into the first line.
1c. If they are merged, check next that the first line can be merged
with the line after the second line.
2. Do a second iteration over all paths to remove the tombstones. */
std::vector<size_t> remove_path_indices;
std::set<size_t> is_merged;
std::set<size_t> removed; // keep track of what we already removed, so don't remove it again
//For each two adjacent lines, see if they can be merged.
size_t first_path_index = 0;
Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten
size_t second_path_index = 1;
for (; second_path_index < paths.size(); second_path_index++)
{
GCodePath& first_path = paths[first_path_index];
GCodePath& second_path = paths[second_path_index];
Point second_path_start = paths[second_path_index - 1].points.back();
if (second_path.config->isTravelPath())
{
continue; //Skip travel paths, we're looking for the first non-travel path.
}
bool allow_try_merge = true;
// see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel
// we're checking the travels here
if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere
{
allow_try_merge = false;
}
if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())
{
allow_try_merge = false;
}
if (first_path.config->isTravelPath()) //Don't merge travel moves.
{
allow_try_merge = false;
}
if (first_path.config != second_path.config) //Only merge lines that have the same type.
{
allow_try_merge = false;
}
if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines.
{
allow_try_merge = false;
}
const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();
if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)
{
// For now we only merge simple lines, not polylines, to keep it simple.
// If the first line is already a merged line, then allow it.
allow_try_merge = false;
}
Point new_first_path_start;
if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start))
{
if (!first_is_already_merged)
{
paths[first_path_index - 1].points.back().X = new_first_path_start.X;
paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;
}
/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update
first_path_index. */
for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)
{
if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)
{
remove_path_indices.push_back(to_delete_index);
removed.insert(to_delete_index);
}
}
is_merged.insert(first_path_index);
}
else
{
/* If we do not combine, the next iteration we must simply merge the
second path with the line after it. */
first_path_index = second_path_index;
first_path_start = second_path_start;
}
}
//Delete all removed lines in one pass so that we need to move lines less often.
if (!remove_path_indices.empty())
{
size_t path_index = remove_path_indices[0];
for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)
{
for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)
{
paths[path_index] = paths[path_index + removed_position]; //Shift all paths.
}
}
for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end.
{
paths[path_index] = paths[path_index + remove_path_indices.size()];
}
paths.erase(paths.begin() + path_index, paths.end());
return true;
}
else
{
return false;
}
}
}//namespace cura
<|endoftext|> |
<commit_before>#include "../ht.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
//#include <memory.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
namespace wi {
class FileStream : public Stream
{
public:
FileStream();
~FileStream();
bool Init(char *pszMode, char *pszFile, char *pszDelete, char *pszFinal);
virtual void Close();
virtual dword Read(void *pv, dword cb);
virtual dword Write(void *pv, dword cb);
virtual bool IsSuccess();
private:
bool m_fSuccess;
FILE *m_pf;
char m_szFile[PATH_MAX];
char m_szDelete[PATH_MAX];
char m_szFinal[PATH_MAX];
};
FileStream::FileStream()
{
m_fSuccess = true;
m_pf = NULL;
m_szFile[0] = 0;
m_szDelete[0] = 0;
m_szFinal[0] = 0;
}
FileStream::~FileStream()
{
Assert(m_pf == NULL);
}
bool FileStream::Init(char *pszMode, char *pszFile, char *pszDelete, char *pszFinal)
{
m_pf = fopen(pszFile, pszMode);
if (m_pf == NULL)
return false;
strcpy(m_szFile, pszFile);
if (pszDelete != NULL)
strcpy(m_szDelete, pszDelete);
if (pszFinal != NULL)
strcpy(m_szFinal, pszFinal);
return true;
}
void FileStream::Close()
{
fclose(m_pf);
m_pf = NULL;
// Delete and rename file if no error
if (m_fSuccess) {
if (m_szDelete[0] != 0) {
unlink(m_szDelete);
}
if (m_szFinal[0] != 0) {
rename(m_szFile, m_szFinal);
}
}
}
dword FileStream::Read(void *pv, dword cb)
{
size_t cbT = fread(pv, 1, cb, m_pf);
if (cb != cbT)
m_fSuccess = false;
return cbT;
}
dword FileStream::Write(void *pv, dword cb)
{
size_t cbT = fwrite(pv, 1, cb, m_pf);
if (cb != cbT)
m_fSuccess = false;
return cbT;
}
bool FileStream::IsSuccess()
{
return m_fSuccess;
}
void PrependSavesDirectory(char *pszIn, char *pszOut)
{
strcpy(pszOut, IPhone::GetSaveGamesDir());
strcat(pszOut, "/");
strcat(pszOut, pszIn);
}
bool FindSaveGame(int nGame, char *psz, int cb, int *pc = NULL)
{
if (pc != NULL)
*pc = 0;
// This is the prefix of the file being looked for
char szCompare[PATH_MAX];
sprintf(szCompare, "htsave%d_", nGame);
int cchCompare = strlen(szCompare);
// This is the special save game that is only used
// when the game exits and reloads right away
char szReinitializeSave[20];
sprintf(szReinitializeSave, "htsave%d_", knGameReinitializeSave);
int cchReinitializeSave = strlen(szReinitializeSave);
// Enum files in this directory
char szFileSpec[PATH_MAX];
PrependSavesDirectory("", szFileSpec);
DIR *pdir = opendir(szFileSpec);
if (pdir == NULL) {
return false;
}
int c = 0;
dirent *pdent;
while ((pdent = readdir(pdir)) != NULL) {
// Only consider save games, because if the desired save game is
// not found, we need to count "slots".
if (strncmp("htsave", pdent->d_name, 6) != 0) {
continue;
}
// Save game found?
if (strncmp(szCompare, pdent->d_name, cchCompare) == 0) {
if (psz != NULL)
strncpyz(psz, pdent->d_name, cb);
closedir(pdir);
return true;
}
// Count save games but don't count the temporary "Reinitialize"
// saved game
if (strncmp(szReinitializeSave, pdent->d_name,
cchReinitializeSave) == 0) {
continue;
}
// Count this save game as a slot
c++;
}
closedir(pdir);
// Didn't find the saved game, but did count the number of occupied slots
if (pc != NULL)
*pc = c;
return false;
}
int HostGetSaveGameCount()
{
int c;
FindSaveGame(-1, NULL, 0, &c);
return c;
}
bool HostGetSaveGameName(int nGame, char *psz, int cb, Date *pdate, int *pnHours24, int *pnMinutes, int *pnSeconds)
{
// Find the game
char szT[PATH_MAX];
if (!FindSaveGame(nGame, szT, sizeof(szT))) {
strncpyz(psz, "-- Empty --", cb);
return false;
}
char szPath[PATH_MAX];
PrependSavesDirectory(szT, szPath);
// Get the creation time in hours24, minutes
struct stat st;
if (stat(szPath, &st) > 0) {
return false;
}
time_t tim = 0;
struct tm *ptm = localtime(&tim);
*pnHours24 = ptm->tm_hour;
*pnMinutes = ptm->tm_min;
*pnSeconds = ptm->tm_sec;
pdate->nDay = ptm->tm_mday;
pdate->nMonth = ptm->tm_mon;
pdate->nYear = ptm->tm_year + 1900;
// Copy over filename, lose prefix
char *pszName = strchr(szT, '_') + 1;
int cbName = strlen(pszName) - 4 + 1;
strncpyz(psz, pszName, _min(cb, cbName));
// restore '#' to ':'
char *pchInvalid = psz;
do {
pchInvalid = strchr(pchInvalid, '#');
if (pchInvalid != 0)
*pchInvalid = ':';
} while (pchInvalid != 0);
return true;
}
Stream *HostNewSaveGameStream(int nGame, char *pszName)
{
// Get the old file name - we'll delete this if successful
char szOld[PATH_MAX];
char szOldFull[PATH_MAX];
if (!FindSaveGame(nGame, szOld, sizeof(szOld))) {
szOldFull[0] = 0;
} else {
PrependSavesDirectory(szOld, szOldFull);
}
// New file name
char szNew[PATH_MAX];
sprintf(szNew, "htsave%d_%s.bin", nGame, pszName);
// windows disallows ':' in a filename, so sub those out
char *pchInvalid = szNew;
do {
pchInvalid = strchr(pchInvalid, ':');
if (pchInvalid != 0)
*pchInvalid = '#';
} while (pchInvalid != 0);
char szNewFull[PATH_MAX];
PrependSavesDirectory(szNew, szNewFull);
// Get stream over temp file
FileStream *pstm = new FileStream();
if (pstm == NULL)
return NULL;
// If save is successful, szOld will be deleted and httempsave.bin
// will be renamed to szNew
char szTempSaveFull[PATH_MAX];
PrependSavesDirectory("httempsave.bin", szTempSaveFull);
if (!pstm->Init("wb", szTempSaveFull, szOldFull, szNewFull)) {
delete pstm;
return NULL;
}
return (Stream *)pstm;
}
Stream *HostOpenSaveGameStream(int nGame, bool fDelete)
{
char szT[PATH_MAX];
if (!FindSaveGame(nGame, szT, sizeof(szT)))
return NULL;
// rename to a temporary file before opening
char szTFull[PATH_MAX];
PrependSavesDirectory(szT, szTFull);
char szTempNameFull[PATH_MAX];
PrependSavesDirectory(kszTempName, szTempNameFull);
rename(szTFull, szTempNameFull);
// Get stream over temp file
FileStream *pstm = new FileStream();
if (pstm == NULL)
return NULL;
// If load is successful, and fDelete is True szTempName will be deleted
// if fDelete is false szTempName will be renamed to szSaveGame
if (!pstm->Init("rb", szTempNameFull, fDelete ? szTempNameFull : NULL, fDelete ? NULL : szTFull)) {
delete pstm;
return NULL;
}
return (Stream *)pstm;
}
bool HostDeleteSaveGame(char *psz, int nGame)
{
// if nGame is > 0, delete that, otherwise if psz is non-null delete that
// return true if we deleted something
char szSaveGame[PATH_MAX];
if (psz == NULL) {
if (!FindSaveGame(nGame, szSaveGame, sizeof(szSaveGame)))
return false;
} else {
strncpyz(szSaveGame, psz, sizeof(szSaveGame));
}
char szSaveGameFull[PATH_MAX];
PrependSavesDirectory(szSaveGame, szSaveGameFull);
if (psz != NULL) {
unlink(szSaveGameFull);
return true;
}
return false;
}
} // namespace wi
<commit_msg>Use the file modified time, not 0. This change requires default alignment.<commit_after>#include "../ht.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
//#include <memory.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
namespace wi {
class FileStream : public Stream
{
public:
FileStream();
~FileStream();
bool Init(char *pszMode, char *pszFile, char *pszDelete, char *pszFinal);
virtual void Close();
virtual dword Read(void *pv, dword cb);
virtual dword Write(void *pv, dword cb);
virtual bool IsSuccess();
private:
bool m_fSuccess;
FILE *m_pf;
char m_szFile[PATH_MAX];
char m_szDelete[PATH_MAX];
char m_szFinal[PATH_MAX];
};
FileStream::FileStream()
{
m_fSuccess = true;
m_pf = NULL;
m_szFile[0] = 0;
m_szDelete[0] = 0;
m_szFinal[0] = 0;
}
FileStream::~FileStream()
{
Assert(m_pf == NULL);
}
bool FileStream::Init(char *pszMode, char *pszFile, char *pszDelete, char *pszFinal)
{
m_pf = fopen(pszFile, pszMode);
if (m_pf == NULL)
return false;
strcpy(m_szFile, pszFile);
if (pszDelete != NULL)
strcpy(m_szDelete, pszDelete);
if (pszFinal != NULL)
strcpy(m_szFinal, pszFinal);
return true;
}
void FileStream::Close()
{
fclose(m_pf);
m_pf = NULL;
// Delete and rename file if no error
if (m_fSuccess) {
if (m_szDelete[0] != 0) {
unlink(m_szDelete);
}
if (m_szFinal[0] != 0) {
rename(m_szFile, m_szFinal);
}
}
}
dword FileStream::Read(void *pv, dword cb)
{
size_t cbT = fread(pv, 1, cb, m_pf);
if (cb != cbT)
m_fSuccess = false;
return cbT;
}
dword FileStream::Write(void *pv, dword cb)
{
size_t cbT = fwrite(pv, 1, cb, m_pf);
if (cb != cbT)
m_fSuccess = false;
return cbT;
}
bool FileStream::IsSuccess()
{
return m_fSuccess;
}
void PrependSavesDirectory(char *pszIn, char *pszOut)
{
strcpy(pszOut, IPhone::GetSaveGamesDir());
strcat(pszOut, "/");
strcat(pszOut, pszIn);
}
bool FindSaveGame(int nGame, char *psz, int cb, int *pc = NULL)
{
if (pc != NULL)
*pc = 0;
// This is the prefix of the file being looked for
char szCompare[PATH_MAX];
sprintf(szCompare, "htsave%d_", nGame);
int cchCompare = strlen(szCompare);
// This is the special save game that is only used
// when the game exits and reloads right away
char szReinitializeSave[20];
sprintf(szReinitializeSave, "htsave%d_", knGameReinitializeSave);
int cchReinitializeSave = strlen(szReinitializeSave);
// Enum files in this directory
char szFileSpec[PATH_MAX];
PrependSavesDirectory("", szFileSpec);
DIR *pdir = opendir(szFileSpec);
if (pdir == NULL) {
return false;
}
int c = 0;
dirent *pdent;
while ((pdent = readdir(pdir)) != NULL) {
// Only consider save games, because if the desired save game is
// not found, we need to count "slots".
if (strncmp("htsave", pdent->d_name, 6) != 0) {
continue;
}
// Save game found?
if (strncmp(szCompare, pdent->d_name, cchCompare) == 0) {
if (psz != NULL)
strncpyz(psz, pdent->d_name, cb);
closedir(pdir);
return true;
}
// Count save games but don't count the temporary "Reinitialize"
// saved game
if (strncmp(szReinitializeSave, pdent->d_name,
cchReinitializeSave) == 0) {
continue;
}
// Count this save game as a slot
c++;
}
closedir(pdir);
// Didn't find the saved game, but did count the number of occupied slots
if (pc != NULL)
*pc = c;
return false;
}
int HostGetSaveGameCount()
{
int c;
FindSaveGame(-1, NULL, 0, &c);
return c;
}
bool HostGetSaveGameName(int nGame, char *psz, int cb, Date *pdate, int *pnHours24, int *pnMinutes, int *pnSeconds)
{
// Find the game
char szT[PATH_MAX];
if (!FindSaveGame(nGame, szT, sizeof(szT))) {
strncpyz(psz, "-- Empty --", cb);
return false;
}
char szPath[PATH_MAX];
PrependSavesDirectory(szT, szPath);
// Get the creation time in hours24, minutes
struct stat st;
if (stat(szPath, &st) > 0) {
return false;
}
time_t tim = st.st_mtimespec.tv_sec;
struct tm *ptm = localtime(&tim);
*pnHours24 = ptm->tm_hour;
*pnMinutes = ptm->tm_min;
*pnSeconds = ptm->tm_sec;
pdate->nDay = ptm->tm_mday;
pdate->nMonth = ptm->tm_mon;
pdate->nYear = ptm->tm_year + 1900;
// Copy over filename, lose prefix
char *pszName = strchr(szT, '_') + 1;
int cbName = strlen(pszName) - 4 + 1;
strncpyz(psz, pszName, _min(cb, cbName));
// restore '#' to ':'
char *pchInvalid = psz;
do {
pchInvalid = strchr(pchInvalid, '#');
if (pchInvalid != 0)
*pchInvalid = ':';
} while (pchInvalid != 0);
return true;
}
Stream *HostNewSaveGameStream(int nGame, char *pszName)
{
// Get the old file name - we'll delete this if successful
char szOld[PATH_MAX];
char szOldFull[PATH_MAX];
if (!FindSaveGame(nGame, szOld, sizeof(szOld))) {
szOldFull[0] = 0;
} else {
PrependSavesDirectory(szOld, szOldFull);
}
// New file name
char szNew[PATH_MAX];
sprintf(szNew, "htsave%d_%s.bin", nGame, pszName);
// windows disallows ':' in a filename, so sub those out
char *pchInvalid = szNew;
do {
pchInvalid = strchr(pchInvalid, ':');
if (pchInvalid != 0)
*pchInvalid = '#';
} while (pchInvalid != 0);
char szNewFull[PATH_MAX];
PrependSavesDirectory(szNew, szNewFull);
// Get stream over temp file
FileStream *pstm = new FileStream();
if (pstm == NULL)
return NULL;
// If save is successful, szOld will be deleted and httempsave.bin
// will be renamed to szNew
char szTempSaveFull[PATH_MAX];
PrependSavesDirectory("httempsave.bin", szTempSaveFull);
if (!pstm->Init("wb", szTempSaveFull, szOldFull, szNewFull)) {
delete pstm;
return NULL;
}
return (Stream *)pstm;
}
Stream *HostOpenSaveGameStream(int nGame, bool fDelete)
{
char szT[PATH_MAX];
if (!FindSaveGame(nGame, szT, sizeof(szT)))
return NULL;
// rename to a temporary file before opening
char szTFull[PATH_MAX];
PrependSavesDirectory(szT, szTFull);
char szTempNameFull[PATH_MAX];
PrependSavesDirectory(kszTempName, szTempNameFull);
rename(szTFull, szTempNameFull);
// Get stream over temp file
FileStream *pstm = new FileStream();
if (pstm == NULL)
return NULL;
// If load is successful, and fDelete is True szTempName will be deleted
// if fDelete is false szTempName will be renamed to szSaveGame
if (!pstm->Init("rb", szTempNameFull, fDelete ? szTempNameFull : NULL, fDelete ? NULL : szTFull)) {
delete pstm;
return NULL;
}
return (Stream *)pstm;
}
bool HostDeleteSaveGame(char *psz, int nGame)
{
// if nGame is > 0, delete that, otherwise if psz is non-null delete that
// return true if we deleted something
char szSaveGame[PATH_MAX];
if (psz == NULL) {
if (!FindSaveGame(nGame, szSaveGame, sizeof(szSaveGame)))
return false;
} else {
strncpyz(szSaveGame, psz, sizeof(szSaveGame));
}
char szSaveGameFull[PATH_MAX];
PrependSavesDirectory(szSaveGame, szSaveGameFull);
if (psz != NULL) {
unlink(szSaveGameFull);
return true;
}
return false;
}
} // namespace wi
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "fdispatch.h"
#include <vespa/searchcore/util/log.h>
#include <vespa/searchcore/util/eventloop.h>
#include <vespa/searchcore/fdispatch/search/querycacheutil.h>
#include <vespa/searchcore/fdispatch/search/nodemanager.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/config/helper/configgetter.hpp>
#include "engineadapter.h"
#include "rpc.h"
#include <thread>
#include <vespa/log/log.h>
LOG_SETUP(".fdispatch");
#ifndef V_TAG
#define V_TAG "NOTAG"
#endif
using search::fs4transport::FS4PersistentPacketStreamer;
using vespa::config::search::core::FdispatchrcConfig;
using vespa::config::search::core::internal::InternalFdispatchrcType;
using document::CompressionConfig;
char FastS_VersionTag[] = V_TAG;
namespace fdispatch
{
FastS_FNETAdapter::FastS_FNETAdapter(FastS_AppContext *appCtx)
: _appCtx(appCtx),
_nodeManager(),
_timeKeeper(NULL),
_transport(NULL),
_last_now(0.0),
_live_counter(0),
_task()
{ }
FastS_FNETAdapter::~FastS_FNETAdapter()
{
fini();
}
void
FastS_FNETAdapter::init()
{
_nodeManager = _appCtx->GetNodeManager();
_timeKeeper = _appCtx->GetTimeKeeper();
_transport = _appCtx->GetFNETTransport();
_last_now = _timeKeeper->GetTime();
_task.reset(new MyTask(_transport->GetScheduler(), *this));
_task->ScheduleNow();
}
void
FastS_FNETAdapter::perform()
{
double now = _timeKeeper->GetTime();
double delta = now - _last_now;
if (delta >= 3.0) {
LOG(warning, "FNET loop high latency: %.3f", delta);
}
_last_now = now;
++_live_counter;
_nodeManager->CheckEvents(_timeKeeper);
}
void
FastS_FNETAdapter::fini()
{
if (_task) {
_task->Kill();
_task.reset();
}
}
Fdispatch::~Fdispatch()
{
if (_transportServer) {
_transportServer->shutDown(); // sync shutdown
}
_FNET_adapter.fini();
if (_nodeManager) {
_nodeManager->ShutdownConfig();
}
if (_transport && _transportStarted) {
_transport->ShutDown(true); // sync shutdown
}
if (_rpc) {
_rpc->ShutDown(); // sync shutdown
}
LOG(debug, "Will close threadpool");
_mypool->Close();
LOG(debug, "Has closed threadpool");
_transportServer.reset();
_engineAdapter.reset();
_nodeManager.reset();
_transport.reset();
_rpc.reset();
_mypool.reset();
}
FNET_Transport *
Fdispatch::GetFNETTransport()
{
return _transport.get();
}
FNET_Scheduler *
Fdispatch::GetFNETScheduler()
{
return (_transport) ? _transport->GetScheduler() : nullptr;
}
FastS_NodeManager *
Fdispatch::GetNodeManager()
{
return _nodeManager.get();
}
FastS_DataSetCollection *
Fdispatch::GetDataSetCollection()
{
return ( _nodeManager) ? _nodeManager->GetDataSetCollection() : nullptr;
}
FastOS_ThreadPool *
Fdispatch::GetThreadPool()
{
return _mypool.get();
}
bool
Fdispatch::Failed()
{
return ( (_transportServer && _transportServer->isFailed())) || _needRestart;
}
bool
Fdispatch::CheckTempFail()
{
bool ret;
bool failflag = _nodeManager->GetTempFail();
unsigned int FNETLiveCounter;
ret = true;
FNETLiveCounter = _FNET_adapter.GetLiveCounter();
if (FNETLiveCounter == _lastFNETLiveCounter) {
if (_FNETLiveCounterFailed) {
failflag = true; // Still failure
} else if (!_FNETLiveCounterDanger) {
_FNETLiveCounterDanger = true;
_FNETLiveCounterDangerStart.SetNow();
} else if (_FNETLiveCounterDangerStart.MilliSecsToNow() >= 6000) {
LOG(error, "fdispatch::Fdispatch::CheckTempFail: FNET inactive for 6 seconds, deadlock ?");
_FNETLiveCounterFailed = true; // Note that we failed
failflag = true; // Force temporary failure
} else if (_FNETLiveCounterDangerStart.MilliSecsToNow() >= 3000 &&
!_FNETLiveCounterWarned) {
_FNETLiveCounterWarned = true;
LOG(warning, "fdispatch::Fdispatch::CheckTempFail: FNET inactive for 3 seconds");
}
} else {
if (_FNETLiveCounterFailed || _FNETLiveCounterWarned) {
LOG(warning, "fdispatch::Fdispatch::CheckTempFail: FNET active again");
}
_FNETLiveCounterFailed = false;
_FNETLiveCounterWarned = false;
_FNETLiveCounterDanger = false;
_lastFNETLiveCounter = FNETLiveCounter;
}
if (failflag == _tempFail)
return ret;
if (_transportServer) {
if (failflag) {
_transportServer->setListen(false);
LOG(error, "Disabling fnet server interface");
} else {
_transportServer->setListen(true);
LOG(info, "Reenabling fnet server interface");
}
}
_tempFail = failflag;
return ret;
}
/**
* Make the httpd and Monitor, and let a Thread execute each.
* Set up stuff as specified in the fdispatch-rc-file.
*/
Fdispatch::Fdispatch(const config::ConfigUri &configUri)
: _mypool(),
_engineAdapter(),
_transportServer(),
_componentConfig(),
_nodeManager(),
_transport(),
_FNET_adapter(this),
_rpc(),
_config(),
_configUri(configUri),
_fdispatchrcFetcher(configUri.getContext()),
_rndGen(),
_partition(0),
_tempFail(false),
_FNETLiveCounterDanger(false),
_FNETLiveCounterWarned(false),
_FNETLiveCounterFailed(false),
_transportStarted(false),
_lastFNETLiveCounter(false),
_FNETLiveCounterDangerStart(),
_timeouts(0u),
_checkLimit(0u),
_healthPort(0),
_needRestart(false)
{
int64_t cfgGen = -1;
_config = config::ConfigGetter<FdispatchrcConfig>::
getConfig(cfgGen, _configUri.getConfigId(), _configUri.getContext());
LOG(config, "fdispatch version %s (RPC-port: %d, transport at %d)",
FastS_VersionTag, _config->frtport, _config->ptport);
_componentConfig.addConfig(vespalib::ComponentConfigProducer::Config("fdispatch", cfgGen,
"config only obtained at startup"));
_fdispatchrcFetcher.subscribe<FdispatchrcConfig>(configUri.getConfigId(), this);
_fdispatchrcFetcher.start();
}
namespace {
bool needRestart(const FdispatchrcConfig & curr, const FdispatchrcConfig & next)
{
if (curr.frtport != next.frtport) {
LOG(warning, "FRT port has changed from %d to %d.", curr.frtport, next.frtport);
return true;
}
if (curr.ptport != next.ptport) {
LOG(warning, "PT port has changed from %d to %d.", curr.ptport, next.ptport);
return true;
}
if (curr.healthport != next.healthport) {
LOG(warning, "Health port has changed from %d to %d.", curr.healthport, next.healthport);
return true;
}
return false;
}
}
void Fdispatch::configure(std::unique_ptr<FdispatchrcConfig> cfg)
{
if (cfg && _config) {
if ( needRestart(*_config, *cfg) ) {
const int sleepMS = (0.100 + 2 * _rndGen.nextDouble()) * 1000;
LOG(warning, "Will restart by abort in %d ms.", sleepMS);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepMS));
_needRestart.store(true);
}
}
}
namespace {
CompressionConfig::Type
convert(InternalFdispatchrcType::Packetcompresstype type)
{
switch (type) {
case InternalFdispatchrcType::LZ4: return CompressionConfig::LZ4;
default: return CompressionConfig::LZ4;
}
}
}
bool
Fdispatch::Init()
{
int maxthreads;
_tempFail = false;
_FNETLiveCounterDanger = false;
_FNETLiveCounterWarned = false;
_FNETLiveCounterFailed = false;
_lastFNETLiveCounter = 0;
_timeouts = 0;
_checkLimit = 60;
FS4PersistentPacketStreamer::Instance.SetCompressionLimit(_config->packetcompresslimit);
FS4PersistentPacketStreamer::Instance.SetCompressionLevel(_config->packetcompresslevel);
FS4PersistentPacketStreamer::Instance.SetCompressionType(convert(_config->packetcompresstype));
LOG(debug, "Creating FNET transport");
_transport = std::make_unique<FNET_Transport>(_config->transportthreads);
// grab node slowness limit defaults
FastS_DataSetDesc::SetDefaultSlowQueryLimitFactor(_config->defaultslowquerylimitfactor);
FastS_DataSetDesc::SetDefaultSlowQueryLimitBias(_config->defaultslowquerylimitbias);
FastS_DataSetDesc::SetDefaultSlowDocsumLimitFactor(_config->defaultslowdocsumlimitfactor);
FastS_DataSetDesc::SetDefaultSlowDocsumLimitBias(_config->defaultslowdocsumlimitbias);
maxthreads = _config->maxthreads;
_mypool = std::make_unique<FastOS_ThreadPool>(256 * 1024, maxthreads);
// Max interval betw read from socket.
FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent] = _config->maxsocksilent;
if (_transport) {
_transport->SetIOCTimeOut((uint32_t) (FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent] * 1000.0));
}
char timestr[40];
FastS_TimeOut::WriteTime(timestr, sizeof(timestr), FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent]);
LOG(debug, "VERBOSE: Max time between successful read from a socket: %s", timestr);
FastS_QueryCacheUtil::_systemMaxHits = std::numeric_limits<int>::max();
LOG(debug, "VERBOSE: maxhits: %d", FastS_QueryCacheUtil::_systemMaxHits);
FastS_QueryCacheUtil::_maxOffset = std::numeric_limits<int>::max();
const uint32_t linesize = 1;
if (FastS_QueryCacheUtil::_systemMaxHits < linesize
&& FastS_QueryCacheUtil::_maxOffset < linesize - FastS_QueryCacheUtil::_systemMaxHits) {
LOG(warning, "maxoffset must be >= %d! (overriding config value)", linesize - FastS_QueryCacheUtil::_systemMaxHits);
FastS_QueryCacheUtil::_maxOffset = linesize - FastS_QueryCacheUtil::_systemMaxHits;
}
LOG(debug, "VERBOSE: maxoffset: %d", FastS_QueryCacheUtil::_maxOffset);
_partition = _config->partition;
int ptportnum = _config->ptport;
LOG(debug, "Using port number %d", ptportnum);
_nodeManager = std::make_unique<FastS_NodeManager>(_componentConfig, this, _partition);
GetFNETTransport()->SetTCPNoDelay(_config->transportnodelay);
GetFNETTransport()->SetDirectWrite(_config->transportdirectwrite);
if (ptportnum == 0) {
throw vespalib::IllegalArgumentException("fdispatchrc.ptportnum must be non-zero, most likely an issue with config delivery.");
}
_engineAdapter = std::make_unique<fdispatch::EngineAdapter>(this, _mypool.get());
_transportServer = std::make_unique<TransportServer>(*_engineAdapter, *_engineAdapter, *_engineAdapter, ptportnum, search::engine::TransportServer::DEBUG_ALL);
_transportServer->setTCPNoDelay(_config->transportnodelay);
_transportServer->setDirectWrite(_config->transportdirectwrite);
if (!_transportServer->start()) {
_transportServer.reset();
_engineAdapter.reset();
LOG(error, "CRITICAL: Failed to init upwards FNET transport on port %d", ptportnum);
return false;
}
_nodeManager->SubscribePartMap(_configUri);
if (_config->frtport != 0) {
_rpc = std::make_unique<FastS_fdispatch_RPC>(this);
if (!_rpc->Init(_config->frtport, _configUri.getConfigId())) {
LOG(error, "RPC init failed");
_rpc.reset();
}
} else {
_rpc.reset();
}
// Kick off fdispatch administrative threads.
if (_transport) {
_FNET_adapter.init();
bool rc = _transport->Start(_mypool.get());
if (rc) {
LOG(debug, "Started FNET transport");
_transportStarted = true;
} else {
LOG(error, "Failed to start FNET transport");
}
}
FastOS_Thread::Sleep(1000);
if (_rpc) {
_rpc->Start();
}
_healthPort = _config->healthport;
return true;
}
void
Fdispatch::logPerformance()
{
_nodeManager->logPerformance();
}
uint32_t
Fdispatch::getDispatchLevel()
{
return _config->dispatchlevel;
}
}
<commit_msg>If you need to restart, just do it right away. You are probably taking up somebody elses port.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "fdispatch.h"
#include "engineadapter.h"
#include "rpc.h"
#include <vespa/searchcore/fdispatch/search/querycacheutil.h>
#include <vespa/searchcore/fdispatch/search/nodemanager.h>
#include <vespa/searchcore/util/eventloop.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/config/helper/configgetter.hpp>
#include <vespa/log/log.h>
LOG_SETUP(".fdispatch");
#ifndef V_TAG
#define V_TAG "NOTAG"
#endif
using search::fs4transport::FS4PersistentPacketStreamer;
using vespa::config::search::core::FdispatchrcConfig;
using vespa::config::search::core::internal::InternalFdispatchrcType;
using document::CompressionConfig;
char FastS_VersionTag[] = V_TAG;
namespace fdispatch
{
FastS_FNETAdapter::FastS_FNETAdapter(FastS_AppContext *appCtx)
: _appCtx(appCtx),
_nodeManager(),
_timeKeeper(NULL),
_transport(NULL),
_last_now(0.0),
_live_counter(0),
_task()
{ }
FastS_FNETAdapter::~FastS_FNETAdapter()
{
fini();
}
void
FastS_FNETAdapter::init()
{
_nodeManager = _appCtx->GetNodeManager();
_timeKeeper = _appCtx->GetTimeKeeper();
_transport = _appCtx->GetFNETTransport();
_last_now = _timeKeeper->GetTime();
_task.reset(new MyTask(_transport->GetScheduler(), *this));
_task->ScheduleNow();
}
void
FastS_FNETAdapter::perform()
{
double now = _timeKeeper->GetTime();
double delta = now - _last_now;
if (delta >= 3.0) {
LOG(warning, "FNET loop high latency: %.3f", delta);
}
_last_now = now;
++_live_counter;
_nodeManager->CheckEvents(_timeKeeper);
}
void
FastS_FNETAdapter::fini()
{
if (_task) {
_task->Kill();
_task.reset();
}
}
Fdispatch::~Fdispatch()
{
if (_transportServer) {
_transportServer->shutDown(); // sync shutdown
}
_FNET_adapter.fini();
if (_nodeManager) {
_nodeManager->ShutdownConfig();
}
if (_transport && _transportStarted) {
_transport->ShutDown(true); // sync shutdown
}
if (_rpc) {
_rpc->ShutDown(); // sync shutdown
}
LOG(debug, "Will close threadpool");
_mypool->Close();
LOG(debug, "Has closed threadpool");
_transportServer.reset();
_engineAdapter.reset();
_nodeManager.reset();
_transport.reset();
_rpc.reset();
_mypool.reset();
}
FNET_Transport *
Fdispatch::GetFNETTransport()
{
return _transport.get();
}
FNET_Scheduler *
Fdispatch::GetFNETScheduler()
{
return (_transport) ? _transport->GetScheduler() : nullptr;
}
FastS_NodeManager *
Fdispatch::GetNodeManager()
{
return _nodeManager.get();
}
FastS_DataSetCollection *
Fdispatch::GetDataSetCollection()
{
return ( _nodeManager) ? _nodeManager->GetDataSetCollection() : nullptr;
}
FastOS_ThreadPool *
Fdispatch::GetThreadPool()
{
return _mypool.get();
}
bool
Fdispatch::Failed()
{
return ( (_transportServer && _transportServer->isFailed())) || _needRestart;
}
bool
Fdispatch::CheckTempFail()
{
bool ret;
bool failflag = _nodeManager->GetTempFail();
unsigned int FNETLiveCounter;
ret = true;
FNETLiveCounter = _FNET_adapter.GetLiveCounter();
if (FNETLiveCounter == _lastFNETLiveCounter) {
if (_FNETLiveCounterFailed) {
failflag = true; // Still failure
} else if (!_FNETLiveCounterDanger) {
_FNETLiveCounterDanger = true;
_FNETLiveCounterDangerStart.SetNow();
} else if (_FNETLiveCounterDangerStart.MilliSecsToNow() >= 6000) {
LOG(error, "fdispatch::Fdispatch::CheckTempFail: FNET inactive for 6 seconds, deadlock ?");
_FNETLiveCounterFailed = true; // Note that we failed
failflag = true; // Force temporary failure
} else if (_FNETLiveCounterDangerStart.MilliSecsToNow() >= 3000 &&
!_FNETLiveCounterWarned) {
_FNETLiveCounterWarned = true;
LOG(warning, "fdispatch::Fdispatch::CheckTempFail: FNET inactive for 3 seconds");
}
} else {
if (_FNETLiveCounterFailed || _FNETLiveCounterWarned) {
LOG(warning, "fdispatch::Fdispatch::CheckTempFail: FNET active again");
}
_FNETLiveCounterFailed = false;
_FNETLiveCounterWarned = false;
_FNETLiveCounterDanger = false;
_lastFNETLiveCounter = FNETLiveCounter;
}
if (failflag == _tempFail)
return ret;
if (_transportServer) {
if (failflag) {
_transportServer->setListen(false);
LOG(error, "Disabling fnet server interface");
} else {
_transportServer->setListen(true);
LOG(info, "Reenabling fnet server interface");
}
}
_tempFail = failflag;
return ret;
}
/**
* Make the httpd and Monitor, and let a Thread execute each.
* Set up stuff as specified in the fdispatch-rc-file.
*/
Fdispatch::Fdispatch(const config::ConfigUri &configUri)
: _mypool(),
_engineAdapter(),
_transportServer(),
_componentConfig(),
_nodeManager(),
_transport(),
_FNET_adapter(this),
_rpc(),
_config(),
_configUri(configUri),
_fdispatchrcFetcher(configUri.getContext()),
_rndGen(),
_partition(0),
_tempFail(false),
_FNETLiveCounterDanger(false),
_FNETLiveCounterWarned(false),
_FNETLiveCounterFailed(false),
_transportStarted(false),
_lastFNETLiveCounter(false),
_FNETLiveCounterDangerStart(),
_timeouts(0u),
_checkLimit(0u),
_healthPort(0),
_needRestart(false)
{
int64_t cfgGen = -1;
_config = config::ConfigGetter<FdispatchrcConfig>::
getConfig(cfgGen, _configUri.getConfigId(), _configUri.getContext());
LOG(config, "fdispatch version %s (RPC-port: %d, transport at %d)",
FastS_VersionTag, _config->frtport, _config->ptport);
_componentConfig.addConfig(vespalib::ComponentConfigProducer::Config("fdispatch", cfgGen,
"config only obtained at startup"));
_fdispatchrcFetcher.subscribe<FdispatchrcConfig>(configUri.getConfigId(), this);
_fdispatchrcFetcher.start();
}
namespace {
bool needRestart(const FdispatchrcConfig & curr, const FdispatchrcConfig & next)
{
if (curr.frtport != next.frtport) {
LOG(warning, "FRT port has changed from %d to %d.", curr.frtport, next.frtport);
return true;
}
if (curr.ptport != next.ptport) {
LOG(warning, "PT port has changed from %d to %d.", curr.ptport, next.ptport);
return true;
}
if (curr.healthport != next.healthport) {
LOG(warning, "Health port has changed from %d to %d.", curr.healthport, next.healthport);
return true;
}
return false;
}
}
void Fdispatch::configure(std::unique_ptr<FdispatchrcConfig> cfg)
{
if (cfg && _config) {
if ( needRestart(*_config, *cfg) ) {
LOG(warning, "Will restart by abort now.");
_needRestart.store(true);
}
}
}
namespace {
CompressionConfig::Type
convert(InternalFdispatchrcType::Packetcompresstype type)
{
switch (type) {
case InternalFdispatchrcType::LZ4: return CompressionConfig::LZ4;
default: return CompressionConfig::LZ4;
}
}
}
bool
Fdispatch::Init()
{
int maxthreads;
_tempFail = false;
_FNETLiveCounterDanger = false;
_FNETLiveCounterWarned = false;
_FNETLiveCounterFailed = false;
_lastFNETLiveCounter = 0;
_timeouts = 0;
_checkLimit = 60;
FS4PersistentPacketStreamer::Instance.SetCompressionLimit(_config->packetcompresslimit);
FS4PersistentPacketStreamer::Instance.SetCompressionLevel(_config->packetcompresslevel);
FS4PersistentPacketStreamer::Instance.SetCompressionType(convert(_config->packetcompresstype));
LOG(debug, "Creating FNET transport");
_transport = std::make_unique<FNET_Transport>(_config->transportthreads);
// grab node slowness limit defaults
FastS_DataSetDesc::SetDefaultSlowQueryLimitFactor(_config->defaultslowquerylimitfactor);
FastS_DataSetDesc::SetDefaultSlowQueryLimitBias(_config->defaultslowquerylimitbias);
FastS_DataSetDesc::SetDefaultSlowDocsumLimitFactor(_config->defaultslowdocsumlimitfactor);
FastS_DataSetDesc::SetDefaultSlowDocsumLimitBias(_config->defaultslowdocsumlimitbias);
maxthreads = _config->maxthreads;
_mypool = std::make_unique<FastOS_ThreadPool>(256 * 1024, maxthreads);
// Max interval betw read from socket.
FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent] = _config->maxsocksilent;
if (_transport) {
_transport->SetIOCTimeOut((uint32_t) (FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent] * 1000.0));
}
char timestr[40];
FastS_TimeOut::WriteTime(timestr, sizeof(timestr), FastS_TimeOut::_val[FastS_TimeOut::maxSockSilent]);
LOG(debug, "VERBOSE: Max time between successful read from a socket: %s", timestr);
FastS_QueryCacheUtil::_systemMaxHits = std::numeric_limits<int>::max();
LOG(debug, "VERBOSE: maxhits: %d", FastS_QueryCacheUtil::_systemMaxHits);
FastS_QueryCacheUtil::_maxOffset = std::numeric_limits<int>::max();
const uint32_t linesize = 1;
if (FastS_QueryCacheUtil::_systemMaxHits < linesize
&& FastS_QueryCacheUtil::_maxOffset < linesize - FastS_QueryCacheUtil::_systemMaxHits) {
LOG(warning, "maxoffset must be >= %d! (overriding config value)", linesize - FastS_QueryCacheUtil::_systemMaxHits);
FastS_QueryCacheUtil::_maxOffset = linesize - FastS_QueryCacheUtil::_systemMaxHits;
}
LOG(debug, "VERBOSE: maxoffset: %d", FastS_QueryCacheUtil::_maxOffset);
_partition = _config->partition;
int ptportnum = _config->ptport;
LOG(debug, "Using port number %d", ptportnum);
_nodeManager = std::make_unique<FastS_NodeManager>(_componentConfig, this, _partition);
GetFNETTransport()->SetTCPNoDelay(_config->transportnodelay);
GetFNETTransport()->SetDirectWrite(_config->transportdirectwrite);
if (ptportnum == 0) {
throw vespalib::IllegalArgumentException("fdispatchrc.ptportnum must be non-zero, most likely an issue with config delivery.");
}
_engineAdapter = std::make_unique<fdispatch::EngineAdapter>(this, _mypool.get());
_transportServer = std::make_unique<TransportServer>(*_engineAdapter, *_engineAdapter, *_engineAdapter, ptportnum, search::engine::TransportServer::DEBUG_ALL);
_transportServer->setTCPNoDelay(_config->transportnodelay);
_transportServer->setDirectWrite(_config->transportdirectwrite);
if (!_transportServer->start()) {
_transportServer.reset();
_engineAdapter.reset();
LOG(error, "CRITICAL: Failed to init upwards FNET transport on port %d", ptportnum);
return false;
}
_nodeManager->SubscribePartMap(_configUri);
if (_config->frtport != 0) {
_rpc = std::make_unique<FastS_fdispatch_RPC>(this);
if (!_rpc->Init(_config->frtport, _configUri.getConfigId())) {
LOG(error, "RPC init failed");
_rpc.reset();
}
} else {
_rpc.reset();
}
// Kick off fdispatch administrative threads.
if (_transport) {
_FNET_adapter.init();
bool rc = _transport->Start(_mypool.get());
if (rc) {
LOG(debug, "Started FNET transport");
_transportStarted = true;
} else {
LOG(error, "Failed to start FNET transport");
}
}
FastOS_Thread::Sleep(1000);
if (_rpc) {
_rpc->Start();
}
_healthPort = _config->healthport;
return true;
}
void
Fdispatch::logPerformance()
{
_nodeManager->logPerformance();
}
uint32_t
Fdispatch::getDispatchLevel()
{
return _config->dispatchlevel;
}
}
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "partitioner.h"
#include "mesh_base.h"
#include "elem.h"
// ------------------------------------------------------------
// Partitioner implementation
void Partitioner::partition (MeshBase& mesh,
const unsigned int n)
{
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_partition(mesh,n);
// Set the node's processor ids
this->_set_node_processor_ids(mesh);
}
void Partitioner::repartition (MeshBase& mesh,
const unsigned int n)
{
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_repartition(mesh,n);
// Set the node's processor ids
this->_set_node_processor_ids(mesh);
}
void Partitioner::single_partition (MeshBase& mesh)
{
// Loop over all the elements and assign them to processor 0.
MeshBase::element_iterator elem_it = mesh.elements_begin();
const MeshBase::element_iterator elem_end = mesh.elements_end();
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->processor_id() = 0;
// For a single partition, all the nodes are on processor 0
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->processor_id() = 0;
}
void Partitioner::_set_node_processor_ids(MeshBase& mesh)
{
// Unset any previously-set node processor ids
// (maybe from previous partitionings).
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->invalidate_processor_id();
// Loop over all the elements
MeshBase::element_iterator elem_it = mesh.active_elements_begin();
const MeshBase::element_iterator elem_end = mesh.active_elements_end();
for ( ; elem_it != elem_end; ++elem_it)
{
Elem* elem = *elem_it;
// For each node, set the processor ID to the min of
// its current value and this Element's processor id.
for (unsigned int n=0; n<elem->n_nodes(); ++n)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
#ifdef DEBUG
// Make sure we hit all the nodes
for ( ; node_it != node_end; ++node_it)
assert((*node_it)->processor_id() != DofObject::invalid_id);
#endif
}
<commit_msg>Bugfix for partitioner sanity check<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "partitioner.h"
#include "mesh_base.h"
#include "elem.h"
// ------------------------------------------------------------
// Partitioner implementation
void Partitioner::partition (MeshBase& mesh,
const unsigned int n)
{
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_partition(mesh,n);
// Set the node's processor ids
this->_set_node_processor_ids(mesh);
}
void Partitioner::repartition (MeshBase& mesh,
const unsigned int n)
{
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_repartition(mesh,n);
// Set the node's processor ids
this->_set_node_processor_ids(mesh);
}
void Partitioner::single_partition (MeshBase& mesh)
{
// Loop over all the elements and assign them to processor 0.
MeshBase::element_iterator elem_it = mesh.elements_begin();
const MeshBase::element_iterator elem_end = mesh.elements_end();
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->processor_id() = 0;
// For a single partition, all the nodes are on processor 0
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->processor_id() = 0;
}
void Partitioner::_set_node_processor_ids(MeshBase& mesh)
{
// Unset any previously-set node processor ids
// (maybe from previous partitionings).
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->invalidate_processor_id();
// Loop over all the elements
MeshBase::element_iterator elem_it = mesh.active_elements_begin();
const MeshBase::element_iterator elem_end = mesh.active_elements_end();
for ( ; elem_it != elem_end; ++elem_it)
{
Elem* elem = *elem_it;
// For each node, set the processor ID to the min of
// its current value and this Element's processor id.
for (unsigned int n=0; n<elem->n_nodes(); ++n)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
#ifdef DEBUG
node_it = mesh.nodes_begin();
// Make sure we hit all the nodes
for ( ; node_it != node_end; ++node_it)
assert((*node_it)->processor_id() != DofObject::invalid_id);
#endif
}
<|endoftext|> |
<commit_before>#include "GLES2Mesh.h"
#include "GLES2Header.h"
#include "GLES2Util.h"
#include "GLES2Scene.h"
#include "platform/Log.h"
#include "GLES2Texture.h"
#include "math/Vector2.h"
#include "math/Angle.h"
#include "PrimitiveMode.h"
#include "Supernova.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
GLES2Mesh::GLES2Mesh(): MeshRender() {
lighting = false;
}
GLES2Mesh::~GLES2Mesh() {
destroy();
}
void GLES2Mesh::updateVertices(){
MeshRender::updateVertices();
if (loaded)
GLES2Util::updateVBO(vertexBuffer, GL_ARRAY_BUFFER, vertices->size() * 3 * sizeof(GLfloat), &vertices->front());
}
void GLES2Mesh::updateTexcoords(){
MeshRender::updateTexcoords();
if (loaded)
if (texcoords)
GLES2Util::updateVBO(uvBuffer, GL_ARRAY_BUFFER, texcoords->size() * 2 * sizeof(GLfloat), &texcoords->front());
}
void GLES2Mesh::updateNormals(){
MeshRender::updateNormals();
if (loaded)
if (lighting && normals)
GLES2Util::updateVBO(normalBuffer, GL_ARRAY_BUFFER, normals->size() * 3 * sizeof(GLfloat), &normals->front());
}
void GLES2Mesh::updateIndices(){
MeshRender::updateIndices();
if (loaded){
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
std::vector<unsigned int>* gIndices = submeshes->at(i)->getIndices();
GLES2Util::updateVBO(submeshesIndices[submeshes->at(i)].indiceBuffer, GL_ELEMENT_ARRAY_BUFFER, gIndices->size() * sizeof(unsigned int), &gIndices->front());
}
}
}
}
bool GLES2Mesh::load() {
if (!MeshRender::load()){
return false;
}
std::string programName = "mesh_perfragment";
std::string programDefs = "";
if (submeshes){
if (submeshes->at(0)->getMaterial()->getTextureType() == S_TEXTURE_CUBE){
programDefs += "#define USE_TEXTURECUBE\n";
}
}
if (isSky){
programDefs += "#define IS_SKY\n";
}
if (lighting){
programDefs += "#define USE_LIGHTING\n";
}
if (hasfog){
programDefs += "#define HAS_FOG\n";
}
if (texcoords){
programDefs += "#define USE_TEXTURECOORDS\n"; //TODO!
}
if (hasTextureRect){
programDefs += "#define HAS_TEXTURERECT\n";
}
gProgram = ProgramManager::useProgram(programName, programDefs);
light.setProgram((GLES2Program*)gProgram.get());
fog.setProgram((GLES2Program*)gProgram.get());
useTexture = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "uUseTexture");
GLenum usageBuffer = GL_STATIC_DRAW;
if (isDynamic){
usageBuffer = GL_DYNAMIC_DRAW;
}
vertexBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, vertices->size() * 3 * sizeof(GLfloat), &vertices->front(), usageBuffer);
aPositionHandle = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_Position");
uvBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, texcoords->size() * 2 * sizeof(GLfloat), &texcoords->front(), usageBuffer);
aTextureCoordinatesLocation = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_TextureCoordinates");
if (lighting){
normalBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, normals->size() * 3 * sizeof(GLfloat), &normals->front(), usageBuffer);
aNormal = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_Normal");
}
if (hasTextureRect){
u_textureRect = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_textureRect");
}
uTextureUnitLocation = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_TextureUnit");
uColor = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_Color");
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
std::vector<unsigned int>* gIndices = submeshes->at(i)->getIndices();
submeshesIndices[submeshes->at(i)].indiceBuffer = GLES2Util::createVBO(GL_ELEMENT_ARRAY_BUFFER, gIndices->size() * sizeof(unsigned int), &gIndices->front(), usageBuffer);
}
if (submeshesRender[submeshes->at(i)].textured){
if (submeshes->at(i)->getMaterial()->getTextureType() == S_TEXTURE_CUBE){
std::vector<std::string> textures;
std::string id = "cube|";
for (int t = 0; t < submeshes->at(i)->getMaterial()->getTextures().size(); t++){
textures.push_back(submeshes->at(i)->getMaterial()->getTextures()[t]);
id = id + "|" + textures.back();
}
submeshesRender[submeshes->at(i)].texture = TextureManager::loadTextureCube(textures, id);
}else{
submeshesRender[submeshes->at(i)].texture = TextureManager::loadTexture(submeshes->at(i)->getMaterial()->getTextures()[0]);
}
}else{
//Fix Chrome warnings of no texture bound with an empty texture
if (Supernova::getPlatform() == S_WEB){
GLES2Util::generateEmptyTexture();
}
submeshesRender[submeshes->at(i)].texture = NULL;
}
}
u_mvpMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_mvpMatrix");
if (lighting){
light.getUniformLocations();
uEyePos = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_EyePos");
u_mMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_mMatrix");
u_nMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_nMatrix");
}
if (hasfog){
fog.getUniformLocations();
}
GLES2Util::checkGlError("Error on load GLES2");
return true;
}
bool GLES2Mesh::draw() {
if (!MeshRender::draw()){
return false;
}
if (!loaded){
return false;
}
if (isSky) {
glDepthFunc(GL_LEQUAL);
}
glUseProgram(((GLES2Program*)gProgram.get())->getProgram());
GLES2Util::checkGlError("glUseProgram");
glUniformMatrix4fv(u_mvpMatrix, 1, GL_FALSE, (GLfloat*)modelViewProjectMatrix);
if (lighting){
light.setUniformValues(sceneRender);
glUniform3fv(uEyePos, 1, cameraPosition.ptr());
glUniformMatrix4fv(u_mMatrix, 1, GL_FALSE, (GLfloat*)modelMatrix);
glUniformMatrix4fv(u_nMatrix, 1, GL_FALSE, (GLfloat*)normalMatrix);
}
if (hasfog){
fog.setUniformValues(sceneRender);
}
int attributePos = -1;
attributePos++;
glEnableVertexAttribArray(attributePos);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
if (aPositionHandle == -1) aPositionHandle = attributePos;
glVertexAttribPointer(aPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
if (texcoords){
attributePos++;
glEnableVertexAttribArray(attributePos);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
if (aTextureCoordinatesLocation == -1) aTextureCoordinatesLocation = attributePos;
glVertexAttribPointer(aTextureCoordinatesLocation, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
}
if (lighting) {
attributePos++;
glEnableVertexAttribArray(attributePos);
if (normals) {
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
if (aNormal == -1) aNormal = attributePos;
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
}
}
GLenum modeGles = GL_TRIANGLES;
if (primitiveMode == S_TRIANGLES_STRIP){
modeGles = GL_TRIANGLE_STRIP;
}
if (primitiveMode == S_POINTS){
modeGles = GL_POINTS;
}
for (int i = 0; i < submeshes->size(); i++){
if (hasTextureRect){
TextureRect textureRect;
if (submeshes->at(i)->getMaterial()->getTextureRect())
textureRect = *submeshes->at(i)->getMaterial()->getTextureRect();
glUniform4f(u_textureRect, textureRect.getX(), textureRect.getY(), textureRect.getWidth(), textureRect.getHeight());
}
glUniform1i(useTexture, submeshesRender[submeshes->at(i)].textured);
if (submeshesRender[submeshes->at(i)].textured){
glActiveTexture(GL_TEXTURE0);
glBindTexture(((GLES2Texture*)(submeshesRender[submeshes->at(i)].texture.get()))->getTextureType(), ((GLES2Texture*)(submeshesRender[submeshes->at(i)].texture.get()))->getTexture());
glUniform1i(uTextureUnitLocation, 0);
}
glUniform4fv(uColor, 1, submeshes->at(i)->getMaterial()->getColor()->ptr());
if (Supernova::getPlatform() == S_WEB){
//Fix Chrome warnings of no texture bound
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, GLES2Util::emptyTexture);
glUniform1i(uTextureUnitLocation, 0);
}
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submeshesIndices[submeshes->at(i)].indiceBuffer);
glDrawElements(modeGles, submeshesRender[submeshes->at(i)].indicesSizes, GL_UNSIGNED_INT, BUFFER_OFFSET(0));
}else{
glDrawArrays(modeGles, 0, (int)vertices->size());
}
}
for (int i = 0; i <= attributePos; i++)
glDisableVertexAttribArray(i);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
GLES2Util::checkGlError("Error on draw GLES2");
return true;
}
void GLES2Mesh::destroy(){
if (loaded){
glDeleteBuffers(1, &vertexBuffer);
if (texcoords){
glDeleteBuffers(1, &uvBuffer);
}
if (lighting && normals){
glDeleteBuffers(1, &normalBuffer);
}
if (submeshes){
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0)
glDeleteBuffers(1, &submeshesIndices[submeshes->at(i)].indiceBuffer);
if (submeshesRender[submeshes->at(i)].textured){
submeshesRender[submeshes->at(i)].texture.reset();
TextureManager::deleteUnused();
}
}
}
gProgram.reset();
ProgramManager::deleteUnused();
}
loaded = false;
}
<commit_msg>Fixed WebGL bug with textures<commit_after>#include "GLES2Mesh.h"
#include "GLES2Header.h"
#include "GLES2Util.h"
#include "GLES2Scene.h"
#include "platform/Log.h"
#include "GLES2Texture.h"
#include "math/Vector2.h"
#include "math/Angle.h"
#include "PrimitiveMode.h"
#include "Supernova.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
GLES2Mesh::GLES2Mesh(): MeshRender() {
lighting = false;
}
GLES2Mesh::~GLES2Mesh() {
destroy();
}
void GLES2Mesh::updateVertices(){
MeshRender::updateVertices();
if (loaded)
GLES2Util::updateVBO(vertexBuffer, GL_ARRAY_BUFFER, vertices->size() * 3 * sizeof(GLfloat), &vertices->front());
}
void GLES2Mesh::updateTexcoords(){
MeshRender::updateTexcoords();
if (loaded)
if (texcoords)
GLES2Util::updateVBO(uvBuffer, GL_ARRAY_BUFFER, texcoords->size() * 2 * sizeof(GLfloat), &texcoords->front());
}
void GLES2Mesh::updateNormals(){
MeshRender::updateNormals();
if (loaded)
if (lighting && normals)
GLES2Util::updateVBO(normalBuffer, GL_ARRAY_BUFFER, normals->size() * 3 * sizeof(GLfloat), &normals->front());
}
void GLES2Mesh::updateIndices(){
MeshRender::updateIndices();
if (loaded){
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
std::vector<unsigned int>* gIndices = submeshes->at(i)->getIndices();
GLES2Util::updateVBO(submeshesIndices[submeshes->at(i)].indiceBuffer, GL_ELEMENT_ARRAY_BUFFER, gIndices->size() * sizeof(unsigned int), &gIndices->front());
}
}
}
}
bool GLES2Mesh::load() {
if (!MeshRender::load()){
return false;
}
std::string programName = "mesh_perfragment";
std::string programDefs = "";
if (submeshes){
if (submeshes->at(0)->getMaterial()->getTextureType() == S_TEXTURE_CUBE){
programDefs += "#define USE_TEXTURECUBE\n";
}
}
if (isSky){
programDefs += "#define IS_SKY\n";
}
if (lighting){
programDefs += "#define USE_LIGHTING\n";
}
if (hasfog){
programDefs += "#define HAS_FOG\n";
}
if (texcoords){
programDefs += "#define USE_TEXTURECOORDS\n"; //TODO!
}
if (hasTextureRect){
programDefs += "#define HAS_TEXTURERECT\n";
}
gProgram = ProgramManager::useProgram(programName, programDefs);
light.setProgram((GLES2Program*)gProgram.get());
fog.setProgram((GLES2Program*)gProgram.get());
useTexture = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "uUseTexture");
GLenum usageBuffer = GL_STATIC_DRAW;
if (isDynamic){
usageBuffer = GL_DYNAMIC_DRAW;
}
vertexBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, vertices->size() * 3 * sizeof(GLfloat), &vertices->front(), usageBuffer);
aPositionHandle = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_Position");
uvBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, texcoords->size() * 2 * sizeof(GLfloat), &texcoords->front(), usageBuffer);
aTextureCoordinatesLocation = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_TextureCoordinates");
if (lighting){
normalBuffer = GLES2Util::createVBO(GL_ARRAY_BUFFER, normals->size() * 3 * sizeof(GLfloat), &normals->front(), usageBuffer);
aNormal = glGetAttribLocation(((GLES2Program*)gProgram.get())->getProgram(), "a_Normal");
}
if (hasTextureRect){
u_textureRect = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_textureRect");
}
uTextureUnitLocation = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_TextureUnit");
uColor = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_Color");
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
std::vector<unsigned int>* gIndices = submeshes->at(i)->getIndices();
submeshesIndices[submeshes->at(i)].indiceBuffer = GLES2Util::createVBO(GL_ELEMENT_ARRAY_BUFFER, gIndices->size() * sizeof(unsigned int), &gIndices->front(), usageBuffer);
}
if (submeshesRender[submeshes->at(i)].textured){
if (submeshes->at(i)->getMaterial()->getTextureType() == S_TEXTURE_CUBE){
std::vector<std::string> textures;
std::string id = "cube|";
for (int t = 0; t < submeshes->at(i)->getMaterial()->getTextures().size(); t++){
textures.push_back(submeshes->at(i)->getMaterial()->getTextures()[t]);
id = id + "|" + textures.back();
}
submeshesRender[submeshes->at(i)].texture = TextureManager::loadTextureCube(textures, id);
}else{
submeshesRender[submeshes->at(i)].texture = TextureManager::loadTexture(submeshes->at(i)->getMaterial()->getTextures()[0]);
}
}else{
//Fix Chrome warnings of no texture bound with an empty texture
if (Supernova::getPlatform() == S_WEB){
GLES2Util::generateEmptyTexture();
}
submeshesRender[submeshes->at(i)].texture = NULL;
}
}
u_mvpMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_mvpMatrix");
if (lighting){
light.getUniformLocations();
uEyePos = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_EyePos");
u_mMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_mMatrix");
u_nMatrix = glGetUniformLocation(((GLES2Program*)gProgram.get())->getProgram(), "u_nMatrix");
}
if (hasfog){
fog.getUniformLocations();
}
GLES2Util::checkGlError("Error on load GLES2");
return true;
}
bool GLES2Mesh::draw() {
if (!MeshRender::draw()){
return false;
}
if (!loaded){
return false;
}
if (isSky) {
glDepthFunc(GL_LEQUAL);
}
glUseProgram(((GLES2Program*)gProgram.get())->getProgram());
GLES2Util::checkGlError("glUseProgram");
glUniformMatrix4fv(u_mvpMatrix, 1, GL_FALSE, (GLfloat*)modelViewProjectMatrix);
if (lighting){
light.setUniformValues(sceneRender);
glUniform3fv(uEyePos, 1, cameraPosition.ptr());
glUniformMatrix4fv(u_mMatrix, 1, GL_FALSE, (GLfloat*)modelMatrix);
glUniformMatrix4fv(u_nMatrix, 1, GL_FALSE, (GLfloat*)normalMatrix);
}
if (hasfog){
fog.setUniformValues(sceneRender);
}
int attributePos = -1;
attributePos++;
glEnableVertexAttribArray(attributePos);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
if (aPositionHandle == -1) aPositionHandle = attributePos;
glVertexAttribPointer(aPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
if (texcoords){
attributePos++;
glEnableVertexAttribArray(attributePos);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
if (aTextureCoordinatesLocation == -1) aTextureCoordinatesLocation = attributePos;
glVertexAttribPointer(aTextureCoordinatesLocation, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
}
if (lighting) {
attributePos++;
glEnableVertexAttribArray(attributePos);
if (normals) {
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
if (aNormal == -1) aNormal = attributePos;
glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
}
}
GLenum modeGles = GL_TRIANGLES;
if (primitiveMode == S_TRIANGLES_STRIP){
modeGles = GL_TRIANGLE_STRIP;
}
if (primitiveMode == S_POINTS){
modeGles = GL_POINTS;
}
for (int i = 0; i < submeshes->size(); i++){
if (hasTextureRect){
TextureRect textureRect;
if (submeshes->at(i)->getMaterial()->getTextureRect())
textureRect = *submeshes->at(i)->getMaterial()->getTextureRect();
glUniform4f(u_textureRect, textureRect.getX(), textureRect.getY(), textureRect.getWidth(), textureRect.getHeight());
}
glUniform1i(useTexture, submeshesRender[submeshes->at(i)].textured);
if (submeshesRender[submeshes->at(i)].textured){
glActiveTexture(GL_TEXTURE0);
glBindTexture(((GLES2Texture*)(submeshesRender[submeshes->at(i)].texture.get()))->getTextureType(), ((GLES2Texture*)(submeshesRender[submeshes->at(i)].texture.get()))->getTexture());
glUniform1i(uTextureUnitLocation, 0);
}else{
if (Supernova::getPlatform() == S_WEB){
//Fix Chrome warnings of no texture bound
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, GLES2Util::emptyTexture);
glUniform1i(uTextureUnitLocation, 0);
}
}
glUniform4fv(uColor, 1, submeshes->at(i)->getMaterial()->getColor()->ptr());
if (submeshesRender[submeshes->at(i)].indicesSizes > 0){
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, submeshesIndices[submeshes->at(i)].indiceBuffer);
glDrawElements(modeGles, submeshesRender[submeshes->at(i)].indicesSizes, GL_UNSIGNED_INT, BUFFER_OFFSET(0));
}else{
glDrawArrays(modeGles, 0, (int)vertices->size());
}
}
for (int i = 0; i <= attributePos; i++)
glDisableVertexAttribArray(i);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
GLES2Util::checkGlError("Error on draw GLES2");
return true;
}
void GLES2Mesh::destroy(){
if (loaded){
glDeleteBuffers(1, &vertexBuffer);
if (texcoords){
glDeleteBuffers(1, &uvBuffer);
}
if (lighting && normals){
glDeleteBuffers(1, &normalBuffer);
}
if (submeshes){
for (unsigned int i = 0; i < submeshes->size(); i++){
if (submeshesRender[submeshes->at(i)].indicesSizes > 0)
glDeleteBuffers(1, &submeshesIndices[submeshes->at(i)].indiceBuffer);
if (submeshesRender[submeshes->at(i)].textured){
submeshesRender[submeshes->at(i)].texture.reset();
TextureManager::deleteUnused();
}
}
}
gProgram.reset();
ProgramManager::deleteUnused();
}
loaded = false;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Thorben Kroeger <thorbenkroeger@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "themesettingsitemdelegate.h"
#include "colorvariable.h"
#include "themesettingstablemodel.h"
#include <utils/qtcassert.h>
#include <utils/theme/theme.h>
#include <QAbstractProxyModel>
#include <QComboBox>
#include <QEvent>
#include <QInputDialog>
#include <QMetaEnum>
using namespace Utils;
static QAbstractItemModel *sourceModel(QAbstractItemModel *model)
{
if (QAbstractProxyModel *m = qobject_cast<QAbstractProxyModel *>(model))
return m->sourceModel();
return model;
}
static const QAbstractItemModel *sourceModel(const QAbstractItemModel *model)
{
if (const QAbstractProxyModel *m = qobject_cast<const QAbstractProxyModel *>(model))
return m->sourceModel();
return model;
}
static QIcon makeIcon(const QColor &color)
{
QImage img(QSize(24,24), QImage::Format_ARGB32);
img.fill(color.rgba());
QIcon ico = QIcon(QPixmap::fromImage(img));
return ico;
}
namespace Core {
namespace Internal {
namespace ThemeEditor {
ThemeSettingsItemDelegate::ThemeSettingsItemDelegate(QObject *parent)
: QStyledItemDelegate(parent),
m_comboBox(0)
{
}
QWidget *ThemeSettingsItemDelegate::createColorEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const ThemeSettingsTableModel *model = qobject_cast<const ThemeSettingsTableModel*>(sourceModel(index.model()));
Q_UNUSED(option);
const int row = model->modelToSectionRow(index.row());
QComboBox *cb = new QComboBox(parent);
ColorRole::Ptr colorRole = model->m_colors->colorRole(row);
const bool isUnnamed = colorRole->colorVariable()->variableName().isEmpty();
const QColor currentColor = colorRole->colorVariable()->color();
cb->addItem(makeIcon(currentColor),
isUnnamed ? tr("<Unnamed> (Current)")
: colorRole->colorVariable()->variableName() + tr(" (Current)"));
int k = 1;
foreach (ColorVariable::Ptr namedColor, model->m_colors->colorVariables()) {
if (namedColor->variableName().isEmpty())
continue;
if (colorRole->colorVariable() == namedColor) {
continue;
} else {
cb->addItem(makeIcon(namedColor->color()), namedColor->variableName());
m_actions[k++] = qMakePair(Action_ChooseNamedColor, namedColor);
}
}
if (!isUnnamed) {
cb->addItem(tr("Remove Variable Name"));
m_actions[k++] = qMakePair(Action_MakeUnnamed, QSharedPointer<ColorVariable>(0));
}
cb->addItem(tr("Add Variable Name..."));
m_actions[k++] = qMakePair(Action_CreateNew, QSharedPointer<ColorVariable>(0));
connect(cb, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
this, [this, cb]() {
ThemeSettingsItemDelegate *me = const_cast<ThemeSettingsItemDelegate *>(this);
emit me->commitData(cb);
emit me->closeEditor(cb);
});
m_comboBox = cb;
return cb;
}
QWidget *ThemeSettingsItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const ThemeSettingsTableModel *model = qobject_cast<const ThemeSettingsTableModel*>(sourceModel(index.model()));
const int section = model->inSectionBody(index.row());
QTC_ASSERT(section >= 0, return 0);
switch (section) {
case ThemeSettingsTableModel::SectionWidgetStyle: {
QComboBox *cb = new QComboBox(parent);
QMetaEnum e = Theme::staticMetaObject.enumerator(Theme::staticMetaObject.indexOfEnumerator("WidgetStyle"));
for (int i = 0, total = e.keyCount(); i < total; ++i)
cb->addItem(QLatin1String(e.key(i)));
connect(cb, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
this, [this, cb]() {
ThemeSettingsItemDelegate *me = const_cast<ThemeSettingsItemDelegate *>(this);
emit me->commitData(cb);
emit me->closeEditor(cb);
});
m_comboBox = cb;
return cb;
}
case ThemeSettingsTableModel::SectionColors:
return createColorEditor(parent, option, index);
case ThemeSettingsTableModel::SectionFlags:
return QStyledItemDelegate::createEditor(parent, option, index);
default:
qWarning("unhandled section");
return 0;
} // switch
}
void ThemeSettingsItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QStyledItemDelegate::setEditorData(editor, index);
}
void ThemeSettingsItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
ThemeSettingsTableModel *themeSettingsModel = qobject_cast<ThemeSettingsTableModel *>(sourceModel(model));
const int row = themeSettingsModel->modelToSectionRow(index.row());
const int section = themeSettingsModel->inSectionBody(index.row());
switch (section) {
case ThemeSettingsTableModel::SectionWidgetStyle:
if (QComboBox *cb = qobject_cast<QComboBox *>(editor))
themeSettingsModel->m_widgetStyle = static_cast<Theme::WidgetStyle>(cb->currentIndex());
return;
case ThemeSettingsTableModel::SectionColors: {
if (QComboBox *cb = qobject_cast<QComboBox *>(editor)) {
ColorRole::Ptr themeColor = themeSettingsModel->m_colors->colorRole(row);
Action act = m_actions[cb->currentIndex()].first;
ColorVariable::Ptr previousVariable = themeColor->colorVariable();
ColorVariable::Ptr newVariable = m_actions[cb->currentIndex()].second;
if (act == Action_NoAction) {
return;
} else if (act == Action_ChooseNamedColor) {
previousVariable->removeReference(themeColor.data());
QTC_ASSERT(newVariable, return);
themeColor->assignColorVariable(newVariable);
} else if (act == Action_MakeUnnamed) {
previousVariable->removeReference(themeColor.data());
if (previousVariable->references().size() == 0)
themeSettingsModel->m_colors->removeVariable(previousVariable);
ColorVariable::Ptr anonymousColor = themeSettingsModel->m_colors->createVariable(previousVariable->color());
themeColor->assignColorVariable(anonymousColor);
} else if (act == Action_CreateNew) {
QString name = QInputDialog::getText(editor, tr("Add Variable Name"), tr("Variable name:"));
if (!name.isEmpty()) {
previousVariable->removeReference(themeColor.data());
// TODO: check for name collision
ColorVariable::Ptr newVariable = themeSettingsModel->m_colors->createVariable(previousVariable->color(), name);
themeColor->assignColorVariable(newVariable);
}
}
}
return;
}
default:
return QStyledItemDelegate::setModelData(editor, model, index);
}
}
void ThemeSettingsItemDelegate::popupMenu()
{
m_comboBox->showPopup();
}
} // namespace ThemeEditor
} // namespace Internal
} // namespace Core
<commit_msg>ThemeEditor: Preselect widget style on edit<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Thorben Kroeger <thorbenkroeger@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "themesettingsitemdelegate.h"
#include "colorvariable.h"
#include "themesettingstablemodel.h"
#include <utils/qtcassert.h>
#include <utils/theme/theme.h>
#include <QAbstractProxyModel>
#include <QComboBox>
#include <QEvent>
#include <QInputDialog>
#include <QMetaEnum>
using namespace Utils;
static QAbstractItemModel *sourceModel(QAbstractItemModel *model)
{
if (QAbstractProxyModel *m = qobject_cast<QAbstractProxyModel *>(model))
return m->sourceModel();
return model;
}
static const QAbstractItemModel *sourceModel(const QAbstractItemModel *model)
{
if (const QAbstractProxyModel *m = qobject_cast<const QAbstractProxyModel *>(model))
return m->sourceModel();
return model;
}
static QIcon makeIcon(const QColor &color)
{
QImage img(QSize(24,24), QImage::Format_ARGB32);
img.fill(color.rgba());
QIcon ico = QIcon(QPixmap::fromImage(img));
return ico;
}
namespace Core {
namespace Internal {
namespace ThemeEditor {
ThemeSettingsItemDelegate::ThemeSettingsItemDelegate(QObject *parent)
: QStyledItemDelegate(parent),
m_comboBox(0)
{
}
QWidget *ThemeSettingsItemDelegate::createColorEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const ThemeSettingsTableModel *model = qobject_cast<const ThemeSettingsTableModel*>(sourceModel(index.model()));
Q_UNUSED(option);
const int row = model->modelToSectionRow(index.row());
QComboBox *cb = new QComboBox(parent);
ColorRole::Ptr colorRole = model->m_colors->colorRole(row);
const bool isUnnamed = colorRole->colorVariable()->variableName().isEmpty();
const QColor currentColor = colorRole->colorVariable()->color();
cb->addItem(makeIcon(currentColor),
isUnnamed ? tr("<Unnamed> (Current)")
: colorRole->colorVariable()->variableName() + tr(" (Current)"));
int k = 1;
foreach (ColorVariable::Ptr namedColor, model->m_colors->colorVariables()) {
if (namedColor->variableName().isEmpty())
continue;
if (colorRole->colorVariable() == namedColor) {
continue;
} else {
cb->addItem(makeIcon(namedColor->color()), namedColor->variableName());
m_actions[k++] = qMakePair(Action_ChooseNamedColor, namedColor);
}
}
if (!isUnnamed) {
cb->addItem(tr("Remove Variable Name"));
m_actions[k++] = qMakePair(Action_MakeUnnamed, QSharedPointer<ColorVariable>(0));
}
cb->addItem(tr("Add Variable Name..."));
m_actions[k++] = qMakePair(Action_CreateNew, QSharedPointer<ColorVariable>(0));
connect(cb, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
this, [this, cb]() {
ThemeSettingsItemDelegate *me = const_cast<ThemeSettingsItemDelegate *>(this);
emit me->commitData(cb);
emit me->closeEditor(cb);
});
m_comboBox = cb;
return cb;
}
QWidget *ThemeSettingsItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const ThemeSettingsTableModel *model = qobject_cast<const ThemeSettingsTableModel*>(sourceModel(index.model()));
const int section = model->inSectionBody(index.row());
QTC_ASSERT(section >= 0, return 0);
switch (section) {
case ThemeSettingsTableModel::SectionWidgetStyle: {
QComboBox *cb = new QComboBox(parent);
QMetaEnum e = Theme::staticMetaObject.enumerator(Theme::staticMetaObject.indexOfEnumerator("WidgetStyle"));
for (int i = 0, total = e.keyCount(); i < total; ++i)
cb->addItem(QLatin1String(e.key(i)));
cb->setCurrentIndex(model->m_widgetStyle);
connect(cb, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
this, [this, cb]() {
ThemeSettingsItemDelegate *me = const_cast<ThemeSettingsItemDelegate *>(this);
emit me->commitData(cb);
emit me->closeEditor(cb);
});
m_comboBox = cb;
return cb;
}
case ThemeSettingsTableModel::SectionColors:
return createColorEditor(parent, option, index);
case ThemeSettingsTableModel::SectionFlags:
return QStyledItemDelegate::createEditor(parent, option, index);
default:
qWarning("unhandled section");
return 0;
} // switch
}
void ThemeSettingsItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QStyledItemDelegate::setEditorData(editor, index);
}
void ThemeSettingsItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
ThemeSettingsTableModel *themeSettingsModel = qobject_cast<ThemeSettingsTableModel *>(sourceModel(model));
const int row = themeSettingsModel->modelToSectionRow(index.row());
const int section = themeSettingsModel->inSectionBody(index.row());
switch (section) {
case ThemeSettingsTableModel::SectionWidgetStyle:
if (QComboBox *cb = qobject_cast<QComboBox *>(editor))
themeSettingsModel->m_widgetStyle = static_cast<Theme::WidgetStyle>(cb->currentIndex());
return;
case ThemeSettingsTableModel::SectionColors: {
if (QComboBox *cb = qobject_cast<QComboBox *>(editor)) {
ColorRole::Ptr themeColor = themeSettingsModel->m_colors->colorRole(row);
Action act = m_actions[cb->currentIndex()].first;
ColorVariable::Ptr previousVariable = themeColor->colorVariable();
ColorVariable::Ptr newVariable = m_actions[cb->currentIndex()].second;
if (act == Action_NoAction) {
return;
} else if (act == Action_ChooseNamedColor) {
previousVariable->removeReference(themeColor.data());
QTC_ASSERT(newVariable, return);
themeColor->assignColorVariable(newVariable);
} else if (act == Action_MakeUnnamed) {
previousVariable->removeReference(themeColor.data());
if (previousVariable->references().size() == 0)
themeSettingsModel->m_colors->removeVariable(previousVariable);
ColorVariable::Ptr anonymousColor = themeSettingsModel->m_colors->createVariable(previousVariable->color());
themeColor->assignColorVariable(anonymousColor);
} else if (act == Action_CreateNew) {
QString name = QInputDialog::getText(editor, tr("Add Variable Name"), tr("Variable name:"));
if (!name.isEmpty()) {
previousVariable->removeReference(themeColor.data());
// TODO: check for name collision
ColorVariable::Ptr newVariable = themeSettingsModel->m_colors->createVariable(previousVariable->color(), name);
themeColor->assignColorVariable(newVariable);
}
}
}
return;
}
default:
return QStyledItemDelegate::setModelData(editor, model, index);
}
}
void ThemeSettingsItemDelegate::popupMenu()
{
m_comboBox->showPopup();
}
} // namespace ThemeEditor
} // namespace Internal
} // namespace Core
<|endoftext|> |
<commit_before>#include "scrapers/GamesDBScraper.h"
#include "Log.h"
#include "pugixml/src/pugixml.hpp"
#include "MetaData.h"
#include "Settings.h"
#include "Util.h"
#include <boost/assign.hpp>
using namespace PlatformIds;
const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of
(THREEDO, "3DO")
(AMIGA, "Amiga")
(AMSTRAD_CPC, "Amstrad CPC")
// missing apple2
(ARCADE, "Arcade")
// missing atari 800
(ATARI_2600, "Atari 2600")
(ATARI_5200, "Atari 5200")
(ATARI_7800, "Atari 7800")
(ATARI_JAGUAR, "Atari Jaguar")
(ATARI_JAGUAR_CD, "Atari Jaguar CD")
(ATARI_LYNX, "Atari Lynx")
// missing atari ST/STE/Falcon
(ATARI_XE, "Atari XE")
(COLECOVISION, "Colecovision")
(COMMODORE_64, "Commodore 64")
(INTELLIVISION, "Intellivision")
(MAC_OS, "Mac OS")
(XBOX, "Microsoft Xbox")
(XBOX_360, "Microsoft Xbox 360")
// missing MSX
(NEOGEO, "Neo Geo")
(NEOGEO_POCKET, "Neo Geo Pocket")
(NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color")
(NINTENDO_3DS, "Nintendo 3DS")
(NINTENDO_64, "Nintendo 64")
(NINTENDO_DS, "Nintendo DS")
(NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)")
(GAME_BOY, "Nintendo Game Boy")
(GAME_BOY_ADVANCE, "Nintendo Game Boy Advance")
(GAME_BOY_COLOR, "Nintendo Game Boy Color")
(NINTENDO_GAMECUBE, "Nintendo GameCube")
(NINTENDO_WII, "Nintendo Wii")
(NINTENDO_WII_U, "Nintendo Wii U")
(PC, "PC")
(SEGA_32X, "Sega 32X")
(SEGA_CD, "Sega CD")
(SEGA_DREAMCAST, "Sega Dreamcast")
(SEGA_GAME_GEAR, "Sega Game Gear")
(SEGA_GENESIS, "Sega Genesis")
(SEGA_MASTER_SYSTEM, "Sega Master System")
(SEGA_MEGA_DRIVE, "Sega Mega Drive")
(SEGA_SATURN, "Sega Saturn")
(PLAYSTATION, "Sony Playstation")
(PLAYSTATION_2, "Sony Playstation 2")
(PLAYSTATION_3, "Sony Playstation 3")
(PLAYSTATION_4, "Sony Playstation 4")
(PLAYSTATION_VITA, "Sony Playstation Vita")
(PLAYSTATION_PORTABLE, "Sony PSP")
(SUPER_NINTENDO, "Super Nintendo (SNES)")
(TURBOGRAFX_16, "TurboGrafx 16")
(WONDERSWAN, "WonderSwan")
(WONDERSWAN_COLOR, "WonderSwan Color")
(ZX_SPECTRUM, "Sinclair ZX Spectrum");
void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests,
std::vector<ScraperSearchResult>& results)
{
std::string path = "thegamesdb.net/api/GetGame.php?";
std::string cleanName = params.nameOverride;
if(cleanName.empty())
cleanName = params.game->getCleanName();
path += "name=" + HttpReq::urlEncode(cleanName);
if(params.system->getPlatformIds().empty())
{
// no platform specified, we're done
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}else{
// go through the list, we need to split this into multiple requests
// because TheGamesDB API either sucks or I don't know how to use it properly...
std::string urlBase = path;
auto& platforms = params.system->getPlatformIds();
for(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)
{
path = urlBase;
auto mapIt = gamesdb_platformid_map.find(*platformIt);
if(mapIt != gamesdb_platformid_map.end())
{
path += "&platform=";
path += HttpReq::urlEncode(mapIt->second);
}else{
LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(*platformIt);
}
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}
}
}
void TheGamesDBRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)
{
assert(req->status() == HttpReq::REQ_SUCCESS);
pugi::xml_document doc;
pugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());
if(!parseResult)
{
std::stringstream ss;
ss << "GamesDBRequest - Error parsing XML. \n\t" << parseResult.description() << "";
std::string err = ss.str();
setError(err);
LOG(LogError) << err;
return;
}
pugi::xml_node data = doc.child("Data");
std::string baseImageUrl = data.child("baseImgUrl").text().get();
pugi::xml_node game = data.child("Game");
while(game && results.size() < MAX_SCRAPER_RESULTS)
{
ScraperSearchResult result;
result.mdl.set("name", game.child("GameTitle").text().get());
result.mdl.set("desc", game.child("Overview").text().get());
boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y");
result.mdl.setTime("releasedate", rd);
result.mdl.set("developer", game.child("Developer").text().get());
result.mdl.set("publisher", game.child("Publisher").text().get());
result.mdl.set("genre", game.child("Genres").first_child().text().get());
result.mdl.set("players", game.child("Players").text().get());
if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating"))
{
float ratingVal = (game.child("Rating").text().as_int() / 10.0f);
std::stringstream ss;
ss << ratingVal;
result.mdl.set("rating", ss.str());
}
pugi::xml_node images = game.child("Images");
if(images)
{
pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front");
if(art)
{
result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string();
result.imageUrl = baseImageUrl + art.text().get();
}
}
results.push_back(result);
game = game.next_sibling("Game");
}
}
<commit_msg>#69: Fixing user input from scraper. It now does an exact name search (#123)<commit_after>#include "scrapers/GamesDBScraper.h"
#include "Log.h"
#include "pugixml/src/pugixml.hpp"
#include "MetaData.h"
#include "Settings.h"
#include "Util.h"
#include <boost/assign.hpp>
using namespace PlatformIds;
const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of
(THREEDO, "3DO")
(AMIGA, "Amiga")
(AMSTRAD_CPC, "Amstrad CPC")
// missing apple2
(ARCADE, "Arcade")
// missing atari 800
(ATARI_2600, "Atari 2600")
(ATARI_5200, "Atari 5200")
(ATARI_7800, "Atari 7800")
(ATARI_JAGUAR, "Atari Jaguar")
(ATARI_JAGUAR_CD, "Atari Jaguar CD")
(ATARI_LYNX, "Atari Lynx")
// missing atari ST/STE/Falcon
(ATARI_XE, "Atari XE")
(COLECOVISION, "Colecovision")
(COMMODORE_64, "Commodore 64")
(INTELLIVISION, "Intellivision")
(MAC_OS, "Mac OS")
(XBOX, "Microsoft Xbox")
(XBOX_360, "Microsoft Xbox 360")
// missing MSX
(NEOGEO, "Neo Geo")
(NEOGEO_POCKET, "Neo Geo Pocket")
(NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color")
(NINTENDO_3DS, "Nintendo 3DS")
(NINTENDO_64, "Nintendo 64")
(NINTENDO_DS, "Nintendo DS")
(NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)")
(GAME_BOY, "Nintendo Game Boy")
(GAME_BOY_ADVANCE, "Nintendo Game Boy Advance")
(GAME_BOY_COLOR, "Nintendo Game Boy Color")
(NINTENDO_GAMECUBE, "Nintendo GameCube")
(NINTENDO_WII, "Nintendo Wii")
(NINTENDO_WII_U, "Nintendo Wii U")
(PC, "PC")
(SEGA_32X, "Sega 32X")
(SEGA_CD, "Sega CD")
(SEGA_DREAMCAST, "Sega Dreamcast")
(SEGA_GAME_GEAR, "Sega Game Gear")
(SEGA_GENESIS, "Sega Genesis")
(SEGA_MASTER_SYSTEM, "Sega Master System")
(SEGA_MEGA_DRIVE, "Sega Mega Drive")
(SEGA_SATURN, "Sega Saturn")
(PLAYSTATION, "Sony Playstation")
(PLAYSTATION_2, "Sony Playstation 2")
(PLAYSTATION_3, "Sony Playstation 3")
(PLAYSTATION_4, "Sony Playstation 4")
(PLAYSTATION_VITA, "Sony Playstation Vita")
(PLAYSTATION_PORTABLE, "Sony PSP")
(SUPER_NINTENDO, "Super Nintendo (SNES)")
(TURBOGRAFX_16, "TurboGrafx 16")
(WONDERSWAN, "WonderSwan")
(WONDERSWAN_COLOR, "WonderSwan Color")
(ZX_SPECTRUM, "Sinclair ZX Spectrum");
void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests,
std::vector<ScraperSearchResult>& results)
{
std::string path = "thegamesdb.net/api/GetGame.php?";
std::string cleanName = params.nameOverride;
if (cleanName.empty())
{
cleanName = params.game->getCleanName();
path += "name=" + HttpReq::urlEncode(cleanName);
}
else
{
path += "exactname=" + HttpReq::urlEncode(cleanName);
}
if(params.system->getPlatformIds().empty())
{
// no platform specified, we're done
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}else{
// go through the list, we need to split this into multiple requests
// because TheGamesDB API either sucks or I don't know how to use it properly...
std::string urlBase = path;
auto& platforms = params.system->getPlatformIds();
for(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)
{
path = urlBase;
auto mapIt = gamesdb_platformid_map.find(*platformIt);
if(mapIt != gamesdb_platformid_map.end())
{
path += "&platform=";
path += HttpReq::urlEncode(mapIt->second);
}else{
LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(*platformIt);
}
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}
}
}
void TheGamesDBRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)
{
assert(req->status() == HttpReq::REQ_SUCCESS);
pugi::xml_document doc;
pugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());
if(!parseResult)
{
std::stringstream ss;
ss << "GamesDBRequest - Error parsing XML. \n\t" << parseResult.description() << "";
std::string err = ss.str();
setError(err);
LOG(LogError) << err;
return;
}
pugi::xml_node data = doc.child("Data");
std::string baseImageUrl = data.child("baseImgUrl").text().get();
pugi::xml_node game = data.child("Game");
while(game && results.size() < MAX_SCRAPER_RESULTS)
{
ScraperSearchResult result;
result.mdl.set("name", game.child("GameTitle").text().get());
result.mdl.set("desc", game.child("Overview").text().get());
boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y");
result.mdl.setTime("releasedate", rd);
result.mdl.set("developer", game.child("Developer").text().get());
result.mdl.set("publisher", game.child("Publisher").text().get());
result.mdl.set("genre", game.child("Genres").first_child().text().get());
result.mdl.set("players", game.child("Players").text().get());
if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating"))
{
float ratingVal = (game.child("Rating").text().as_int() / 10.0f);
std::stringstream ss;
ss << ratingVal;
result.mdl.set("rating", ss.str());
}
pugi::xml_node images = game.child("Images");
if(images)
{
pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front");
if(art)
{
result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string();
result.imageUrl = baseImageUrl + art.text().get();
}
}
results.push_back(result);
game = game.next_sibling("Game");
}
}
<|endoftext|> |
<commit_before>#include <gl/pogl.h>
#include <thread>
#include <atomic>
#include <vector>
#include <cmath>
#include "POGLExampleWindow.h"
static const POGL_CHAR SIMPLE_EFFECT_VS[] = { R"(
#version 330
layout(location = 0) in vec3 position;
layout(location = 2) in float value;
out float vs_Value;
void main()
{
vs_Value = value;
gl_Position = vec4(position, 1.0);
}
)"};
static const POGL_CHAR SIMPLE_EFFECT_FS[] = { R"(
#version 330
in float vs_Value;
layout(location = 0) out vec4 color;
void main()
{
color = vec4(vs_Value, vs_Value, vs_Value, 1);
}
)" };
//
// Custom vertex structure
//
// Each custom vertex structure must have a matching POGL_VERTEX_LAYOUT object
//
struct CustomVertex
{
POGL_VECTOR3F position;
POGL_FLOAT value;
CustomVertex() {}
CustomVertex(const POGL_VECTOR3F& p, POGL_FLOAT v) { position = p; value = v; }
CustomVertex(const CustomVertex& v) { position = v.position; value = v.value; }
~CustomVertex() {}
inline CustomVertex& operator=(const CustomVertex& rhs) { position = rhs.position; value = rhs.value; return *this; }
};
//
// Layout object describing the data inside the CustomVertex.
//
static const POGL_VERTEX_LAYOUT CustomVertexLayout = {
//
// Vertex attribute locations.
//
// The index of POGL_VERTEX_LAYOUT_FIELD fields array will become the attribute location
//
{
//
// Attribute location = 0
//
// First value tells us how large the attribute is
// The second value tells us what type of data is contained in the attribute (float, int, etc.)
// The third value indicates if we want OpenGL to normalize the value on input
{ sizeof(POGL_VECTOR3F), POGLVertexType::FLOAT, false },
//
// Do not use attribute location = 1
//
// You are free to put the attributes in any location that you want. Some drivers, however, might optimize access to
// the vertex data if they are.
//
{ 0 },
//
// Attribute location = 2
//
{ sizeof(POGL_FLOAT), POGLVertexType::FLOAT, false },
//
// No more attributes
//
0
},
//
// The offset between each vertex. This is almost always the size of the vertex
//
sizeof(CustomVertex)
};
static const POGL_UINT32 CIRCLE_PTS = 365;
int main()
{
// Create a window
POGL_HANDLE windowHandle = POGLCreateExampleWindow(POGL_SIZEI(1024, 768), POGL_TOSTRING("Example 6: Custom Vertex Type"));
// Create a POGL device based on the supplied information
POGL_DEVICE_INFO deviceInfo = { 0 };
#ifdef _DEBUG
deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE;
#else
deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE;
#endif
deviceInfo.windowHandle = windowHandle;
deviceInfo.colorBits = 32;
deviceInfo.depthBits = 16;
deviceInfo.pixelFormat = POGLPixelFormat::R8G8B8A8;
IPOGLDevice* device = POGLCreateDevice(&deviceInfo);
try {
IPOGLDeviceContext* context = device->GetDeviceContext();
IPOGLShaderProgram* vertexShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_VS, sizeof(SIMPLE_EFFECT_VS), POGLShaderProgramType::VERTEX_SHADER);
IPOGLShaderProgram* fragmentShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_FS, sizeof(SIMPLE_EFFECT_FS), POGLShaderProgramType::FRAGMENT_SHADER);
IPOGLShaderProgram* programs[] = { vertexShader, fragmentShader };
IPOGLEffect* simpleEffect = context->CreateEffectFromPrograms(programs, 2);
vertexShader->Release();
fragmentShader->Release();
//
// Create data for a triangle.
//
const CustomVertex VERTICES[] = {
CustomVertex(POGL_VECTOR3F(-0.5f, -0.5f, 0.0f), 1.0f),
CustomVertex(POGL_VECTOR3F(0.0f, 0.5f, 0.0f), 0.0f),
CustomVertex(POGL_VECTOR3F(0.5f, -0.5f, 0.0f), 1.0f)
};
//
// Create a vertex buffer resource based using the custom vertex structure
//
IPOGLVertexBuffer* vertexBuffer = context->CreateVertexBuffer(VERTICES, sizeof(VERTICES), &CustomVertexLayout, POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC);
while (POGLProcessEvents()) {
IPOGLRenderState* state = context->Apply(simpleEffect);
state->Clear(POGLClearType::COLOR | POGLClearType::DEPTH);
//
// Draw the vertex buffer in the same way as normal
//
state->Draw(vertexBuffer);
state->EndFrame();
device->SwapBuffers();
}
//
// Release the vertex resources in the same way as normal
//
vertexBuffer->Release();
simpleEffect->Release();
context->Release();
}
catch (POGLException e) {
POGLAlert(e);
}
device->Release();
POGLDestroyExampleWindow(windowHandle);
return 0;
}
<commit_msg>Updated comments<commit_after>#include <gl/pogl.h>
#include <thread>
#include <atomic>
#include <vector>
#include <cmath>
#include "POGLExampleWindow.h"
static const POGL_CHAR SIMPLE_EFFECT_VS[] = { R"(
#version 330
layout(location = 0) in vec3 position;
layout(location = 2) in float value;
out float vs_Value;
void main()
{
vs_Value = value;
gl_Position = vec4(position, 1.0);
}
)"};
static const POGL_CHAR SIMPLE_EFFECT_FS[] = { R"(
#version 330
in float vs_Value;
layout(location = 0) out vec4 color;
void main()
{
color = vec4(vs_Value, vs_Value, vs_Value, 1);
}
)" };
//
// Custom vertex structure
//
// Each custom vertex structure must have a matching POGL_VERTEX_LAYOUT object
//
struct CustomVertex
{
POGL_VECTOR3F position;
POGL_FLOAT value;
CustomVertex() {}
CustomVertex(const POGL_VECTOR3F& p, POGL_FLOAT v) { position = p; value = v; }
CustomVertex(const CustomVertex& v) { position = v.position; value = v.value; }
~CustomVertex() {}
inline CustomVertex& operator=(const CustomVertex& rhs) { position = rhs.position; value = rhs.value; return *this; }
};
//
// Layout object describing the data inside the CustomVertex.
//
static const POGL_VERTEX_LAYOUT CustomVertexLayout = {
//
// Vertex attribute locations.
//
// The index of POGL_VERTEX_LAYOUT_FIELD fields array will become the attribute location
//
{
//
// Attribute location = 0
//
// First value tells us how large the attribute is. This is almost always the size of the attribute.
//
// The second value tells us what type of data is contained in the attribute (floats, integers etc.)
//
// The third value indicates if we want OpenGL to normalize the value on input. This is almost always "false".
//
{ sizeof(POGL_VECTOR3F), POGLVertexType::FLOAT, false },
//
// Do not use attribute location = 1
//
// You are free to put the attributes in any location that you want.
//
{ 0 },
//
// Attribute location = 2
//
{ sizeof(POGL_FLOAT), POGLVertexType::FLOAT, false },
//
// No more attributes
//
0
},
//
// The offset between each vertex. This is almost always the size of the vertex
//
sizeof(CustomVertex)
};
static const POGL_UINT32 CIRCLE_PTS = 365;
int main()
{
// Create a window
POGL_HANDLE windowHandle = POGLCreateExampleWindow(POGL_SIZEI(1024, 768), POGL_TOSTRING("Example 6: Custom Vertex Type"));
// Create a POGL device based on the supplied information
POGL_DEVICE_INFO deviceInfo = { 0 };
#ifdef _DEBUG
deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE;
#else
deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE;
#endif
deviceInfo.windowHandle = windowHandle;
deviceInfo.colorBits = 32;
deviceInfo.depthBits = 16;
deviceInfo.pixelFormat = POGLPixelFormat::R8G8B8A8;
IPOGLDevice* device = POGLCreateDevice(&deviceInfo);
try {
IPOGLDeviceContext* context = device->GetDeviceContext();
IPOGLShaderProgram* vertexShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_VS, sizeof(SIMPLE_EFFECT_VS), POGLShaderProgramType::VERTEX_SHADER);
IPOGLShaderProgram* fragmentShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_FS, sizeof(SIMPLE_EFFECT_FS), POGLShaderProgramType::FRAGMENT_SHADER);
IPOGLShaderProgram* programs[] = { vertexShader, fragmentShader };
IPOGLEffect* simpleEffect = context->CreateEffectFromPrograms(programs, 2);
vertexShader->Release();
fragmentShader->Release();
//
// Create data for a triangle.
//
const CustomVertex VERTICES[] = {
CustomVertex(POGL_VECTOR3F(-0.5f, -0.5f, 0.0f), 1.0f),
CustomVertex(POGL_VECTOR3F(0.0f, 0.5f, 0.0f), 0.0f),
CustomVertex(POGL_VECTOR3F(0.5f, -0.5f, 0.0f), 1.0f)
};
//
// Create a vertex buffer resource based using the custom vertex structure
//
IPOGLVertexBuffer* vertexBuffer = context->CreateVertexBuffer(VERTICES, sizeof(VERTICES), &CustomVertexLayout, POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC);
while (POGLProcessEvents()) {
IPOGLRenderState* state = context->Apply(simpleEffect);
state->Clear(POGLClearType::COLOR | POGLClearType::DEPTH);
//
// Draw the vertex buffer in the same way as normal
//
state->Draw(vertexBuffer);
state->EndFrame();
device->SwapBuffers();
}
//
// Release the vertex resources in the same way as normal
//
vertexBuffer->Release();
simpleEffect->Release();
context->Release();
}
catch (POGLException e) {
POGLAlert(e);
}
device->Release();
POGLDestroyExampleWindow(windowHandle);
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "lighting.h"
#include <QtGui>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
Lighting::Lighting(QWidget *parent): QGraphicsView(parent), angle(0.0)
{
setScene(&m_scene);
setupScene();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(animate()));
timer->setInterval(30);
timer->start();
setRenderHint(QPainter::Antialiasing, true);
setFrameStyle(QFrame::NoFrame);
}
void Lighting::setupScene()
{
m_scene.setSceneRect(-300, -200, 600, 460);
QLinearGradient linearGrad(QPointF(-100, -100), QPointF(100, 100));
linearGrad.setColorAt(0, QColor(255, 255, 255));
linearGrad.setColorAt(1, QColor(192, 192, 255));
setBackgroundBrush(linearGrad);
QRadialGradient radialGrad(30, 30, 30);
radialGrad.setColorAt(0, Qt::yellow);
radialGrad.setColorAt(0.2, Qt::yellow);
radialGrad.setColorAt(1, Qt::transparent);
QPixmap pixmap(60, 60);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setPen(Qt::NoPen);
painter.setBrush(radialGrad);
painter.drawEllipse(0, 0, 60, 60);
painter.end();
m_lightSource = m_scene.addPixmap(pixmap);
m_lightSource->setZValue(2);
for (int i = -2; i < 3; ++i)
for (int j = -2; j < 3; ++j) {
QAbstractGraphicsShapeItem *item;
if ((i + j) & 1)
item = new QGraphicsEllipseItem(0, 0, 50, 50);
else
item = new QGraphicsRectItem(0, 0, 50, 50);
item->setPen(QPen(Qt::black));
item->setBrush(QBrush(Qt::white));
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect;
effect->setBlurRadius(8);
item->setGraphicsEffect(effect);
item->setZValue(1);
item->setPos(i * 80, j * 80);
m_scene.addItem(item);
m_items << item;
}
}
void Lighting::animate()
{
angle += (M_PI / 30);
qreal xs = 200 * sin(angle) - 40 + 25;
qreal ys = 200 * cos(angle) - 40 + 25;
m_lightSource->setPos(xs, ys);
for (int i = 0; i < m_items.size(); ++i) {
QGraphicsItem *item = m_items.at(i);
Q_ASSERT(item);
QGraphicsDropShadowEffect *effect = static_cast<QGraphicsDropShadowEffect *>(item->graphicsEffect());
Q_ASSERT(effect);
QPointF delta(item->x() - xs, item->y() - ys);
effect->setOffset(delta.toPoint() / 30);
qreal dx = delta.x();
qreal dy = delta.y();
qreal dd = sqrt(dx * dx + dy * dy);
QColor color = effect->color();
color.setAlphaF(qBound(0.4, 1 - dd / 200.0, 0.7));
effect->setColor(color);
}
m_scene.update();
}
<commit_msg>Use a non-cosmetic 1-width pen in example to match graphicsview specs<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "lighting.h"
#include <QtGui>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
Lighting::Lighting(QWidget *parent): QGraphicsView(parent), angle(0.0)
{
setScene(&m_scene);
setupScene();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(animate()));
timer->setInterval(30);
timer->start();
setRenderHint(QPainter::Antialiasing, true);
setFrameStyle(QFrame::NoFrame);
}
void Lighting::setupScene()
{
m_scene.setSceneRect(-300, -200, 600, 460);
QLinearGradient linearGrad(QPointF(-100, -100), QPointF(100, 100));
linearGrad.setColorAt(0, QColor(255, 255, 255));
linearGrad.setColorAt(1, QColor(192, 192, 255));
setBackgroundBrush(linearGrad);
QRadialGradient radialGrad(30, 30, 30);
radialGrad.setColorAt(0, Qt::yellow);
radialGrad.setColorAt(0.2, Qt::yellow);
radialGrad.setColorAt(1, Qt::transparent);
QPixmap pixmap(60, 60);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setPen(Qt::NoPen);
painter.setBrush(radialGrad);
painter.drawEllipse(0, 0, 60, 60);
painter.end();
m_lightSource = m_scene.addPixmap(pixmap);
m_lightSource->setZValue(2);
for (int i = -2; i < 3; ++i)
for (int j = -2; j < 3; ++j) {
QAbstractGraphicsShapeItem *item;
if ((i + j) & 1)
item = new QGraphicsEllipseItem(0, 0, 50, 50);
else
item = new QGraphicsRectItem(0, 0, 50, 50);
item->setPen(QPen(Qt::black, 1));
item->setBrush(QBrush(Qt::white));
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect;
effect->setBlurRadius(8);
item->setGraphicsEffect(effect);
item->setZValue(1);
item->setPos(i * 80, j * 80);
m_scene.addItem(item);
m_items << item;
}
}
void Lighting::animate()
{
angle += (M_PI / 30);
qreal xs = 200 * sin(angle) - 40 + 25;
qreal ys = 200 * cos(angle) - 40 + 25;
m_lightSource->setPos(xs, ys);
for (int i = 0; i < m_items.size(); ++i) {
QGraphicsItem *item = m_items.at(i);
Q_ASSERT(item);
QGraphicsDropShadowEffect *effect = static_cast<QGraphicsDropShadowEffect *>(item->graphicsEffect());
Q_ASSERT(effect);
QPointF delta(item->x() - xs, item->y() - ys);
effect->setOffset(delta.toPoint() / 30);
qreal dx = delta.x();
qreal dy = delta.y();
qreal dd = sqrt(dx * dx + dy * dy);
QColor color = effect->color();
color.setAlphaF(qBound(0.4, 1 - dd / 200.0, 0.7));
effect->setColor(color);
}
m_scene.update();
}
<|endoftext|> |
<commit_before>/* OpenSceneGraph example, osganimate.
*
* 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 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 <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#if USE_QT4
#include <QtCore/QString>
#include <QtCore/QTimer>
#include <QtGui/QKeyEvent>
#include <QtGui/QApplication>
#include <QtOpenGL/QGLWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QMdiSubWindow>
#include <QtGui/QMdiArea>
using Qt::WindowFlags;
#else
class QWidget;
#include <qtimer.h>
#include <qgl.h>
#include <qapplication.h>
#define WindowFlags WFlags
#endif
#include <iostream>
class AdapterWidget : public QGLWidget
{
public:
AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0 );
virtual ~AdapterWidget() {}
osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }
protected:
void init();
virtual void resizeGL( int width, int height );
virtual void keyPressEvent( QKeyEvent* event );
virtual void keyReleaseEvent( QKeyEvent* event );
virtual void mousePressEvent( QMouseEvent* event );
virtual void mouseReleaseEvent( QMouseEvent* event );
virtual void mouseMoveEvent( QMouseEvent* event );
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};
AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WindowFlags f):
#if USE_QT4
QGLWidget(parent, shareWidget, f)
#else
QGLWidget(parent, name, shareWidget, f)
#endif
{
_gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height());
setFocusPolicy(Qt::ClickFocus);
}
void AdapterWidget::resizeGL( int width, int height )
{
_gw->getEventQueue()->windowResize(0, 0, width, height );
_gw->resized(0,0,width,height);
}
void AdapterWidget::keyPressEvent( QKeyEvent* event )
{
#if USE_QT4
_gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data() ) );
#else
_gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
#endif
}
void AdapterWidget::keyReleaseEvent( QKeyEvent* event )
{
#if USE_QT4
_gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data() ) );
#else
_gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
#endif
}
void AdapterWidget::mousePressEvent( QMouseEvent* event )
{
int button = 0;
switch(event->button())
{
case(Qt::LeftButton): button = 1; break;
case(Qt::MidButton): button = 2; break;
case(Qt::RightButton): button = 3; break;
case(Qt::NoButton): button = 0; break;
default: button = 0; break;
}
_gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button);
}
void AdapterWidget::mouseReleaseEvent( QMouseEvent* event )
{
int button = 0;
switch(event->button())
{
case(Qt::LeftButton): button = 1; break;
case(Qt::MidButton): button = 2; break;
case(Qt::RightButton): button = 3; break;
case(Qt::NoButton): button = 0; break;
default: button = 0; break;
}
_gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button);
}
void AdapterWidget::mouseMoveEvent( QMouseEvent* event )
{
_gw->getEventQueue()->mouseMotion(event->x(), event->y());
}
class ViewerQT : public osgViewer::Viewer, public AdapterWidget
{
public:
ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0):
AdapterWidget( parent, name, shareWidget, f )
{
getCamera()->setViewport(new osg::Viewport(0,0,width(),height()));
getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width())/static_cast<double>(height()), 1.0f, 10000.0f);
getCamera()->setGraphicsContext(getGraphicsWindow());
setThreadingModel(osgViewer::Viewer::SingleThreaded);
connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
_timer.start(10);
}
virtual void paintGL()
{
frame();
}
protected:
QTimer _timer;
};
class CompositeViewerQT : public osgViewer::CompositeViewer, public AdapterWidget
{
public:
CompositeViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0):
AdapterWidget( parent, name, shareWidget, f )
{
setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
_timer.start(10);
}
virtual void paintGL()
{
frame();
}
protected:
QTimer _timer;
};
int mainAdapterWidget(QApplication& a, osg::ArgumentParser& arguments)
{
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
std::cout << arguments[0] <<": No data loaded." << std::endl;
return 1;
}
std::cout<<"Using AdapterWidget - QGLWidget subclassed to integrate with osgViewer using its embedded graphics window support."<<std::endl;
if (arguments.read("--CompositeViewer"))
{
CompositeViewerQT* viewerWindow = new CompositeViewerQT;
unsigned int width = viewerWindow->width();
unsigned int height = viewerWindow->height();
{
osgViewer::View* view1 = new osgViewer::View;
view1->getCamera()->setGraphicsContext(viewerWindow->getGraphicsWindow());
view1->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view1->getCamera()->setViewport(new osg::Viewport(0,0,width,height/2));
view1->setCameraManipulator(new osgGA::TrackballManipulator);
view1->setSceneData(loadedModel.get());
viewerWindow->addView(view1);
}
{
osgViewer::View* view2 = new osgViewer::View;
view2->getCamera()->setGraphicsContext(viewerWindow->getGraphicsWindow());
view2->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view2->getCamera()->setViewport(new osg::Viewport(0,height/2,width,height/2));
view2->setCameraManipulator(new osgGA::TrackballManipulator);
view2->setSceneData(loadedModel.get());
viewerWindow->addView(view2);
}
viewerWindow->show();
}
else if (arguments.read("--mdi")) {
std::cout<<"Using ViewetQT MDI version"<<std::endl;
/*
Following problems are found here:
- miminize causes loaded model to disappear (some problem with Camera matrix? - clampProjectionMatrix is invalid)
*/
ViewerQT* viewerWindow = new ViewerQT;
viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow->setSceneData(loadedModel.get());
QMainWindow* mw = new QMainWindow();
QMdiArea* mdiArea = new QMdiArea(mw);
mw->setCentralWidget(mdiArea);
QMdiSubWindow *subWindow = mdiArea->addSubWindow(viewerWindow);
subWindow->showMaximized();
subWindow->setWindowTitle("New Window");
mw->show();
} else {
ViewerQT* viewerWindow = new ViewerQT;
viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow->setSceneData(loadedModel.get());
viewerWindow->show();
}
a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
return a.exec();
}
/*EOF*/
<commit_msg>From John Shue, build fix for QT 3.x<commit_after>/* OpenSceneGraph example, osganimate.
*
* 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 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 <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#if USE_QT4
#include <QtCore/QString>
#include <QtCore/QTimer>
#include <QtGui/QKeyEvent>
#include <QtGui/QApplication>
#include <QtOpenGL/QGLWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QMdiSubWindow>
#include <QtGui/QMdiArea>
using Qt::WindowFlags;
#else
class QWidget;
#include <qtimer.h>
#include <qgl.h>
#include <qapplication.h>
#define WindowFlags WFlags
#endif
#include <iostream>
class AdapterWidget : public QGLWidget
{
public:
AdapterWidget( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0 );
virtual ~AdapterWidget() {}
osgViewer::GraphicsWindow* getGraphicsWindow() { return _gw.get(); }
const osgViewer::GraphicsWindow* getGraphicsWindow() const { return _gw.get(); }
protected:
void init();
virtual void resizeGL( int width, int height );
virtual void keyPressEvent( QKeyEvent* event );
virtual void keyReleaseEvent( QKeyEvent* event );
virtual void mousePressEvent( QMouseEvent* event );
virtual void mouseReleaseEvent( QMouseEvent* event );
virtual void mouseMoveEvent( QMouseEvent* event );
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _gw;
};
AdapterWidget::AdapterWidget( QWidget * parent, const char * name, const QGLWidget * shareWidget, WindowFlags f):
#if USE_QT4
QGLWidget(parent, shareWidget, f)
#else
QGLWidget(parent, name, shareWidget, f)
#endif
{
_gw = new osgViewer::GraphicsWindowEmbedded(0,0,width(),height());
#if USE_QT4
setFocusPolicy(Qt::ClickFocus);
#else
setFocusPolicy(QWidget::ClickFocus);
#endif
}
void AdapterWidget::resizeGL( int width, int height )
{
_gw->getEventQueue()->windowResize(0, 0, width, height );
_gw->resized(0,0,width,height);
}
void AdapterWidget::keyPressEvent( QKeyEvent* event )
{
#if USE_QT4
_gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data() ) );
#else
_gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
#endif
}
void AdapterWidget::keyReleaseEvent( QKeyEvent* event )
{
#if USE_QT4
_gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data() ) );
#else
_gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event->ascii() );
#endif
}
void AdapterWidget::mousePressEvent( QMouseEvent* event )
{
int button = 0;
switch(event->button())
{
case(Qt::LeftButton): button = 1; break;
case(Qt::MidButton): button = 2; break;
case(Qt::RightButton): button = 3; break;
case(Qt::NoButton): button = 0; break;
default: button = 0; break;
}
_gw->getEventQueue()->mouseButtonPress(event->x(), event->y(), button);
}
void AdapterWidget::mouseReleaseEvent( QMouseEvent* event )
{
int button = 0;
switch(event->button())
{
case(Qt::LeftButton): button = 1; break;
case(Qt::MidButton): button = 2; break;
case(Qt::RightButton): button = 3; break;
case(Qt::NoButton): button = 0; break;
default: button = 0; break;
}
_gw->getEventQueue()->mouseButtonRelease(event->x(), event->y(), button);
}
void AdapterWidget::mouseMoveEvent( QMouseEvent* event )
{
_gw->getEventQueue()->mouseMotion(event->x(), event->y());
}
class ViewerQT : public osgViewer::Viewer, public AdapterWidget
{
public:
ViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0):
AdapterWidget( parent, name, shareWidget, f )
{
getCamera()->setViewport(new osg::Viewport(0,0,width(),height()));
getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width())/static_cast<double>(height()), 1.0f, 10000.0f);
getCamera()->setGraphicsContext(getGraphicsWindow());
setThreadingModel(osgViewer::Viewer::SingleThreaded);
connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
_timer.start(10);
}
virtual void paintGL()
{
frame();
}
protected:
QTimer _timer;
};
class CompositeViewerQT : public osgViewer::CompositeViewer, public AdapterWidget
{
public:
CompositeViewerQT(QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WindowFlags f = 0):
AdapterWidget( parent, name, shareWidget, f )
{
setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
_timer.start(10);
}
virtual void paintGL()
{
frame();
}
protected:
QTimer _timer;
};
int mainAdapterWidget(QApplication& a, osg::ArgumentParser& arguments)
{
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
std::cout << arguments[0] <<": No data loaded." << std::endl;
return 1;
}
std::cout<<"Using AdapterWidget - QGLWidget subclassed to integrate with osgViewer using its embedded graphics window support."<<std::endl;
if (arguments.read("--CompositeViewer"))
{
CompositeViewerQT* viewerWindow = new CompositeViewerQT;
unsigned int width = viewerWindow->width();
unsigned int height = viewerWindow->height();
{
osgViewer::View* view1 = new osgViewer::View;
view1->getCamera()->setGraphicsContext(viewerWindow->getGraphicsWindow());
view1->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view1->getCamera()->setViewport(new osg::Viewport(0,0,width,height/2));
view1->setCameraManipulator(new osgGA::TrackballManipulator);
view1->setSceneData(loadedModel.get());
viewerWindow->addView(view1);
}
{
osgViewer::View* view2 = new osgViewer::View;
view2->getCamera()->setGraphicsContext(viewerWindow->getGraphicsWindow());
view2->getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width)/static_cast<double>(height/2), 1.0, 1000.0);
view2->getCamera()->setViewport(new osg::Viewport(0,height/2,width,height/2));
view2->setCameraManipulator(new osgGA::TrackballManipulator);
view2->setSceneData(loadedModel.get());
viewerWindow->addView(view2);
}
viewerWindow->show();
#if USE_QT4
}
else if (arguments.read("--mdi")) {
std::cout<<"Using ViewetQT MDI version"<<std::endl;
/*
Following problems are found here:
- miminize causes loaded model to disappear (some problem with Camera matrix? - clampProjectionMatrix is invalid)
*/
ViewerQT* viewerWindow = new ViewerQT;
viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow->setSceneData(loadedModel.get());
QMainWindow* mw = new QMainWindow();
QMdiArea* mdiArea = new QMdiArea(mw);
mw->setCentralWidget(mdiArea);
QMdiSubWindow *subWindow = mdiArea->addSubWindow(viewerWindow);
subWindow->showMaximized();
subWindow->setWindowTitle("New Window");
mw->show();
#endif // USE_QT4
} else {
ViewerQT* viewerWindow = new ViewerQT;
viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator);
viewerWindow->setSceneData(loadedModel.get());
viewerWindow->show();
}
a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
return a.exec();
}
/*EOF*/
<|endoftext|> |
<commit_before>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/common/NativeProcessProtocol.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
using namespace lldb_private;
using namespace lldb;
using namespace testing;
namespace {
class MockDelegate : public NativeProcessProtocol::NativeDelegate {
public:
MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process));
MOCK_METHOD2(ProcessStateChanged,
void(NativeProcessProtocol *Process, StateType State));
MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process));
};
class MockProcess : public NativeProcessProtocol {
public:
MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch,
lldb::pid_t Pid = 1)
: NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {}
MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions));
MOCK_METHOD0(Halt, Status());
MOCK_METHOD0(Detach, Status());
MOCK_METHOD1(Signal, Status(int Signo));
MOCK_METHOD0(Kill, Status());
MOCK_METHOD3(AllocateMemory,
Status(size_t Size, uint32_t Permissions, addr_t &Addr));
MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr));
MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t());
MOCK_METHOD0(UpdateThreads, size_t());
MOCK_CONST_METHOD0(GetAuxvData,
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>());
MOCK_METHOD2(GetLoadedModuleFileSpec,
Status(const char *ModulePath, FileSpec &Spec));
MOCK_METHOD2(GetFileLoadAddress,
Status(const llvm::StringRef &FileName, addr_t &Addr));
const ArchSpec &GetArchitecture() const override { return Arch; }
Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size,
bool Hardware) override {
if (Hardware)
return SetHardwareBreakpoint(Addr, Size);
else
return SetSoftwareBreakpoint(Addr, Size);
}
// Redirect base class Read/Write Memory methods to functions whose signatures
// are more mock-friendly.
Status ReadMemory(addr_t Addr, void *Buf, size_t Size,
size_t &BytesRead) override;
Status WriteMemory(addr_t Addr, const void *Buf, size_t Size,
size_t &BytesWritten) override;
MOCK_METHOD2(ReadMemory,
llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size));
MOCK_METHOD2(WriteMemory,
llvm::Expected<size_t>(addr_t Addr,
llvm::ArrayRef<uint8_t> Data));
using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode;
llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr,
size_t Size);
private:
ArchSpec Arch;
};
class FakeMemory {
public:
FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {}
llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size);
llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk);
private:
std::vector<uint8_t> Data;
};
} // namespace
Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size,
size_t &BytesRead) {
auto ExpectedMemory = ReadMemory(Addr, Size);
if (!ExpectedMemory) {
BytesRead = 0;
return Status(ExpectedMemory.takeError());
}
BytesRead = ExpectedMemory->size();
assert(BytesRead <= Size);
std::memcpy(Buf, ExpectedMemory->data(), BytesRead);
return Status();
}
Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size,
size_t &BytesWritten) {
auto ExpectedBytes = WriteMemory(
Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size));
if (!ExpectedBytes) {
BytesWritten = 0;
return Status(ExpectedBytes.takeError());
}
BytesWritten = *ExpectedBytes;
return Status();
}
llvm::Expected<std::vector<uint8_t>>
MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) {
std::vector<uint8_t> Data(Size, 0);
size_t BytesRead;
Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap(
Addr, Data.data(), Data.size(), BytesRead);
if (ST.Fail())
return ST.ToError();
Data.resize(BytesRead);
return std::move(Data);
}
llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr,
size_t Size) {
if (Addr >= Data.size())
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Address out of range.");
Size = std::min(Size, Data.size() - (size_t)Addr);
return std::vector<uint8_t>(&Data[Addr], &Data[Addr + Size]);
}
llvm::Expected<size_t> FakeMemory::Write(addr_t Addr,
llvm::ArrayRef<uint8_t> Chunk) {
if (Addr >= Data.size())
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Address out of range.");
size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr);
std::copy_n(Chunk.begin(), Size, &Data[Addr]);
return Size;
}
TEST(NativeProcessProtocolTest, SetBreakpoint) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap)));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Succeeded());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailRead) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux"));
FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
EXPECT_CALL(Process, ReadMemory(_, _))
.WillRepeatedly(Invoke(&M, &FakeMemory::Read));
EXPECT_CALL(Process, WriteMemory(_, _))
.WillRepeatedly(Invoke(&M, &FakeMemory::Write));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(),
llvm::Succeeded());
EXPECT_THAT_EXPECTED(
Process.ReadMemoryWithoutTrap(0, 10),
llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6),
llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4),
llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2),
llvm::HasValue(std::vector<uint8_t>{6, 7}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2),
llvm::HasValue(std::vector<uint8_t>{4, 5}));
}
<commit_msg>Fix assertion failure in NativeProcessProtocolTest<commit_after>//===-- NativeProcessProtocolTest.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/common/NativeProcessProtocol.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
using namespace lldb_private;
using namespace lldb;
using namespace testing;
namespace {
class MockDelegate : public NativeProcessProtocol::NativeDelegate {
public:
MOCK_METHOD1(InitializeDelegate, void(NativeProcessProtocol *Process));
MOCK_METHOD2(ProcessStateChanged,
void(NativeProcessProtocol *Process, StateType State));
MOCK_METHOD1(DidExec, void(NativeProcessProtocol *Process));
};
class MockProcess : public NativeProcessProtocol {
public:
MockProcess(NativeDelegate &Delegate, const ArchSpec &Arch,
lldb::pid_t Pid = 1)
: NativeProcessProtocol(Pid, -1, Delegate), Arch(Arch) {}
MOCK_METHOD1(Resume, Status(const ResumeActionList &ResumeActions));
MOCK_METHOD0(Halt, Status());
MOCK_METHOD0(Detach, Status());
MOCK_METHOD1(Signal, Status(int Signo));
MOCK_METHOD0(Kill, Status());
MOCK_METHOD3(AllocateMemory,
Status(size_t Size, uint32_t Permissions, addr_t &Addr));
MOCK_METHOD1(DeallocateMemory, Status(addr_t Addr));
MOCK_METHOD0(GetSharedLibraryInfoAddress, addr_t());
MOCK_METHOD0(UpdateThreads, size_t());
MOCK_CONST_METHOD0(GetAuxvData,
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>());
MOCK_METHOD2(GetLoadedModuleFileSpec,
Status(const char *ModulePath, FileSpec &Spec));
MOCK_METHOD2(GetFileLoadAddress,
Status(const llvm::StringRef &FileName, addr_t &Addr));
const ArchSpec &GetArchitecture() const override { return Arch; }
Status SetBreakpoint(lldb::addr_t Addr, uint32_t Size,
bool Hardware) override {
if (Hardware)
return SetHardwareBreakpoint(Addr, Size);
else
return SetSoftwareBreakpoint(Addr, Size);
}
// Redirect base class Read/Write Memory methods to functions whose signatures
// are more mock-friendly.
Status ReadMemory(addr_t Addr, void *Buf, size_t Size,
size_t &BytesRead) override;
Status WriteMemory(addr_t Addr, const void *Buf, size_t Size,
size_t &BytesWritten) override;
MOCK_METHOD2(ReadMemory,
llvm::Expected<std::vector<uint8_t>>(addr_t Addr, size_t Size));
MOCK_METHOD2(WriteMemory,
llvm::Expected<size_t>(addr_t Addr,
llvm::ArrayRef<uint8_t> Data));
using NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode;
llvm::Expected<std::vector<uint8_t>> ReadMemoryWithoutTrap(addr_t Addr,
size_t Size);
private:
ArchSpec Arch;
};
class FakeMemory {
public:
FakeMemory(llvm::ArrayRef<uint8_t> Data) : Data(Data) {}
llvm::Expected<std::vector<uint8_t>> Read(addr_t Addr, size_t Size);
llvm::Expected<size_t> Write(addr_t Addr, llvm::ArrayRef<uint8_t> Chunk);
private:
std::vector<uint8_t> Data;
};
} // namespace
Status MockProcess::ReadMemory(addr_t Addr, void *Buf, size_t Size,
size_t &BytesRead) {
auto ExpectedMemory = ReadMemory(Addr, Size);
if (!ExpectedMemory) {
BytesRead = 0;
return Status(ExpectedMemory.takeError());
}
BytesRead = ExpectedMemory->size();
assert(BytesRead <= Size);
std::memcpy(Buf, ExpectedMemory->data(), BytesRead);
return Status();
}
Status MockProcess::WriteMemory(addr_t Addr, const void *Buf, size_t Size,
size_t &BytesWritten) {
auto ExpectedBytes = WriteMemory(
Addr, llvm::makeArrayRef(static_cast<const uint8_t *>(Buf), Size));
if (!ExpectedBytes) {
BytesWritten = 0;
return Status(ExpectedBytes.takeError());
}
BytesWritten = *ExpectedBytes;
return Status();
}
llvm::Expected<std::vector<uint8_t>>
MockProcess::ReadMemoryWithoutTrap(addr_t Addr, size_t Size) {
std::vector<uint8_t> Data(Size, 0);
size_t BytesRead;
Status ST = NativeProcessProtocol::ReadMemoryWithoutTrap(
Addr, Data.data(), Data.size(), BytesRead);
if (ST.Fail())
return ST.ToError();
Data.resize(BytesRead);
return std::move(Data);
}
llvm::Expected<std::vector<uint8_t>> FakeMemory::Read(addr_t Addr,
size_t Size) {
if (Addr >= Data.size())
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Address out of range.");
Size = std::min(Size, Data.size() - (size_t)Addr);
auto Begin = std::next(Data.begin(), Addr);
return std::vector<uint8_t>(Begin, std::next(Begin, Size));
}
llvm::Expected<size_t> FakeMemory::Write(addr_t Addr,
llvm::ArrayRef<uint8_t> Chunk) {
if (Addr >= Data.size())
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Address out of range.");
size_t Size = std::min(Chunk.size(), Data.size() - (size_t)Addr);
std::copy_n(Chunk.begin(), Size, &Data[Addr]);
return Size;
}
TEST(NativeProcessProtocolTest, SetBreakpoint) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
EXPECT_CALL(Process, ReadMemory(0x47, 1)).WillOnce(Return(ByMove(Trap)));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Succeeded());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailRead) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailWrite) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, SetBreakpointFailVerify) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("x86_64-pc-linux"));
auto Trap = cantFail(Process.GetSoftwareBreakpointTrapOpcode(1));
InSequence S;
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(std::vector<uint8_t>{0xbb})));
EXPECT_CALL(Process, WriteMemory(0x47, Trap)).WillOnce(Return(ByMove(1)));
EXPECT_CALL(Process, ReadMemory(0x47, 1))
.WillOnce(Return(ByMove(
llvm::createStringError(llvm::inconvertibleErrorCode(), "Foo"))));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x47, 0, false).ToError(),
llvm::Failed());
}
TEST(NativeProcessProtocolTest, ReadMemoryWithoutTrap) {
NiceMock<MockDelegate> DummyDelegate;
MockProcess Process(DummyDelegate, ArchSpec("aarch64-pc-linux"));
FakeMemory M{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
EXPECT_CALL(Process, ReadMemory(_, _))
.WillRepeatedly(Invoke(&M, &FakeMemory::Read));
EXPECT_CALL(Process, WriteMemory(_, _))
.WillRepeatedly(Invoke(&M, &FakeMemory::Write));
EXPECT_THAT_ERROR(Process.SetBreakpoint(0x4, 0, false).ToError(),
llvm::Succeeded());
EXPECT_THAT_EXPECTED(
Process.ReadMemoryWithoutTrap(0, 10),
llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(0, 6),
llvm::HasValue(std::vector<uint8_t>{0, 1, 2, 3, 4, 5}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 4),
llvm::HasValue(std::vector<uint8_t>{6, 7, 8, 9}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(6, 2),
llvm::HasValue(std::vector<uint8_t>{6, 7}));
EXPECT_THAT_EXPECTED(Process.ReadMemoryWithoutTrap(4, 2),
llvm::HasValue(std::vector<uint8_t>{4, 5}));
}
<|endoftext|> |
<commit_before>#include "include/Media.h"
#include <iostream>
/**< ShapeMedia */
Shape * ShapeMedia::getShape(){
return shape;
}
double ShapeMedia::area() const{
return shape->area();
}
double ShapeMedia::perimeter() const{
return shape->perimeter();
}
/**< ComboMedia */
ComboMedia::ComboMedia() {
std::vector<Media *> instance;
medias = instance;
}
void ComboMedia::add(Media * ma){
medias.push_back(ma);
}
std::vector<Media *> ComboMedia::getMedias(){
return medias;
}
double ComboMedia::area() const{
double total = 0;
for (Media * mp : medias)
total += mp->area();
return total;
}
double ComboMedia::perimeter() const{
double total = 0;
for (Media * mp : medias)
total += mp->perimeter();
return total;
}
<commit_msg>Delete Media.cpp<commit_after><|endoftext|> |
<commit_before>#pragma once
#include "Tools/NoCreateU.hpp"
#include <string>
#include <vector>
namespace proZPRd
{
/**
Klasa opisująca podstawowe operacje na pliku
W chwili obecnej zakładam, że będzie zawierała wyłącznie metody statyczne itp, więc nie ma konstruktorów, destruktorów itp. Zabronienie tworzenia obiektów klasy gwarantuje dziedziczenie po NoCreateU
*/
class File : public Tools::NoCreateU
{
public:
typedef std::vector<std::string> Lines_t;
/**
Funkcja ma sprawdzić czy podany plik istnieje i czy jest plikiem.
Jeśli istnieje i jest plikiem - zwraca true
Jeśli nie istnieje lub nie jest plikiem - zwraca false
*/
static bool Exists(const std::string & FileName);
/**
Funkcja ma wczytać cały plik o podanej nazwie do pamięci i zwrócić go w postaci std::string.
Jeśli plik nie istnieje ma rzucić Tool::Exception z odpowiednimi parametrami
*/
static std::string ToString(const std::string & FileName);
/**
Funkcja wczytuje cały plik o podanej nazwie do pamięci i zwraca go w postaci Lines_t, czyli wektora zawierającego linie pliku
*/
static Lines_t GetLines(const std::string & FileName);
struct FileStruct
{
std::string Name;
std::string Extension;
};
/**
Funkcja ma podzielić nazwę pliku na nazwę i rozszerzenie.
Jeśli plik nie ma rozszerzenia, pozostaje ono puste.
*/
static FileStruct SplitFileName(const std::string & FileName);
};
}<commit_msg>Porządki w proZPRd/File.hpp<commit_after>#pragma once
#include "Tools/NoCreateU.hpp"
#include <string>
#include <vector>
namespace proZPRd
{
/**
Klasa opisująca podstawowe operacje na pliku
W chwili obecnej zakładam, że będzie zawierała wyłącznie metody statyczne itp, więc nie ma konstruktorów, destruktorów itp. Zabronienie tworzenia obiektów klasy gwarantuje dziedziczenie po NoCreateU
*/
class File : public Tools::NoCreateU
{
public:
/**
Funkcja ma sprawdzić czy podany plik istnieje i czy jest plikiem.
Jeśli istnieje i jest plikiem - zwraca true
Jeśli nie istnieje lub nie jest plikiem - zwraca false
*/
static bool Exists(const std::string & FileName);
/**
Funkcja ma wczytać cały plik o podanej nazwie do pamięci i zwrócić go w postaci std::string.
Jeśli plik nie istnieje ma rzucić Tool::Exception z odpowiednimi parametrami
*/
static std::string ToString(const std::string & FileName);
/**
Funkcja wczytuje cały plik o podanej nazwie do pamięci i zwraca go w postaci Lines_t, czyli wektora zawierającego linie pliku
*/
typedef std::vector<std::string> Lines_t;
static Lines_t GetLines(const std::string & FileName);
/**
Funkcja ma podzielić nazwę pliku na nazwę i rozszerzenie.
Jeśli plik nie ma rozszerzenia, pozostaje ono puste.
*/
struct FileStruct
{
std::string Name;
std::string Extension;
};
static FileStruct SplitFileName(const std::string & FileName);
};
}<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "Renderer.h"
#include "common/FrameBuffer.h"
#include "visitor/MarkAllAsModified.h"
#include "visitor/VerifyNodes.h"
namespace ospray {
namespace sg {
static std::vector<std::string> globalWhiteList = {
std::string("scivis"),
std::string("pathtracer"),
std::string("ao"),
std::string("raycast"),
std::string("raycast_vertexColor"),
std::string("raycast_dPds"),
std::string("raycast_dPdt"),
std::string("raycast_Ng"),
std::string("raycast_Ns"),
std::string("backfacing_Ng"),
std::string("backfacing_Ns"),
std::string("primID"),
std::string("geomID"),
std::string("instID"),
std::string("testFrame")
};
std::vector<std::string> Renderer::globalRendererTypeWhiteList()
{
return globalWhiteList;
}
void Renderer::setGlobalRendererTypeWhiteList(std::vector<std::string> list)
{
globalWhiteList = list;
}
Renderer::Renderer()
{
std::string defaultRendererType =
globalWhiteList.empty() ? "scivis" : globalWhiteList[0];
createChild("rendererType", "string", defaultRendererType,
NodeFlags::required |
NodeFlags::gui_combo,
"scivis: standard whitted style ray tracer. "
"pathtracer/pt: photo-realistic path tracer");
std::vector<Any> whiteList;
for (auto &v : globalWhiteList)
whiteList.push_back(v);
child("rendererType").setWhiteList(whiteList);
createChild("world",
"Model").setDocumentation("model containing scene objects");
createChild("camera", "PerspectiveCamera");
createChild("frameBuffer", "FrameBuffer");
createChild("lights");
createChild("bgColor", "vec3f", vec3f(0.15f, 0.15f, 0.15f),
NodeFlags::required |
NodeFlags::gui_color);
createChild("spp", "int", 1,
NodeFlags::required | NodeFlags::gui_slider,
"the number of samples rendered per pixel. The higher "
"the number, the smoother the resulting image.");
child("spp").setMinMax(-8,128);
createChild("minContribution", "float", 0.001f,
NodeFlags::required |
NodeFlags::gui_slider,
"sample contributions below this value will be neglected"
" to speed-up rendering.");
child("minContribution").setMinMax(0.f, 0.1f);
createChild("maxContribution", "float", 5.f,
NodeFlags::required |
NodeFlags::gui_slider,
"sample contributions above this value will be ignored."
" This reduces bright dots appearing in images");
child("maxContribution").setMinMax(1e-5f, 1e5f);
createChild("varianceThreshold", "float", 0.f,
NodeFlags::required |
NodeFlags::gui_slider,
"the percent (%) threshold of pixel difference to enable"
" tile rendering early termination.");
child("varianceThreshold").setMinMax(0.f, 25.f);
//TODO: move these to seperate SciVisRenderer
createChild("shadowsEnabled", "bool", true);
createChild("maxDepth", "int", 5,
NodeFlags::required | NodeFlags::valid_min_max,
"maximum number of ray bounces").setMinMax(0,999);
createChild("aoSamples", "int", 1,
NodeFlags::required |
NodeFlags::gui_slider,
"AO samples per frame.").setMinMax(0,128);
createChild("aoDistance", "float", 10000.f,
NodeFlags::required,
"maximum distance ao rays will trace to."
" Useful if you do not want a large interior of a"
" building to be completely black from occlusion.");
child("aoDistance").setMinMax(1e-20f, 1e20f);
createChild("epsilon", "float", 1e-3f,
NodeFlags::required | NodeFlags::valid_min_max,
"epsilon step for secondary ray generation. Adjust"
" if you see speckles or a lack of lighting.");
child("epsilon").setMinMax(1e-20f, 1e20f);
createChild("autoEpsilon", "bool", true, NodeFlags::required,
"automatically adjust epsilon step");
createChild("oneSidedLighting", "bool", true, NodeFlags::required);
createChild("aoTransparencyEnabled", "bool", true, NodeFlags::required);
createChild("backplate", "Texture2D");
auto backplate = child("backplate").nodeAs<Texture2D>();
backplate->size.x = 1;
backplate->size.y = 1;
backplate->channels = 3;
backplate->preferLinear = true;
backplate->depth = 4;
const size_t stride = backplate->size.x * backplate->channels * backplate->depth;
backplate->data = malloc(sizeof(unsigned char) * backplate->size.y * stride);
vec3f bgColor = child("bgColor").valueAs<vec3f>();
memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
createChild("useBackplate", "bool", true, NodeFlags::none, "use\
backplate for path tracer");
}
Renderer::~Renderer()
{
if (lightsData)
ospRelease(lightsData);
}
void Renderer::renderFrame(std::shared_ptr<FrameBuffer> fb,
int flags,
bool verifyCommit)
{
RenderContext ctx;
if (verifyCommit) {
Node::traverse(VerifyNodes{});
traverse(ctx, "commit");
}
traverse(ctx, "render");
variance = ospRenderFrame(fb->valueAs<OSPFrameBuffer>(),
ospRenderer,
flags);
}
std::string Renderer::toString() const
{
return "ospray::sg::Renderer";
}
void Renderer::traverse(RenderContext &ctx, const std::string& operation)
{
if (operation == "render") {
preRender(ctx);
postRender(ctx);
}
else
Node::traverse(ctx,operation);
}
void Renderer::traverse(const std::string& operation)
{
Node::traverse(operation);
}
void Renderer::preRender(RenderContext& ctx)
{
ctx.ospRenderer = ospRenderer;
ctx.ospRendererType = child("rendererType").valueAs<std::string>();
}
void Renderer::preCommit(RenderContext &ctx)
{
if (child("camera").hasChild("aspect") &&
child("frameBuffer")["size"].lastModified() >
child("camera")["aspect"].lastCommitted()) {
auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>();
child("camera")["aspect"] = fbSize.x / float(fbSize.y);
}
auto rendererType = child("rendererType").valueAs<std::string>();
if (!ospRenderer || rendererType != createdType) {
auto setRenderer = [&](OSPRenderer handle, const std::string &rType) {
Node::traverse(MarkAllAsModified{});
ospRenderer = handle;
createdType = rType;
ospCommit(ospRenderer);
setValue(ospRenderer);
};
auto potentialRenderer = ospNewRenderer(rendererType.c_str());
if (potentialRenderer != nullptr) {
setRenderer(potentialRenderer, rendererType);
} else if (ospRenderer == nullptr) {
//NOTE(jda) - default to scivs!
setRenderer(ospNewRenderer("scivis"), "scivis");
child("rendererType").setValue(std::string("scivis"));
} else {
//NOTE(jda) - revert rendererType back to name of currently valid
// renderer
child("rendererType").setValue(createdType);
}
}
auto backplate = child("backplate").nodeAs<Texture2D>();
vec3f bgColor = child("bgColor").valueAs<vec3f>();
memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
backplate->markAsModified();
ctx.ospRenderer = ospRenderer;
ctx.ospRendererType = rendererType;
ctx.world = child("world").nodeAs<sg::Model>();
}
void Renderer::postCommit(RenderContext &ctx)
{
bool modified = lastModified() > frameMTime;
if (!modified) {
for (const auto& c : children()) {
// ignore changes to the frame buffer/tone mapper
if (c.second->lastModified() > frameMTime
|| (c.second->childrenLastModified() > frameMTime
&& c.first != "frameBuffer"))
{
modified = true;
break;
}
}
}
if (modified) {
ospFrameBufferClear(
(OSPFrameBuffer)child("frameBuffer").valueAs<OSPObject>(),
OSP_FB_COLOR | OSP_FB_ACCUM
);
if (lightsData == nullptr ||
lightsBuildTime < child("lights").childrenLastModified())
{
// create and setup light list
std::vector<OSPLight> lights;
for(auto &lightNode : child("lights").children())
{
auto light = lightNode.second->valueAs<OSPLight>();
if (light)
lights.push_back(light);
}
if (lightsData)
ospRelease(lightsData);
lightsData = ospNewData(lights.size(), OSP_LIGHT, &lights[0]);
ospCommit(lightsData);
lightsBuildTime.renew();
}
// complete setup of renderer
ospSetObject(ospRenderer,"camera", child("camera").valueAs<OSPObject>());
ospSetObject(ospRenderer, "lights", lightsData);
ospSetObject(ospRenderer, "backplate", child("backplate").valueAs<OSPObject>());
if (child("world").childrenLastModified() > frameMTime)
{
child("world").finalize(ctx);
ospSetObject(ospRenderer, "model", child("world").valueAs<OSPObject>());
if (child("autoEpsilon").valueAs<bool>()) {
const box3f bounds = child("world")["bounds"].valueAs<box3f>();
const float diam = length(bounds.size());
float logDiam = ospcommon::log(diam);
if (logDiam < 0.f)
{
logDiam = -1.f/logDiam;
}
const float epsilon = 1e-5f*logDiam;
ospSet1f(ospRenderer, "epsilon", epsilon);
ospSet1f(ospRenderer, "aoDistance", diam*0.3);
}
}
if (!child("useBackplate").valueAs<bool>())
ospSetObject(ospRenderer, "backplate", nullptr);
ospCommit(ospRenderer);
frameMTime.renew();
}
}
OSPPickResult Renderer::pick(const vec2f &pickPos)
{
OSPPickResult result;
ospPick(&result, ospRenderer, (const osp::vec2f&)pickPos);
return result;
}
float Renderer::getLastVariance() const
{
return variance;
}
OSP_REGISTER_SG_NODE(Renderer);
} // ::ospray::sg
} // ::ospray
<commit_msg>working, w/o cross-instance<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "Renderer.h"
#include "common/FrameBuffer.h"
#include "visitor/MarkAllAsModified.h"
#include "visitor/VerifyNodes.h"
namespace ospray {
namespace sg {
static std::vector<std::string> globalWhiteList = {
std::string("scivis"),
std::string("pathtracer"),
std::string("ao"),
std::string("raycast"),
std::string("raycast_vertexColor"),
std::string("raycast_dPds"),
std::string("raycast_dPdt"),
std::string("raycast_Ng"),
std::string("raycast_Ns"),
std::string("backfacing_Ng"),
std::string("backfacing_Ns"),
std::string("primID"),
std::string("geomID"),
std::string("instID"),
std::string("testFrame")
};
std::vector<std::string> Renderer::globalRendererTypeWhiteList()
{
return globalWhiteList;
}
void Renderer::setGlobalRendererTypeWhiteList(std::vector<std::string> list)
{
globalWhiteList = list;
}
Renderer::Renderer()
{
std::string defaultRendererType =
globalWhiteList.empty() ? "scivis" : globalWhiteList[0];
createChild("rendererType", "string", defaultRendererType,
NodeFlags::required |
NodeFlags::gui_combo,
"scivis: standard whitted style ray tracer. "
"pathtracer/pt: photo-realistic path tracer");
std::vector<Any> whiteList;
for (auto &v : globalWhiteList)
whiteList.push_back(v);
child("rendererType").setWhiteList(whiteList);
createChild("world",
"Model").setDocumentation("model containing scene objects");
createChild("camera", "PerspectiveCamera");
createChild("frameBuffer", "FrameBuffer");
createChild("lights");
createChild("bgColor", "vec3f", vec3f(0.85f, 0.85f, 0.85f),
// createChild("bgColor", "vec3f", vec3f(0.15f, 0.15f, 0.15f),
NodeFlags::required |
NodeFlags::gui_color);
createChild("spp", "int", 1,
NodeFlags::required | NodeFlags::gui_slider,
"the number of samples rendered per pixel. The higher "
"the number, the smoother the resulting image.");
child("spp").setMinMax(-8,128);
createChild("minContribution", "float", 0.001f,
NodeFlags::required |
NodeFlags::gui_slider,
"sample contributions below this value will be neglected"
" to speed-up rendering.");
child("minContribution").setMinMax(0.f, 0.1f);
createChild("maxContribution", "float", 5.f,
NodeFlags::required |
NodeFlags::gui_slider,
"sample contributions above this value will be ignored."
" This reduces bright dots appearing in images");
child("maxContribution").setMinMax(1e-5f, 1e5f);
createChild("varianceThreshold", "float", 0.f,
NodeFlags::required |
NodeFlags::gui_slider,
"the percent (%) threshold of pixel difference to enable"
" tile rendering early termination.");
child("varianceThreshold").setMinMax(0.f, 25.f);
//TODO: move these to seperate SciVisRenderer
createChild("shadowsEnabled", "bool", true);
createChild("maxDepth", "int", 5,
NodeFlags::required | NodeFlags::valid_min_max,
"maximum number of ray bounces").setMinMax(0,999);
createChild("aoSamples", "int", 1,
NodeFlags::required |
NodeFlags::gui_slider,
"AO samples per frame.").setMinMax(0,128);
createChild("aoDistance", "float", 10000.f,
NodeFlags::required,
"maximum distance ao rays will trace to."
" Useful if you do not want a large interior of a"
" building to be completely black from occlusion.");
child("aoDistance").setMinMax(1e-20f, 1e20f);
createChild("epsilon", "float", 1e-3f,
NodeFlags::required | NodeFlags::valid_min_max,
"epsilon step for secondary ray generation. Adjust"
" if you see speckles or a lack of lighting.");
child("epsilon").setMinMax(1e-20f, 1e20f);
createChild("autoEpsilon", "bool", true, NodeFlags::required,
"automatically adjust epsilon step");
createChild("oneSidedLighting", "bool", true, NodeFlags::required);
createChild("aoTransparencyEnabled", "bool", true, NodeFlags::required);
createChild("backplate", "Texture2D");
auto backplate = child("backplate").nodeAs<Texture2D>();
backplate->size.x = 1;
backplate->size.y = 1;
backplate->channels = 3;
backplate->preferLinear = true;
backplate->depth = 4;
const size_t stride = backplate->size.x * backplate->channels * backplate->depth;
backplate->data = malloc(sizeof(unsigned char) * backplate->size.y * stride);
vec3f bgColor = child("bgColor").valueAs<vec3f>();
memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
createChild("useBackplate", "bool", true, NodeFlags::none, "use\
backplate for path tracer");
}
Renderer::~Renderer()
{
if (lightsData)
ospRelease(lightsData);
}
void Renderer::renderFrame(std::shared_ptr<FrameBuffer> fb,
int flags,
bool verifyCommit)
{
RenderContext ctx;
if (verifyCommit) {
Node::traverse(VerifyNodes{});
traverse(ctx, "commit");
}
traverse(ctx, "render");
variance = ospRenderFrame(fb->valueAs<OSPFrameBuffer>(),
ospRenderer,
flags);
}
std::string Renderer::toString() const
{
return "ospray::sg::Renderer";
}
void Renderer::traverse(RenderContext &ctx, const std::string& operation)
{
if (operation == "render") {
preRender(ctx);
postRender(ctx);
}
else
Node::traverse(ctx,operation);
}
void Renderer::traverse(const std::string& operation)
{
Node::traverse(operation);
}
void Renderer::preRender(RenderContext& ctx)
{
ctx.ospRenderer = ospRenderer;
ctx.ospRendererType = child("rendererType").valueAs<std::string>();
}
void Renderer::preCommit(RenderContext &ctx)
{
if (child("camera").hasChild("aspect") &&
child("frameBuffer")["size"].lastModified() >
child("camera")["aspect"].lastCommitted()) {
auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>();
child("camera")["aspect"] = fbSize.x / float(fbSize.y);
}
auto rendererType = child("rendererType").valueAs<std::string>();
if (!ospRenderer || rendererType != createdType) {
auto setRenderer = [&](OSPRenderer handle, const std::string &rType) {
Node::traverse(MarkAllAsModified{});
ospRenderer = handle;
createdType = rType;
ospCommit(ospRenderer);
setValue(ospRenderer);
};
auto potentialRenderer = ospNewRenderer(rendererType.c_str());
if (potentialRenderer != nullptr) {
setRenderer(potentialRenderer, rendererType);
} else if (ospRenderer == nullptr) {
//NOTE(jda) - default to scivs!
setRenderer(ospNewRenderer("scivis"), "scivis");
child("rendererType").setValue(std::string("scivis"));
} else {
//NOTE(jda) - revert rendererType back to name of currently valid
// renderer
child("rendererType").setValue(createdType);
}
}
auto backplate = child("backplate").nodeAs<Texture2D>();
vec3f bgColor = child("bgColor").valueAs<vec3f>();
memcpy(backplate->data, &bgColor.x, backplate->channels*backplate->depth);
backplate->markAsModified();
ctx.ospRenderer = ospRenderer;
ctx.ospRendererType = rendererType;
ctx.world = child("world").nodeAs<sg::Model>();
}
void Renderer::postCommit(RenderContext &ctx)
{
bool modified = lastModified() > frameMTime;
if (!modified) {
for (const auto& c : children()) {
// ignore changes to the frame buffer/tone mapper
if (c.second->lastModified() > frameMTime
|| (c.second->childrenLastModified() > frameMTime
&& c.first != "frameBuffer"))
{
modified = true;
break;
}
}
}
if (modified) {
ospFrameBufferClear(
(OSPFrameBuffer)child("frameBuffer").valueAs<OSPObject>(),
OSP_FB_COLOR | OSP_FB_ACCUM
);
if (lightsData == nullptr ||
lightsBuildTime < child("lights").childrenLastModified())
{
// create and setup light list
std::vector<OSPLight> lights;
for(auto &lightNode : child("lights").children())
{
auto light = lightNode.second->valueAs<OSPLight>();
if (light)
lights.push_back(light);
}
if (lightsData)
ospRelease(lightsData);
lightsData = ospNewData(lights.size(), OSP_LIGHT, &lights[0]);
ospCommit(lightsData);
lightsBuildTime.renew();
}
// complete setup of renderer
ospSetObject(ospRenderer,"camera", child("camera").valueAs<OSPObject>());
ospSetObject(ospRenderer, "lights", lightsData);
ospSetObject(ospRenderer, "backplate", child("backplate").valueAs<OSPObject>());
if (child("world").childrenLastModified() > frameMTime)
{
child("world").finalize(ctx);
ospSetObject(ospRenderer, "model", child("world").valueAs<OSPObject>());
if (child("autoEpsilon").valueAs<bool>()) {
const box3f bounds = child("world")["bounds"].valueAs<box3f>();
const float diam = length(bounds.size());
float logDiam = ospcommon::log(diam);
if (logDiam < 0.f)
{
logDiam = -1.f/logDiam;
}
const float epsilon = 1e-5f*logDiam;
ospSet1f(ospRenderer, "epsilon", epsilon);
ospSet1f(ospRenderer, "aoDistance", diam*0.3);
}
}
if (!child("useBackplate").valueAs<bool>())
ospSetObject(ospRenderer, "backplate", nullptr);
ospCommit(ospRenderer);
frameMTime.renew();
}
}
OSPPickResult Renderer::pick(const vec2f &pickPos)
{
OSPPickResult result;
ospPick(&result, ospRenderer, (const osp::vec2f&)pickPos);
return result;
}
float Renderer::getLastVariance() const
{
return variance;
}
OSP_REGISTER_SG_NODE(Renderer);
} // ::ospray::sg
} // ::ospray
<|endoftext|> |
<commit_before>#include <iostream>
#include "Includes/EngineLogger.h"
#include "SFML/Graphics.hpp"
int main() {
sf::RectangleShape rect(sf::Vector2f(50,40));
sf::RenderWindow window(sf::VideoMode(1280, 720), "Test");
EngineLogger logger = EngineLogger();
logger.Log(EngineLogger::LogLevel::LOG_INFO, "Renderer successfully initialised.");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
default:
break;
}
}
window.clear(sf::Color::Black);
window.draw(rect);
window.display();
}
}<commit_msg>made spacing less ugly<commit_after>#include <iostream>
#include "Includes/EngineLogger.h"
#include "SFML/Graphics.hpp"
int main() {
sf::RectangleShape rect(sf::Vector2f(50,40));
sf::RenderWindow window(sf::VideoMode(1280, 720), "Test");
EngineLogger logger = EngineLogger();
logger.Log(EngineLogger::LogLevel::LOG_INFO, "Renderer successfully initialised.");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
default:
break;
}
}
window.clear(sf::Color::Black);
window.draw(rect);
window.display();
}
}<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
*/
#include "Inst.h"
#include <Fabric/Core/KL/StringSource.h>
#include <Fabric/Core/KL/Scanner.h>
#include <Fabric/Core/KL/Parser.hpp>
#include <Fabric/Core/AST/Function.h>
#include <Fabric/Core/AST/GlobalList.h>
#include <Fabric/Core/CG/Manager.h>
#include <Fabric/Core/CG/ModuleBuilder.h>
#include <Fabric/Core/RT/Impl.h>
#include <Fabric/Core/DG/Context.h>
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Core/IO/Dir.h>
#include <Fabric/Core/Plug/Helpers.h>
#include <Fabric/Core/Build.h>
#include <Fabric/EDK/Common.h>
namespace Fabric
{
namespace Plug
{
//typedef void (*OnLoadFn)( SDK::Value FABRIC );
//typedef void (*OnUnloadFn)( SDK::Value FABRIC );
RC::Handle<Inst> Inst::Create(
RC::ConstHandle<IO::Dir> const &extensionDir,
std::string const &extensionName,
std::string const &jsonDesc,
std::vector<std::string> const &pluginDirs,
RC::Handle<CG::Manager> const &cgManager,
EDK::Callbacks const &callbacks,
std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
)
{
return new Inst( extensionDir, extensionName, jsonDesc, pluginDirs, cgManager, callbacks, implNameToDestructorMap );
}
Inst::Inst(
RC::ConstHandle<IO::Dir> const &extensionDir,
std::string const &extensionName,
std::string const &jsonDesc,
std::vector<std::string> const &pluginDirs,
RC::Handle<CG::Manager> const &cgManager,
EDK::Callbacks const &callbacks,
std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
)
: m_name( extensionName )
, m_jsonDesc( jsonDesc )
{
try
{
JSON::Decoder jsonDecode( jsonDesc.data(), jsonDesc.length() );
JSON::Entity jsonEntity;
if ( !jsonDecode.getNext( jsonEntity ) )
throw Exception( "missing JSON entity" );
jsonEntity.requireObject();
m_desc = parseDesc( jsonEntity );
if ( jsonDecode.getNext( jsonEntity ) )
throw Exception( "extra JSON entity" );
}
catch ( Exception e )
{
throw "JSON description: " + e;
}
/*
m_fabricLIBObject = LIB::NakedObject::Create();
m_fabricLIBObject->set( "hostTriple", LIB::ReferencedString::Create( Util::getHostTriple() ) );
m_fabricLIBObject->set( "DependencyGraph", LIBDG::Namespace::Create( dgContext ) );
*/
std::vector< std::string > libs;
m_desc.libs.appendMatching( Util::getHostTriple(), libs );
std::string libSuffix = "-" + std::string(buildOS) + "-" + std::string(buildArch);
for ( size_t i=0; i<libs.size(); ++i )
{
std::string resolvedName;
SOLibHandle soLibHandle = SOLibOpen( libs[i]+libSuffix, resolvedName, false, pluginDirs );
m_resolvedNameToSOLibHandleMap.insert( ResolvedNameToSOLibHandleMap::value_type( resolvedName, soLibHandle ) );
m_orderedSOLibHandles.push_back( soLibHandle );
}
void *resolvedFabricEDKInitFunction = 0;
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
resolvedFabricEDKInitFunction = SOLibResolve( m_orderedSOLibHandles[i], "FabricEDKInit" );
if ( resolvedFabricEDKInitFunction )
break;
}
if ( !resolvedFabricEDKInitFunction )
throw Exception( "error: extension doesn't implement function FabricEDKInit through macro IMPLEMENT_FABRIC_EDK_ENTRIES" );
( *( FabricEDKInitPtr )resolvedFabricEDKInitFunction )( callbacks );
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
/*
OnLoadFn onLoadFn = (OnLoadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnLoad" );
if ( onLoadFn )
onLoadFn( SDK::Value::Bind( m_fabricLIBObject ) );
*/
}
/*
for ( size_t i=0; i<m_desc.interface.methods.size(); ++i )
{
std::string const &methodName = m_desc.interface.methods[i];
Method method = 0;
for ( size_t j=0; j<m_orderedSOLibHandles.size(); ++j )
{
SOLibHandle soLibHandle = m_orderedSOLibHandles[j];
method = (Method)SOLibResolve( soLibHandle, methodName );
if ( method )
break;
}
if ( !method )
throw Exception( "method "+_(methodName)+" not found" );
m_methodMap.insert( MethodMap::value_type( methodName, method ) );
}
*/
std::vector<std::string> codeFiles;
m_desc.code.appendMatching( Util::getHostTriple(), codeFiles );
std::string filename;
m_code = "";
for ( std::vector<std::string>::const_iterator it=codeFiles.begin(); it!=codeFiles.end(); ++it )
{
std::string const &codeEntry = *it;
if ( filename.empty() )
filename = codeEntry;
std::string code;
try
{
code = extensionDir->getFileContents( codeEntry );
}
catch ( Exception e )
{
throw _(codeEntry) + ": " + e;
}
m_code += code + "\n";
}
RC::ConstHandle<KL::Source> source = KL::StringSource::Create( filename, m_code );
RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source );
m_ast = KL::Parse( scanner, m_diagnostics );
if ( !m_diagnostics.containsError() )
m_ast->registerTypes( cgManager, m_diagnostics );
for ( CG::Diagnostics::const_iterator it=m_diagnostics.begin(); it!=m_diagnostics.end(); ++it )
{
CG::Location const &location = it->first;
CG::Diagnostic const &diagnostic = it->second;
FABRIC_LOG( "[%s] %s:%u:%u: %s: %s", extensionName.c_str(), location.getFilename()->c_str(), (unsigned)location.getLine(), (unsigned)location.getColumn(), diagnostic.getLevelDesc(), diagnostic.getDesc().c_str() );
}
if ( m_diagnostics.containsError() )
throw Exception( "KL compile failed" );
std::vector< RC::ConstHandle<AST::FunctionBase> > functionBases;
m_ast->collectFunctionBases( functionBases );
for ( std::vector< RC::ConstHandle<AST::FunctionBase> >::const_iterator it=functionBases.begin(); it!=functionBases.end(); ++it )
{
RC::ConstHandle<AST::FunctionBase> const &functionBase = *it;
if ( !functionBase->getBody() )
{
std::string symbolName = functionBase->getSymbolName( cgManager );
void *resolvedFunction = 0;
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
resolvedFunction = SOLibResolve( m_orderedSOLibHandles[i], symbolName );
if ( resolvedFunction )
break;
}
if ( !resolvedFunction )
throw Exception( "error: symbol " + _(symbolName) + ", prototyped in KL, not found in native code" );
m_externalFunctionMap.insert( ExternalFunctionMap::value_type( symbolName, resolvedFunction ) );
if ( functionBase->isDestructor() )
{
RC::ConstHandle<AST::Destructor> destructor = RC::ConstHandle<AST::Destructor>::StaticCast( functionBase );
std::string thisTypeName = destructor->getThisTypeName();
implNameToDestructorMap[thisTypeName] = (void (*)( void * )) resolvedFunction;
}
}
}
m_jsConstants = m_desc.jsConstants.concatMatching( Util::getHostTriple() );
}
Inst::~Inst()
{
for ( size_t i=m_orderedSOLibHandles.size(); i--; )
{
/*
OnUnloadFn onUnloadFn = (OnUnloadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnUnload" );
if ( onUnloadFn )
onUnloadFn( SDK::Value::Bind( m_fabricLIBObject ) );
*/
}
for ( ResolvedNameToSOLibHandleMap::const_iterator it=m_resolvedNameToSOLibHandleMap.begin(); it !=m_resolvedNameToSOLibHandleMap.end(); ++it )
{
SOLibClose( it->second, it->first );
}
}
void *Inst::llvmResolveExternalFunction( std::string const &name ) const
{
void *result = 0;
ExternalFunctionMap::const_iterator it = m_externalFunctionMap.find( name );
if ( it != m_externalFunctionMap.end() )
result = it->second;
return result;
}
bool Inst::hasMethod( std::string const &methodName ) const
{
/*
MethodMap::const_iterator it = m_methodMap.find( methodName );
return it != m_methodMap.end();
*/
return false;
}
void Inst::enumerateMethods( std::vector<std::string> &result ) const
{
/*
for ( MethodMap::const_iterator it=m_methodMap.begin(); it!=m_methodMap.end(); ++it )
result.push_back( it->first );
*/
}
/*
RC::Handle<LIB::Value> Inst::invokeMethod( std::string const &methodName, std::vector< RC::Handle<LIB::Value> > const &args )
{
MethodMap::const_iterator it = m_methodMap.find( methodName );
FABRIC_ASSERT( it != m_methodMap.end() );
return SDK::Value::Unbind( it->second( SDK::Value::Bind( m_fabricLIBObject ), SDK::Value::LIBArgsToSDKArgs( args ) ) );
}
*/
void Inst::jsonDesc( JSON::Encoder &resultEncoder ) const
{
JSON::ObjectEncoder resultObjectEncoder = resultEncoder.makeObject();
{
JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "code", 4 );
memberEncoder.makeString( m_code );
}
{
JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "jsConstants", 11 );
memberEncoder.makeString( m_jsConstants );
}
}
RC::ConstHandle<AST::GlobalList> Inst::getAST() const
{
return m_ast;
}
};
};
<commit_msg>Add support for KL-only extensions<commit_after>/*
* Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
*/
#include "Inst.h"
#include <Fabric/Core/KL/StringSource.h>
#include <Fabric/Core/KL/Scanner.h>
#include <Fabric/Core/KL/Parser.hpp>
#include <Fabric/Core/AST/Function.h>
#include <Fabric/Core/AST/GlobalList.h>
#include <Fabric/Core/CG/Manager.h>
#include <Fabric/Core/CG/ModuleBuilder.h>
#include <Fabric/Core/RT/Impl.h>
#include <Fabric/Core/DG/Context.h>
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Core/IO/Dir.h>
#include <Fabric/Core/Plug/Helpers.h>
#include <Fabric/Core/Build.h>
#include <Fabric/EDK/Common.h>
namespace Fabric
{
namespace Plug
{
//typedef void (*OnLoadFn)( SDK::Value FABRIC );
//typedef void (*OnUnloadFn)( SDK::Value FABRIC );
RC::Handle<Inst> Inst::Create(
RC::ConstHandle<IO::Dir> const &extensionDir,
std::string const &extensionName,
std::string const &jsonDesc,
std::vector<std::string> const &pluginDirs,
RC::Handle<CG::Manager> const &cgManager,
EDK::Callbacks const &callbacks,
std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
)
{
return new Inst( extensionDir, extensionName, jsonDesc, pluginDirs, cgManager, callbacks, implNameToDestructorMap );
}
Inst::Inst(
RC::ConstHandle<IO::Dir> const &extensionDir,
std::string const &extensionName,
std::string const &jsonDesc,
std::vector<std::string> const &pluginDirs,
RC::Handle<CG::Manager> const &cgManager,
EDK::Callbacks const &callbacks,
std::map< std::string, void (*)( void * ) > &implNameToDestructorMap
)
: m_name( extensionName )
, m_jsonDesc( jsonDesc )
{
try
{
JSON::Decoder jsonDecode( jsonDesc.data(), jsonDesc.length() );
JSON::Entity jsonEntity;
if ( !jsonDecode.getNext( jsonEntity ) )
throw Exception( "missing JSON entity" );
jsonEntity.requireObject();
m_desc = parseDesc( jsonEntity );
if ( jsonDecode.getNext( jsonEntity ) )
throw Exception( "extra JSON entity" );
}
catch ( Exception e )
{
throw "JSON description: " + e;
}
/*
m_fabricLIBObject = LIB::NakedObject::Create();
m_fabricLIBObject->set( "hostTriple", LIB::ReferencedString::Create( Util::getHostTriple() ) );
m_fabricLIBObject->set( "DependencyGraph", LIBDG::Namespace::Create( dgContext ) );
*/
std::vector< std::string > libs;
m_desc.libs.appendMatching( Util::getHostTriple(), libs );
std::string libSuffix = "-" + std::string(buildOS) + "-" + std::string(buildArch);
for ( size_t i=0; i<libs.size(); ++i )
{
std::string resolvedName;
SOLibHandle soLibHandle = SOLibOpen( libs[i]+libSuffix, resolvedName, false, pluginDirs );
m_resolvedNameToSOLibHandleMap.insert( ResolvedNameToSOLibHandleMap::value_type( resolvedName, soLibHandle ) );
m_orderedSOLibHandles.push_back( soLibHandle );
}
if ( !m_orderedSOLibHandles.empty() )
{
void *resolvedFabricEDKInitFunction = 0;
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
resolvedFabricEDKInitFunction = SOLibResolve( m_orderedSOLibHandles[i], "FabricEDKInit" );
if ( resolvedFabricEDKInitFunction )
break;
}
if ( !resolvedFabricEDKInitFunction )
throw Exception( "error: extension doesn't implement function FabricEDKInit through macro IMPLEMENT_FABRIC_EDK_ENTRIES" );
( *( FabricEDKInitPtr )resolvedFabricEDKInitFunction )( callbacks );
}
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
/*
OnLoadFn onLoadFn = (OnLoadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnLoad" );
if ( onLoadFn )
onLoadFn( SDK::Value::Bind( m_fabricLIBObject ) );
*/
}
/*
for ( size_t i=0; i<m_desc.interface.methods.size(); ++i )
{
std::string const &methodName = m_desc.interface.methods[i];
Method method = 0;
for ( size_t j=0; j<m_orderedSOLibHandles.size(); ++j )
{
SOLibHandle soLibHandle = m_orderedSOLibHandles[j];
method = (Method)SOLibResolve( soLibHandle, methodName );
if ( method )
break;
}
if ( !method )
throw Exception( "method "+_(methodName)+" not found" );
m_methodMap.insert( MethodMap::value_type( methodName, method ) );
}
*/
std::vector<std::string> codeFiles;
m_desc.code.appendMatching( Util::getHostTriple(), codeFiles );
std::string filename;
m_code = "";
for ( std::vector<std::string>::const_iterator it=codeFiles.begin(); it!=codeFiles.end(); ++it )
{
std::string const &codeEntry = *it;
if ( filename.empty() )
filename = codeEntry;
std::string code;
try
{
code = extensionDir->getFileContents( codeEntry );
}
catch ( Exception e )
{
throw _(codeEntry) + ": " + e;
}
m_code += code + "\n";
}
RC::ConstHandle<KL::Source> source = KL::StringSource::Create( filename, m_code );
RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source );
m_ast = KL::Parse( scanner, m_diagnostics );
if ( !m_diagnostics.containsError() )
m_ast->registerTypes( cgManager, m_diagnostics );
for ( CG::Diagnostics::const_iterator it=m_diagnostics.begin(); it!=m_diagnostics.end(); ++it )
{
CG::Location const &location = it->first;
CG::Diagnostic const &diagnostic = it->second;
FABRIC_LOG( "[%s] %s:%u:%u: %s: %s", extensionName.c_str(), location.getFilename()->c_str(), (unsigned)location.getLine(), (unsigned)location.getColumn(), diagnostic.getLevelDesc(), diagnostic.getDesc().c_str() );
}
if ( m_diagnostics.containsError() )
throw Exception( "KL compile failed" );
std::vector< RC::ConstHandle<AST::FunctionBase> > functionBases;
m_ast->collectFunctionBases( functionBases );
for ( std::vector< RC::ConstHandle<AST::FunctionBase> >::const_iterator it=functionBases.begin(); it!=functionBases.end(); ++it )
{
RC::ConstHandle<AST::FunctionBase> const &functionBase = *it;
if ( !functionBase->getBody() )
{
std::string symbolName = functionBase->getSymbolName( cgManager );
void *resolvedFunction = 0;
for ( size_t i=0; i<m_orderedSOLibHandles.size(); ++i )
{
resolvedFunction = SOLibResolve( m_orderedSOLibHandles[i], symbolName );
if ( resolvedFunction )
break;
}
if ( !resolvedFunction )
throw Exception( "error: symbol " + _(symbolName) + ", prototyped in KL, not found in native code" );
m_externalFunctionMap.insert( ExternalFunctionMap::value_type( symbolName, resolvedFunction ) );
if ( functionBase->isDestructor() )
{
RC::ConstHandle<AST::Destructor> destructor = RC::ConstHandle<AST::Destructor>::StaticCast( functionBase );
std::string thisTypeName = destructor->getThisTypeName();
implNameToDestructorMap[thisTypeName] = (void (*)( void * )) resolvedFunction;
}
}
}
m_jsConstants = m_desc.jsConstants.concatMatching( Util::getHostTriple() );
}
Inst::~Inst()
{
for ( size_t i=m_orderedSOLibHandles.size(); i--; )
{
/*
OnUnloadFn onUnloadFn = (OnUnloadFn)SOLibResolve( m_orderedSOLibHandles[i], "FabricOnUnload" );
if ( onUnloadFn )
onUnloadFn( SDK::Value::Bind( m_fabricLIBObject ) );
*/
}
for ( ResolvedNameToSOLibHandleMap::const_iterator it=m_resolvedNameToSOLibHandleMap.begin(); it !=m_resolvedNameToSOLibHandleMap.end(); ++it )
{
SOLibClose( it->second, it->first );
}
}
void *Inst::llvmResolveExternalFunction( std::string const &name ) const
{
void *result = 0;
ExternalFunctionMap::const_iterator it = m_externalFunctionMap.find( name );
if ( it != m_externalFunctionMap.end() )
result = it->second;
return result;
}
bool Inst::hasMethod( std::string const &methodName ) const
{
/*
MethodMap::const_iterator it = m_methodMap.find( methodName );
return it != m_methodMap.end();
*/
return false;
}
void Inst::enumerateMethods( std::vector<std::string> &result ) const
{
/*
for ( MethodMap::const_iterator it=m_methodMap.begin(); it!=m_methodMap.end(); ++it )
result.push_back( it->first );
*/
}
/*
RC::Handle<LIB::Value> Inst::invokeMethod( std::string const &methodName, std::vector< RC::Handle<LIB::Value> > const &args )
{
MethodMap::const_iterator it = m_methodMap.find( methodName );
FABRIC_ASSERT( it != m_methodMap.end() );
return SDK::Value::Unbind( it->second( SDK::Value::Bind( m_fabricLIBObject ), SDK::Value::LIBArgsToSDKArgs( args ) ) );
}
*/
void Inst::jsonDesc( JSON::Encoder &resultEncoder ) const
{
JSON::ObjectEncoder resultObjectEncoder = resultEncoder.makeObject();
{
JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "code", 4 );
memberEncoder.makeString( m_code );
}
{
JSON::Encoder memberEncoder = resultObjectEncoder.makeMember( "jsConstants", 11 );
memberEncoder.makeString( m_jsConstants );
}
}
RC::ConstHandle<AST::GlobalList> Inst::getAST() const
{
return m_ast;
}
};
};
<|endoftext|> |
<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);
AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF
AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
// Creates a jet finder task, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskJets", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskJets", "This task requires an input event handler");
return NULL;
}
// Create the task and configure it.
//===========================================================================
AliAnalysisTaskJets *jetana;
AliJetReader *er = CreateJetReader(jr);
// Define jet header and jet finder
AliJetFinder *jetFinder = CreateJetFinder(jf,radius);
if (jetFinder){
if (er) jetFinder->SetJetReader(er);
}
char *cRadius = "";
if(radius>0)cRadius = Form("%02d",(int)(radius*10));
jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius));
AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(),
AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius));
// Connect jet finder to task.
jetana->SetJetFinder(jetFinder);
jetana->SetConfigFile("");
jetana->SetDebugLevel(10);
mgr->AddTask(jetana);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput (jetana, 1, cout_jet);
return jetana;
}
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){
switch (jf) {
case "CDF":
AliCdfJetHeader *jh = new AliCdfJetHeader();
jh->SetRadius(0.7);
jetFinder = new AliCdfJetFinder();
jetFinder->SetOutputFile("jets.root");
if (jh) jetFinder->SetJetHeader(jh);
break;
case "DA":
AliDAJetHeader *jh=new AliDAJetHeader();
jh->SetComment("DA jet code with default parameters");
jh->SelectJets(kTRUE);
jh->SetNclust(10);
jetFinder = new AliDAJetFinder();
if (jh) jetFinder->SetJetHeader(jh);
break;
case "Fastjet":
AliFastJetHeader *jh = new AliFastJetHeader();
jh->SetRparam(0.7); // setup parameters
jetFinder = new AliFastJetFinder();
jetFinder->SetOutputFile("jets.root");
if (jh) jetFinder->SetJetHeader(jh);
break;
case "UA1":
AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
jh->SetComment("UA1 jet code with default parameters");
jh->BackgMode(0);
jh->SetRadius(0.4);
if(radius>0)jh->SetRadius(radius);
jh->SetEtSeed(4.);
jh->SetLegoNbinPhi(432);
jh->SetLegoNbinEta(274);
jh->SetLegoEtaMin(-2);
jh->SetLegoEtaMax(+2);
jh->SetMinJetEt(10.);
jh->SetJetEtaMax(1.5);
jh->SetJetEtaMin(-1.5);
jetFinder = new AliUA1JetFinderV1();
if (jh) jetFinder->SetJetHeader(jh);
break;
case "UA1MC":
AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
jh->SetComment("UA1 jet code with default MC parameters");
jh->BackgMode(0);
jh->SetRadius(1.0);
if(radius>0)jh->SetRadius(radius);
jh->SetEtSeed(4.);
jh->SetLegoNbinPhi(432);
jh->SetLegoNbinEta(274);
jh->SetLegoEtaMin(-2);
jh->SetLegoEtaMax(+2);
jh->SetMinJetEt(10.);
jh->SetJetEtaMax(1.5);
jh->SetJetEtaMin(-1.5);
jetFinder = new AliUA1JetFinderV1();
if (jh) jetFinder->SetJetHeader(jh);
break;
case default:
::Error("AddTaskJets", "Wrong jet finder selected\n");
return 0;
}
return jetFinder;
}
AliJetReader *CreateJetReader(Char_t *jr){
AliJetReader *er = 0;
switch (jr) {
case "MC":
AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
jrh->SetComment("MC full Kinematics");
jrh->SetFastSimTPC(kFALSE);
jrh->SetFastSimEMCAL(kFALSE);
jrh->SetPtCut(0.);
jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
// Define reader and set its header
er = new AliJetKineReader();
er->SetReaderHeader(jrh);
break;
case "MC2":
AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
jrh->SetComment("MC full Kinematics spearate config");
jrh->SetFastSimTPC(kFALSE);
jrh->SetFastSimEMCAL(kFALSE);
jrh->SetPtCut(0.);
jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
// Define reader and set its header
er = new AliJetKineReader();
er->SetReaderHeader(jrh);
break;
case "ESD":
AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
jrh->SetComment("Testing");
jrh->SetFirstEvent(0);
jrh->SetLastEvent(1000);
jrh->SetPtCut(0.);
jrh->SetReadSignalOnly(kFALSE);
// Define reader and set its header
er = new AliJetESDReader();
er->SetReaderHeader(jrh);
break;
case "AOD":
AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
jrh->SetComment("AOD Reader");
jrh->SetPtCut(0.);
jrh->SetTestFilterMask(1<<0);
// Define reader and set its header
er = new AliJetAODReader();
er->SetReaderHeader(jrh);
break;
default:
::Error("AddTaskJets", "Wrong jet reader selected\n");
return 0;
}
return er;
}
<commit_msg>Create non standard branch in case AODs are read as input. (M. Gheata)<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);
AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF
AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
// Creates a jet finder task, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskJets", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskJets", "This task requires an input event handler");
return NULL;
}
// Create the task and configure it.
//===========================================================================
AliAnalysisTaskJets *jetana;
AliJetReader *er = CreateJetReader(jr);
// Define jet header and jet finder
AliJetFinder *jetFinder = CreateJetFinder(jf,radius);
if (jetFinder){
if (er) jetFinder->SetJetReader(er);
}
char *cRadius = "";
if(radius>0)cRadius = Form("%02d",(int)(radius*10));
jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius));
TString type = mgr->GetInputEventHandler()->GetDataType();
if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf));
AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(),
AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius));
// Connect jet finder to task.
jetana->SetJetFinder(jetFinder);
jetana->SetConfigFile("");
jetana->SetDebugLevel(10);
mgr->AddTask(jetana);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput (jetana, 1, cout_jet);
return jetana;
}
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){
switch (jf) {
case "CDF":
AliCdfJetHeader *jh = new AliCdfJetHeader();
jh->SetRadius(0.7);
jetFinder = new AliCdfJetFinder();
jetFinder->SetOutputFile("jets.root");
if (jh) jetFinder->SetJetHeader(jh);
break;
case "DA":
AliDAJetHeader *jh=new AliDAJetHeader();
jh->SetComment("DA jet code with default parameters");
jh->SelectJets(kTRUE);
jh->SetNclust(10);
jetFinder = new AliDAJetFinder();
if (jh) jetFinder->SetJetHeader(jh);
break;
case "Fastjet":
AliFastJetHeader *jh = new AliFastJetHeader();
jh->SetRparam(0.7); // setup parameters
jetFinder = new AliFastJetFinder();
jetFinder->SetOutputFile("jets.root");
if (jh) jetFinder->SetJetHeader(jh);
break;
case "UA1":
AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
jh->SetComment("UA1 jet code with default parameters");
jh->BackgMode(0);
jh->SetRadius(0.4);
if(radius>0)jh->SetRadius(radius);
jh->SetEtSeed(4.);
jh->SetLegoNbinPhi(432);
jh->SetLegoNbinEta(274);
jh->SetLegoEtaMin(-2);
jh->SetLegoEtaMax(+2);
jh->SetMinJetEt(10.);
jh->SetJetEtaMax(1.5);
jh->SetJetEtaMin(-1.5);
jetFinder = new AliUA1JetFinderV1();
if (jh) jetFinder->SetJetHeader(jh);
break;
case "UA1MC":
AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
jh->SetComment("UA1 jet code with default MC parameters");
jh->BackgMode(0);
jh->SetRadius(1.0);
if(radius>0)jh->SetRadius(radius);
jh->SetEtSeed(4.);
jh->SetLegoNbinPhi(432);
jh->SetLegoNbinEta(274);
jh->SetLegoEtaMin(-2);
jh->SetLegoEtaMax(+2);
jh->SetMinJetEt(10.);
jh->SetJetEtaMax(1.5);
jh->SetJetEtaMin(-1.5);
jetFinder = new AliUA1JetFinderV1();
if (jh) jetFinder->SetJetHeader(jh);
break;
case default:
::Error("AddTaskJets", "Wrong jet finder selected\n");
return 0;
}
return jetFinder;
}
AliJetReader *CreateJetReader(Char_t *jr){
AliJetReader *er = 0;
switch (jr) {
case "MC":
AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
jrh->SetComment("MC full Kinematics");
jrh->SetFastSimTPC(kFALSE);
jrh->SetFastSimEMCAL(kFALSE);
jrh->SetPtCut(0.);
jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
// Define reader and set its header
er = new AliJetKineReader();
er->SetReaderHeader(jrh);
break;
case "MC2":
AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
jrh->SetComment("MC full Kinematics spearate config");
jrh->SetFastSimTPC(kFALSE);
jrh->SetFastSimEMCAL(kFALSE);
jrh->SetPtCut(0.);
jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
// Define reader and set its header
er = new AliJetKineReader();
er->SetReaderHeader(jrh);
break;
case "ESD":
AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
jrh->SetComment("Testing");
jrh->SetFirstEvent(0);
jrh->SetLastEvent(1000);
jrh->SetPtCut(0.);
jrh->SetReadSignalOnly(kFALSE);
// Define reader and set its header
er = new AliJetESDReader();
er->SetReaderHeader(jrh);
break;
case "AOD":
AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
jrh->SetComment("AOD Reader");
jrh->SetPtCut(0.);
jrh->SetTestFilterMask(1<<0);
// Define reader and set its header
er = new AliJetAODReader();
er->SetReaderHeader(jrh);
break;
default:
::Error("AddTaskJets", "Wrong jet reader selected\n");
return 0;
}
return er;
}
<|endoftext|> |
<commit_before>#include <map>
#include <sstream>
#include "GtpLayer.h"
#include "IPv4Layer.h"
#include "IPv6Layer.h"
#include "PayloadLayer.h"
#include "EndianPortable.h"
namespace pcpp
{
#define PCPP_GTP_V1_GPDU_MESSAGE_TYPE 0xff
/// ==================
/// GtpExtension class
/// ==================
GtpV1Layer::GtpExtension::GtpExtension()
{
m_Data = NULL;
m_DataLen = 0;
m_ExtType = 0;
}
GtpV1Layer::GtpExtension::GtpExtension(uint8_t* data, size_t dataLen, uint8_t type)
{
m_Data = data;
m_DataLen = dataLen;
m_ExtType = type;
}
GtpV1Layer::GtpExtension::GtpExtension(const GtpExtension& other)
{
m_Data = other.m_Data;
m_DataLen = other.m_DataLen;
m_ExtType = other.m_ExtType;
}
GtpV1Layer::GtpExtension& GtpV1Layer::GtpExtension::operator=(const GtpV1Layer::GtpExtension& other)
{
m_Data = other.m_Data;
m_DataLen = other.m_DataLen;
m_ExtType = other.m_ExtType;
return *this;
}
bool GtpV1Layer::GtpExtension::isNull()
{
return m_Data == NULL;
}
uint8_t GtpV1Layer::GtpExtension::getExtensionType()
{
return m_ExtType;
}
size_t GtpV1Layer::GtpExtension::getTotalLength()
{
if (m_Data == NULL)
{
return 0;
}
size_t len = (size_t)(m_Data[0]*4);
if (len <= m_DataLen)
{
return len;
}
return m_DataLen;
}
size_t GtpV1Layer::GtpExtension::getContentLength()
{
size_t res = getTotalLength();
if (res >= 2*sizeof(uint8_t))
{
return (size_t)(res - 2*sizeof(uint8_t));
}
return 0;
}
uint8_t* GtpV1Layer::GtpExtension::getContent()
{
if (m_Data == NULL || getContentLength() == 0)
{
return NULL;
}
return m_Data + sizeof(uint8_t);
}
uint8_t GtpV1Layer::GtpExtension::getNextExtensionHeaderType()
{
if (m_Data == NULL || getTotalLength() < 4)
{
return 0;
}
uint8_t res = *(uint8_t*)(m_Data + sizeof(uint8_t) + getContentLength());
return res;
}
GtpV1Layer::GtpExtension GtpV1Layer::GtpExtension::getNextExtension()
{
size_t totalLength = getTotalLength();
uint8_t nextExtType = getNextExtensionHeaderType();
if (nextExtType > 0 && m_DataLen > totalLength + sizeof(uint8_t))
{
return GtpV1Layer::GtpExtension(m_Data + totalLength, m_DataLen - totalLength, nextExtType);
}
else
{
return GtpV1Layer::GtpExtension();
}
}
/// ================
/// GtpV1Layer class
/// ================
bool GtpV1Layer::isGTPv1(const uint8_t* data, size_t dataSize)
{
if (data != NULL && dataSize > 1 && (data[0] & 0xE0) == 0x20)
{
return true;
}
return false;
}
GtpV1Layer::gtpv1_header_extra* GtpV1Layer::getHeaderExtra()
{
if (m_Data != NULL && m_DataLen >= sizeof(gtpv1_header) + sizeof(gtpv1_header_extra))
{
return (gtpv1_header_extra*)(m_Data + sizeof(gtpv1_header));
}
return NULL;
}
bool GtpV1Layer::getSequenceNumber(uint16_t& seqNumber)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->sequenceNumberFlag == 1)
{
seqNumber = ntohs(headerExtra->sequenceNumber);
return true;
}
return false;
}
bool GtpV1Layer::getNpduNumber(uint8_t& npduNum)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->npduNumberFlag == 1)
{
npduNum = headerExtra->npduNumber;
return true;
}
return false;
}
bool GtpV1Layer::getNextExtensionHeaderType(uint8_t& nextExtType)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->extensionHeaderFlag == 1)
{
nextExtType = headerExtra->nextExtensionHeader;
return true;
}
return false;
}
GtpV1Layer::GtpExtension GtpV1Layer::getNextExtension()
{
uint8_t nextExtType = 0;
bool nextExtExists = getNextExtensionHeaderType(nextExtType);
if (!nextExtExists || nextExtType == 0 || m_DataLen < sizeof(gtpv1_header) + sizeof(uint8_t))
{
return GtpV1Layer::GtpExtension();
}
return GtpV1Layer::GtpExtension(m_Data + sizeof(gtpv1_header) + sizeof(gtpv1_header_extra), m_DataLen - sizeof(gtpv1_header) - sizeof(gtpv1_header_extra), nextExtType);
}
GtpV1MessageType GtpV1Layer::getMessageType()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return GtpV1_MessageTypeUnknown;
}
return (GtpV1MessageType)header->messageType;
}
std::map<uint8_t, std::string> createGtpV1MessageTypeToStringMap()
{
std::map<uint8_t, std::string> tempMap;
tempMap[0] = "GTPv1 Message Type Unknown";
tempMap[1] = "Echo Request";
tempMap[2] = "Echo Response";
tempMap[3] = "Version Not Supported";
tempMap[4] = "Node Alive Request";
tempMap[5] = "Node Alive Response";
tempMap[6] = "Redirection Request";
tempMap[7] = "Create PDP Context Request";
tempMap[16] = "Create PDP Context Response";
tempMap[17] = "Update PDP Context Request";
tempMap[18] = "Update PDP Context Response";
tempMap[19] = "Delete PDP Context Request";
tempMap[20] = "Delete PDP Context Response";
tempMap[22] = "Initiate PDP Context Activation Request";
tempMap[23] = "Initiate PDP Context Activation Response";
tempMap[26] = "Error Indication";
tempMap[27] = "PDU Notification Request";
tempMap[28] = "PDU Notification Response";
tempMap[29] = "PDU Notification Reject Request";
tempMap[30] = "PDU Notification Reject Response";
tempMap[31] = "Supported Extensions Header Notification";
tempMap[32] = "Send Routing for GPRS Request";
tempMap[33] = "Send Routing for GPRS Response";
tempMap[34] = "Failure Report Request";
tempMap[35] = "Failure Report Response";
tempMap[36] = "Note MS Present Request";
tempMap[37] = "Note MS Present Response";
tempMap[38] = "Identification Request";
tempMap[39] = "Identification Response";
tempMap[50] = "SGSN Context Request";
tempMap[51] = "SGSN Context Response";
tempMap[52] = "SGSN Context Acknowledge";
tempMap[53] = "Forward Relocation Request";
tempMap[54] = "Forward Relocation Response";
tempMap[55] = "Forward Relocation Complete";
tempMap[56] = "Relocation Cancel Request";
tempMap[57] = "Relocation Cancel Response";
tempMap[58] = "Forward SRNS Context";
tempMap[59] = "Forward Relocation Complete Acknowledge";
tempMap[60] = "Forward SRNS Context Acknowledge";
tempMap[61] = "UE Registration Request";
tempMap[62] = "UE Registration Response";
tempMap[70] = "RAN Information Relay";
tempMap[96] = "MBMS Notification Request";
tempMap[97] = "MBMS Notification Response";
tempMap[98] = "MBMS Notification Reject Request";
tempMap[99] = "MBMS Notification Reject Response";
tempMap[100] = "Create MBMS Notification Request";
tempMap[101] = "Create MBMS Notification Response";
tempMap[102] = "Update MBMS Notification Request";
tempMap[103] = "Update MBMS Notification Response";
tempMap[104] = "Delete MBMS Notification Request";
tempMap[105] = "Delete MBMS Notification Response";
tempMap[112] = "MBMS Registration Request";
tempMap[113] = "MBMS Registration Response";
tempMap[114] = "MBMS De-Registration Request";
tempMap[115] = "MBMS De-Registration Response";
tempMap[116] = "MBMS Session Start Request";
tempMap[117] = "MBMS Session Start Response";
tempMap[118] = "MBMS Session Stop Request";
tempMap[119] = "MBMS Session Stop Response";
tempMap[120] = "MBMS Session Update Request";
tempMap[121] = "MBMS Session Update Response";
tempMap[128] = "MS Info Change Request";
tempMap[129] = "MS Info Change Response";
tempMap[240] = "Data Record Transfer Request";
tempMap[241] = "Data Record Transfer Response";
tempMap[254] = "End Marker";
tempMap[255] = "G-PDU";
return tempMap;
}
const std::map<uint8_t, std::string> GTPv1MsgTypeToStringMap = createGtpV1MessageTypeToStringMap();
std::string GtpV1Layer::getMessageTypeAsString()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return GTPv1MsgTypeToStringMap.find(0)->second;
}
std::map<uint8_t, std::string>::const_iterator iter = GTPv1MsgTypeToStringMap.find(header->messageType);
if (iter != GTPv1MsgTypeToStringMap.end())
{
return iter->second;
}
else
{
return GTPv1MsgTypeToStringMap.find(0)->second;
}
}
bool GtpV1Layer::isGTPUMessage()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return false;
}
return header->messageType == PCPP_GTP_V1_GPDU_MESSAGE_TYPE;
}
bool GtpV1Layer::isGTPCMessage()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return false;
}
return header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE;
}
void GtpV1Layer::parseNextLayer()
{
size_t headerLen = getHeaderLen();
if (headerLen < sizeof(gtpv1_header))
{
// do nothing
return;
}
gtpv1_header* header = getHeader();
if (header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
// this is a GTP-C message, hence it is the last layer
return;
}
if (m_DataLen <= headerLen)
{
// no data beyond headerLen, nothing to parse further
return;
}
// GTP-U message, try to parse the next layer
uint8_t subProto = *(uint8_t*)(m_Data + headerLen);
if (subProto >= 0x45 && subProto <= 0x4e)
{
m_NextLayer = new IPv4Layer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
else if ((subProto & 0xf0) == 0x60)
{
m_NextLayer = new IPv6Layer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
else
{
m_NextLayer = new PayloadLayer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
}
size_t GtpV1Layer::getHeaderLen()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return 0;
}
size_t res = sizeof(gtpv1_header);
if (header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
size_t msgLen = ntohs(header->messageLength);
res += (msgLen > m_DataLen - sizeof(gtpv1_header) ? m_DataLen - sizeof(gtpv1_header) : msgLen);
}
else
{
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (headerExtra != NULL && (header->extensionHeaderFlag == 1 || header->sequenceNumberFlag == 1 || header->npduNumberFlag == 1))
{
res += sizeof(gtpv1_header_extra);
GtpExtension nextExt = getNextExtension();
while (!nextExt.isNull())
{
res += nextExt.getTotalLength();
nextExt = nextExt.getNextExtension();
}
}
}
return res;
}
std::string GtpV1Layer::toString()
{
std::string res = "GTP v1 Layer";
gtpv1_header* header = getHeader();
if (header != NULL)
{
std::stringstream teidStream;
teidStream << ntohl(header->teid);
std::string gtpu_gtpc;
if (header->messageType == PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
gtpu_gtpc = "GTP-U message";
}
else
{
gtpu_gtpc = "GTP-C message: " + getMessageTypeAsString();
}
res += ", " + gtpu_gtpc + ", TEID: " + teidStream.str();
}
return res;
}
}<commit_msg>Small fix<commit_after>#include <map>
#include <sstream>
#include "GtpLayer.h"
#include "IPv4Layer.h"
#include "IPv6Layer.h"
#include "PayloadLayer.h"
#include "EndianPortable.h"
namespace pcpp
{
#define PCPP_GTP_V1_GPDU_MESSAGE_TYPE 0xff
/// ==================
/// GtpExtension class
/// ==================
GtpV1Layer::GtpExtension::GtpExtension()
{
m_Data = NULL;
m_DataLen = 0;
m_ExtType = 0;
}
GtpV1Layer::GtpExtension::GtpExtension(uint8_t* data, size_t dataLen, uint8_t type)
{
m_Data = data;
m_DataLen = dataLen;
m_ExtType = type;
}
GtpV1Layer::GtpExtension::GtpExtension(const GtpExtension& other)
{
m_Data = other.m_Data;
m_DataLen = other.m_DataLen;
m_ExtType = other.m_ExtType;
}
GtpV1Layer::GtpExtension& GtpV1Layer::GtpExtension::operator=(const GtpV1Layer::GtpExtension& other)
{
m_Data = other.m_Data;
m_DataLen = other.m_DataLen;
m_ExtType = other.m_ExtType;
return *this;
}
bool GtpV1Layer::GtpExtension::isNull()
{
return m_Data == NULL;
}
uint8_t GtpV1Layer::GtpExtension::getExtensionType()
{
return m_ExtType;
}
size_t GtpV1Layer::GtpExtension::getTotalLength()
{
if (m_Data == NULL)
{
return 0;
}
size_t len = (size_t)(m_Data[0]*4);
if (len <= m_DataLen)
{
return len;
}
return m_DataLen;
}
size_t GtpV1Layer::GtpExtension::getContentLength()
{
size_t res = getTotalLength();
if (res >= 2*sizeof(uint8_t))
{
return (size_t)(res - 2*sizeof(uint8_t));
}
return 0;
}
uint8_t* GtpV1Layer::GtpExtension::getContent()
{
if (m_Data == NULL || getContentLength() == 0)
{
return NULL;
}
return m_Data + sizeof(uint8_t);
}
uint8_t GtpV1Layer::GtpExtension::getNextExtensionHeaderType()
{
if (m_Data == NULL || getTotalLength() < 4)
{
return 0;
}
uint8_t res = *(uint8_t*)(m_Data + sizeof(uint8_t) + getContentLength());
return res;
}
GtpV1Layer::GtpExtension GtpV1Layer::GtpExtension::getNextExtension()
{
size_t totalLength = getTotalLength();
uint8_t nextExtType = getNextExtensionHeaderType();
if (nextExtType > 0 && m_DataLen > totalLength + sizeof(uint8_t))
{
return GtpV1Layer::GtpExtension(m_Data + totalLength, m_DataLen - totalLength, nextExtType);
}
else
{
return GtpV1Layer::GtpExtension();
}
}
/// ================
/// GtpV1Layer class
/// ================
bool GtpV1Layer::isGTPv1(const uint8_t* data, size_t dataSize)
{
if (data != NULL && dataSize > 1 && (data[0] & 0xE0) == 0x20)
{
return true;
}
return false;
}
GtpV1Layer::gtpv1_header_extra* GtpV1Layer::getHeaderExtra()
{
if (m_Data != NULL && m_DataLen >= sizeof(gtpv1_header) + sizeof(gtpv1_header_extra))
{
return (gtpv1_header_extra*)(m_Data + sizeof(gtpv1_header));
}
return NULL;
}
bool GtpV1Layer::getSequenceNumber(uint16_t& seqNumber)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->sequenceNumberFlag == 1)
{
seqNumber = be16toh(headerExtra->sequenceNumber);
return true;
}
return false;
}
bool GtpV1Layer::getNpduNumber(uint8_t& npduNum)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->npduNumberFlag == 1)
{
npduNum = headerExtra->npduNumber;
return true;
}
return false;
}
bool GtpV1Layer::getNextExtensionHeaderType(uint8_t& nextExtType)
{
gtpv1_header* header = getHeader();
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (header != NULL && headerExtra != NULL && header->extensionHeaderFlag == 1)
{
nextExtType = headerExtra->nextExtensionHeader;
return true;
}
return false;
}
GtpV1Layer::GtpExtension GtpV1Layer::getNextExtension()
{
uint8_t nextExtType = 0;
bool nextExtExists = getNextExtensionHeaderType(nextExtType);
if (!nextExtExists || nextExtType == 0 || m_DataLen < sizeof(gtpv1_header) + sizeof(uint8_t))
{
return GtpV1Layer::GtpExtension();
}
return GtpV1Layer::GtpExtension(m_Data + sizeof(gtpv1_header) + sizeof(gtpv1_header_extra), m_DataLen - sizeof(gtpv1_header) - sizeof(gtpv1_header_extra), nextExtType);
}
GtpV1MessageType GtpV1Layer::getMessageType()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return GtpV1_MessageTypeUnknown;
}
return (GtpV1MessageType)header->messageType;
}
std::map<uint8_t, std::string> createGtpV1MessageTypeToStringMap()
{
std::map<uint8_t, std::string> tempMap;
tempMap[0] = "GTPv1 Message Type Unknown";
tempMap[1] = "Echo Request";
tempMap[2] = "Echo Response";
tempMap[3] = "Version Not Supported";
tempMap[4] = "Node Alive Request";
tempMap[5] = "Node Alive Response";
tempMap[6] = "Redirection Request";
tempMap[7] = "Create PDP Context Request";
tempMap[16] = "Create PDP Context Response";
tempMap[17] = "Update PDP Context Request";
tempMap[18] = "Update PDP Context Response";
tempMap[19] = "Delete PDP Context Request";
tempMap[20] = "Delete PDP Context Response";
tempMap[22] = "Initiate PDP Context Activation Request";
tempMap[23] = "Initiate PDP Context Activation Response";
tempMap[26] = "Error Indication";
tempMap[27] = "PDU Notification Request";
tempMap[28] = "PDU Notification Response";
tempMap[29] = "PDU Notification Reject Request";
tempMap[30] = "PDU Notification Reject Response";
tempMap[31] = "Supported Extensions Header Notification";
tempMap[32] = "Send Routing for GPRS Request";
tempMap[33] = "Send Routing for GPRS Response";
tempMap[34] = "Failure Report Request";
tempMap[35] = "Failure Report Response";
tempMap[36] = "Note MS Present Request";
tempMap[37] = "Note MS Present Response";
tempMap[38] = "Identification Request";
tempMap[39] = "Identification Response";
tempMap[50] = "SGSN Context Request";
tempMap[51] = "SGSN Context Response";
tempMap[52] = "SGSN Context Acknowledge";
tempMap[53] = "Forward Relocation Request";
tempMap[54] = "Forward Relocation Response";
tempMap[55] = "Forward Relocation Complete";
tempMap[56] = "Relocation Cancel Request";
tempMap[57] = "Relocation Cancel Response";
tempMap[58] = "Forward SRNS Context";
tempMap[59] = "Forward Relocation Complete Acknowledge";
tempMap[60] = "Forward SRNS Context Acknowledge";
tempMap[61] = "UE Registration Request";
tempMap[62] = "UE Registration Response";
tempMap[70] = "RAN Information Relay";
tempMap[96] = "MBMS Notification Request";
tempMap[97] = "MBMS Notification Response";
tempMap[98] = "MBMS Notification Reject Request";
tempMap[99] = "MBMS Notification Reject Response";
tempMap[100] = "Create MBMS Notification Request";
tempMap[101] = "Create MBMS Notification Response";
tempMap[102] = "Update MBMS Notification Request";
tempMap[103] = "Update MBMS Notification Response";
tempMap[104] = "Delete MBMS Notification Request";
tempMap[105] = "Delete MBMS Notification Response";
tempMap[112] = "MBMS Registration Request";
tempMap[113] = "MBMS Registration Response";
tempMap[114] = "MBMS De-Registration Request";
tempMap[115] = "MBMS De-Registration Response";
tempMap[116] = "MBMS Session Start Request";
tempMap[117] = "MBMS Session Start Response";
tempMap[118] = "MBMS Session Stop Request";
tempMap[119] = "MBMS Session Stop Response";
tempMap[120] = "MBMS Session Update Request";
tempMap[121] = "MBMS Session Update Response";
tempMap[128] = "MS Info Change Request";
tempMap[129] = "MS Info Change Response";
tempMap[240] = "Data Record Transfer Request";
tempMap[241] = "Data Record Transfer Response";
tempMap[254] = "End Marker";
tempMap[255] = "G-PDU";
return tempMap;
}
const std::map<uint8_t, std::string> GTPv1MsgTypeToStringMap = createGtpV1MessageTypeToStringMap();
std::string GtpV1Layer::getMessageTypeAsString()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return GTPv1MsgTypeToStringMap.find(0)->second;
}
std::map<uint8_t, std::string>::const_iterator iter = GTPv1MsgTypeToStringMap.find(header->messageType);
if (iter != GTPv1MsgTypeToStringMap.end())
{
return iter->second;
}
else
{
return GTPv1MsgTypeToStringMap.find(0)->second;
}
}
bool GtpV1Layer::isGTPUMessage()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return false;
}
return header->messageType == PCPP_GTP_V1_GPDU_MESSAGE_TYPE;
}
bool GtpV1Layer::isGTPCMessage()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return false;
}
return header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE;
}
void GtpV1Layer::parseNextLayer()
{
size_t headerLen = getHeaderLen();
if (headerLen < sizeof(gtpv1_header))
{
// do nothing
return;
}
gtpv1_header* header = getHeader();
if (header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
// this is a GTP-C message, hence it is the last layer
return;
}
if (m_DataLen <= headerLen)
{
// no data beyond headerLen, nothing to parse further
return;
}
// GTP-U message, try to parse the next layer
uint8_t subProto = *(uint8_t*)(m_Data + headerLen);
if (subProto >= 0x45 && subProto <= 0x4e)
{
m_NextLayer = new IPv4Layer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
else if ((subProto & 0xf0) == 0x60)
{
m_NextLayer = new IPv6Layer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
else
{
m_NextLayer = new PayloadLayer(m_Data + headerLen, m_DataLen - headerLen, this, m_Packet);
}
}
size_t GtpV1Layer::getHeaderLen()
{
gtpv1_header* header = getHeader();
if (header == NULL)
{
return 0;
}
size_t res = sizeof(gtpv1_header);
if (header->messageType != PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
size_t msgLen = be16toh(header->messageLength);
res += (msgLen > m_DataLen - sizeof(gtpv1_header) ? m_DataLen - sizeof(gtpv1_header) : msgLen);
}
else
{
gtpv1_header_extra* headerExtra = getHeaderExtra();
if (headerExtra != NULL && (header->extensionHeaderFlag == 1 || header->sequenceNumberFlag == 1 || header->npduNumberFlag == 1))
{
res += sizeof(gtpv1_header_extra);
GtpExtension nextExt = getNextExtension();
while (!nextExt.isNull())
{
res += nextExt.getTotalLength();
nextExt = nextExt.getNextExtension();
}
}
}
return res;
}
std::string GtpV1Layer::toString()
{
std::string res = "GTP v1 Layer";
gtpv1_header* header = getHeader();
if (header != NULL)
{
std::stringstream teidStream;
teidStream << be32toh(header->teid);
std::string gtpu_gtpc;
if (header->messageType == PCPP_GTP_V1_GPDU_MESSAGE_TYPE)
{
gtpu_gtpc = "GTP-U message";
}
else
{
gtpu_gtpc = "GTP-C message: " + getMessageTypeAsString();
}
res += ", " + gtpu_gtpc + ", TEID: " + teidStream.str();
}
return res;
}
}<|endoftext|> |
<commit_before>/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/ssl/SSLSession.h>
#include <folly/io/async/test/AsyncSSLSocketTest.h>
#include <folly/portability/GTest.h>
#include <folly/portability/Sockets.h>
#include <memory>
using namespace std;
using namespace testing;
using folly::ssl::SSLSession;
namespace folly {
void getfds(int fds[2]) {
if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
LOG(ERROR) << "failed to create socketpair: " << errnoStr(errno);
}
for (int idx = 0; idx < 2; ++idx) {
int flags = fcntl(fds[idx], F_GETFL, 0);
if (flags == -1) {
LOG(ERROR) << "failed to get flags for socket " << idx << ": "
<< errnoStr(errno);
}
if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
LOG(ERROR) << "failed to put socket " << idx
<< " in non-blocking mode: " << errnoStr(errno);
}
}
}
void getctx(
std::shared_ptr<folly::SSLContext> clientCtx,
std::shared_ptr<folly::SSLContext> serverCtx) {
clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
serverCtx->loadCertificate(kTestCert);
serverCtx->loadPrivateKey(kTestKey);
}
class SSLSessionTest : public testing::Test {
public:
void SetUp() override {
clientCtx.reset(new folly::SSLContext());
dfServerCtx.reset(new folly::SSLContext());
hskServerCtx.reset(new folly::SSLContext());
serverName = "xyz.newdev.facebook.com";
getctx(clientCtx, dfServerCtx);
}
void TearDown() override {}
folly::EventBase eventBase;
std::shared_ptr<SSLContext> clientCtx;
std::shared_ptr<SSLContext> dfServerCtx;
// Use the same SSLContext to continue the handshake after
// tlsext_hostname match.
std::shared_ptr<SSLContext> hskServerCtx;
std::string serverName;
};
/**
* 1. Client sends TLSEXT_HOSTNAME in client hello.
* 2. Server found a match SSL_CTX and use this SSL_CTX to
* continue the SSL handshake.
* 3. Server sends back TLSEXT_HOSTNAME in server hello.
*/
TEST_F(SSLSessionTest, BasicTest) {
std::unique_ptr<SSLSession> sess;
{
int fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
sess = std::make_unique<SSLSession>(clientPtr->getSSLSession());
ASSERT_NE(sess.get(), nullptr);
}
{
int fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
ASSERT_TRUE(clientPtr->getSSLSessionReused());
}
}
TEST_F(SSLSessionTest, SerializeDeserializeTest) {
std::string sessiondata;
{
int fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(clientPtr->getSSLSession());
sessiondata = sess->serialize();
ASSERT_TRUE(!sessiondata.empty());
}
{
int fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(sessiondata);
ASSERT_NE(sess.get(), nullptr);
clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
ASSERT_TRUE(clientPtr->getSSLSessionReused());
}
}
TEST_F(SSLSessionTest, GetSessionID) {
int fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(clientPtr->getSSLSession());
ASSERT_NE(sess, nullptr);
auto sessID = sess->getSessionID();
ASSERT_GE(sessID.length(), 0);
}
} // namespace folly
<commit_msg>SSLSessionTest now uses NetworkSocket<commit_after>/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/ssl/SSLSession.h>
#include <folly/io/async/test/AsyncSSLSocketTest.h>
#include <folly/net/NetOps.h>
#include <folly/net/NetworkSocket.h>
#include <folly/portability/GTest.h>
#include <folly/portability/Sockets.h>
#include <memory>
using namespace std;
using namespace testing;
using folly::ssl::SSLSession;
namespace folly {
void getfds(NetworkSocket fds[2]) {
if (netops::socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
FAIL() << "failed to create socketpair: " << errnoStr(errno);
}
for (int idx = 0; idx < 2; ++idx) {
if (netops::set_socket_non_blocking(fds[idx]) != 0) {
FAIL() << "failed to put socket " << idx
<< " in non-blocking mode: " << errnoStr(errno);
}
}
}
void getctx(
std::shared_ptr<folly::SSLContext> clientCtx,
std::shared_ptr<folly::SSLContext> serverCtx) {
clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
serverCtx->loadCertificate(kTestCert);
serverCtx->loadPrivateKey(kTestKey);
}
class SSLSessionTest : public testing::Test {
public:
void SetUp() override {
clientCtx.reset(new folly::SSLContext());
dfServerCtx.reset(new folly::SSLContext());
hskServerCtx.reset(new folly::SSLContext());
serverName = "xyz.newdev.facebook.com";
getctx(clientCtx, dfServerCtx);
}
void TearDown() override {}
folly::EventBase eventBase;
std::shared_ptr<SSLContext> clientCtx;
std::shared_ptr<SSLContext> dfServerCtx;
// Use the same SSLContext to continue the handshake after
// tlsext_hostname match.
std::shared_ptr<SSLContext> hskServerCtx;
std::string serverName;
};
/**
* 1. Client sends TLSEXT_HOSTNAME in client hello.
* 2. Server found a match SSL_CTX and use this SSL_CTX to
* continue the SSL handshake.
* 3. Server sends back TLSEXT_HOSTNAME in server hello.
*/
TEST_F(SSLSessionTest, BasicTest) {
std::unique_ptr<SSLSession> sess;
{
NetworkSocket fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
sess = std::make_unique<SSLSession>(clientPtr->getSSLSession());
ASSERT_NE(sess.get(), nullptr);
}
{
NetworkSocket fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
ASSERT_TRUE(clientPtr->getSSLSessionReused());
}
}
TEST_F(SSLSessionTest, SerializeDeserializeTest) {
std::string sessiondata;
{
NetworkSocket fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(clientPtr->getSSLSession());
sessiondata = sess->serialize();
ASSERT_TRUE(!sessiondata.empty());
}
{
NetworkSocket fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(sessiondata);
ASSERT_NE(sess.get(), nullptr);
clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
ASSERT_TRUE(clientPtr->getSSLSessionReused());
}
}
TEST_F(SSLSessionTest, GetSessionID) {
NetworkSocket fds[2];
getfds(fds);
AsyncSSLSocket::UniquePtr clientSock(
new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
auto clientPtr = clientSock.get();
AsyncSSLSocket::UniquePtr serverSock(
new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
SSLHandshakeClient client(std::move(clientSock), false, false);
SSLHandshakeServerParseClientHello server(
std::move(serverSock), false, false);
eventBase.loop();
ASSERT_TRUE(client.handshakeSuccess_);
std::unique_ptr<SSLSession> sess =
std::make_unique<SSLSession>(clientPtr->getSSLSession());
ASSERT_NE(sess, nullptr);
auto sessID = sess->getSessionID();
ASSERT_GE(sessID.length(), 0);
}
} // namespace folly
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: boolexpression.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:14:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "boolexpression.hxx"
namespace xforms
{
/** BoolExpression represents a computed XPath expression that returns
* a bool value and caches the results.
*
* As this class has no virtual methods, it should never be used
* polymorphically. */
BoolExpression::BoolExpression() : ComputedExpression()
{
}
BoolExpression::~BoolExpression()
{
}
void BoolExpression::setExpression( const rtl::OUString& rExpression )
{
ComputedExpression::setExpression( rExpression );
mbIsSimple = _checkExpression( " *(true)|(false) *\\( *\\) *" );
}
} // namespace xforms
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.112); FILE MERGED 2006/09/01 17:27:45 kaib 1.3.112.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: boolexpression.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:02:51 $
*
* 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_forms.hxx"
#include "boolexpression.hxx"
namespace xforms
{
/** BoolExpression represents a computed XPath expression that returns
* a bool value and caches the results.
*
* As this class has no virtual methods, it should never be used
* polymorphically. */
BoolExpression::BoolExpression() : ComputedExpression()
{
}
BoolExpression::~BoolExpression()
{
}
void BoolExpression::setExpression( const rtl::OUString& rExpression )
{
ComputedExpression::setExpression( rExpression );
mbIsSimple = _checkExpression( " *(true)|(false) *\\( *\\) *" );
}
} // namespace xforms
<|endoftext|> |
<commit_before>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
#include <set>
#include <vector>
namespace aleph
{
namespace topology
{
/**
Checks whether a simplex in a simplicial complex is principal, i.e.
whether it is not a proper face of any other simplex in K.
*/
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
// Individual vertices cannot be considered to be principal because
// they do not have a free face.
if( s.dimension() == 0 )
return false;
bool principal = true;
auto itPair = K.range( s.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ s. Note that
// the check only has to evaluate the *size* of the intersection,
// as this is sufficient to determine whether a simplex is a face
// of another simplex.
if( sizeOfIntersection(s,t) == s.size() )
principal = false;
}
return principal;
}
/**
Checks whether a simplex in a simplicial complex is admissible, i.e.
the simplex is *principal* and has at least one free face.
*/
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
if( !isPrincipal(s,K) )
return false;
// Check whether a free face exists ----------------------------------
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::vector<bool> admissible( faces.size(), true );
std::size_t i = 0;
auto itPair = K.range( s.dimension() ); // valid range for searches, viz. *all*
// faces in "one dimension up"
for( auto&& face : faces )
{
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// We do not have to check for intersections with the original
// simplex from which we started---we already know that we are
// a face.
if( t != s )
{
if( sizeOfIntersection(face,t) == face.size() )
{
admissible[i] = false;
break;
}
}
}
++i;
}
// TODO: return free face along with admissibility condition
return std::find( admissible.begin(), admissible.end(), true ) != admissible.end();
}
/**
Checks whether a pair of a simplex and its face are admissible, i.e.
the simplex is *principal* and the face is free.
*/
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& sigma, const Simplex& delta, const SimplicialComplex& K )
{
if( !isPrincipal(sigma,K) )
return false;
// Check whether the face is free ------------------------------------
bool admissible = true;
auto itPair = K.range( delta.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& s = *it;
// The simplex we are looking for should be a free face of sigma, so
// we must skip it when checking for other co-faces.
if( s != sigma )
{
if( sizeOfIntersection(delta, s) == delta.size() )
{
admissible = false;
break;
}
}
}
return admissible;
}
/**
Performs one step of an elementary simplicial collapse in a given
simplicial complex. The function assumes that the given simplices
are *valid* for performing the collapse.
*/
template <class SimplicialComplex, class Simplex> SimplicialComplex elementarySimplicialCollapse(
const Simplex& sigma,
const Simplex& delta,
const SimplicialComplex& K )
{
auto L = K;
L.remove_without_validation( sigma );
L.remove_without_validation( delta );
}
/**
Performs an iterated elementary simplicial collapse until *all* of the
admissible simplices have been collapsed. This leads to the *spine* of
the simplicial complex.
@see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/
template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
std::set<Simplex> admissible;
// Step 1: determine free faces --------------------------------------
//
// This first checks which simplices have at least one free face,
// meaning that they may be potentially admissible.
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
continue;
// The range of the complex M is sufficient because we have
// already encountered all lower-dimensional simplices that
// precede the current one given by `it`.
//
// This complex will be used for testing free faces.
SimplicialComplex M( L.begin(), it );
bool hasFreeFace = false;
for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
{
bool isFace = false;
for( auto&& simplex : M )
{
if( itFace->dimension() + 1 == simplex.dimension() )
{
// The current face must *not* be a face of another simplex in
// the simplicial complex.
if( intersect( *itFace, simplex ) == *itFace )
{
isFace = true;
break;
}
}
}
hasFreeFace = !isFace;
if( hasFreeFace )
break;
}
if( hasFreeFace )
admissible.insert( *it );
}
// Step 2: determine principality ------------------------------------
//
// All simplices that are faces of higher-dimensional simplices are
// now removed from the map of admissible simplices.
for( auto&& s : L )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
admissible.erase( *itFace );
}
// Step 3: collapse until no admissible simplices are left -----------
while( !admissible.empty() )
{
auto s = *admissible.begin();
bool hasFreeFace = false;
// TODO: this check could be simplified by *storing* the free face
// along with the given simplex
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto t = *itFace;
if( isAdmissible( s, t, L ) )
{
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices -----------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
if( t != s && isAdmissible( s, L ) )
admissible.insert( s );
}
);
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
if( isAdmissible( s, L ) )
admissible.insert( s );
}
);
hasFreeFace = true;
break;
}
}
// The admissible simplex does not have a free face, so it must not
// be used.
if( !hasFreeFace )
admissible.erase( s );
}
return L;
}
} // namespace topology
} // namespace aleph
#endif
<commit_msg>New function for determining principal faces in a simplicial complex<commit_after>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
#include <set>
#include <vector>
namespace aleph
{
namespace topology
{
/**
Checks whether a simplex in a simplicial complex is principal, i.e.
whether it is not a proper face of any other simplex in K.
*/
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
// Individual vertices cannot be considered to be principal because
// they do not have a free face.
if( s.dimension() == 0 )
return false;
bool principal = true;
auto itPair = K.range( s.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ s. Note that
// the check only has to evaluate the *size* of the intersection,
// as this is sufficient to determine whether a simplex is a face
// of another simplex.
if( sizeOfIntersection(s,t) == s.size() )
principal = false;
}
return principal;
}
/**
Checks whether a simplex in a simplicial complex is admissible, i.e.
the simplex is *principal* and has at least one free face.
*/
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
if( !isPrincipal(s,K) )
return false;
// Check whether a free face exists ----------------------------------
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::vector<bool> admissible( faces.size(), true );
std::size_t i = 0;
auto itPair = K.range( s.dimension() ); // valid range for searches, viz. *all*
// faces in "one dimension up"
for( auto&& face : faces )
{
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& t = *it;
// We do not have to check for intersections with the original
// simplex from which we started---we already know that we are
// a face.
if( t != s )
{
if( sizeOfIntersection(face,t) == face.size() )
{
admissible[i] = false;
break;
}
}
}
++i;
}
// TODO: return free face along with admissibility condition
return std::find( admissible.begin(), admissible.end(), true ) != admissible.end();
}
/**
Checks whether a pair of a simplex and its face are admissible, i.e.
the simplex is *principal* and the face is free.
*/
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& sigma, const Simplex& delta, const SimplicialComplex& K )
{
if( !isPrincipal(sigma,K) )
return false;
// Check whether the face is free ------------------------------------
bool admissible = true;
auto itPair = K.range( delta.dimension() + 1 );
for( auto it = itPair.first; it != itPair.second; ++it )
{
auto&& s = *it;
// The simplex we are looking for should be a free face of sigma, so
// we must skip it when checking for other co-faces.
if( s != sigma )
{
if( sizeOfIntersection(delta, s) == delta.size() )
{
admissible = false;
break;
}
}
}
return admissible;
}
/**
Calculates all principal faces of a given simplicial complex and
returns them.
*/
template <class SimplicialComplex> std::unordered_set<typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
std::unordered_set<Simplex> admissible;
// Step 1: determine free faces --------------------------------------
//
// This first checks which simplices have at least one free face,
// meaning that they may be potentially admissible.
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
continue;
// The range of the complex M is sufficient because we have
// already encountered all lower-dimensional simplices that
// precede the current one given by `it`.
//
// This complex will be used for testing free faces.
SimplicialComplex M( L.begin(), it );
// FIXME:
//
// In case of equal data values, the assignment from above does
// *not* work and will result in incorrect candidates.
M = L;
bool hasFreeFace = false;
for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
{
bool isFace = false;
for( auto&& simplex : M )
{
if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )
{
// The current face must *not* be a face of another simplex in
// the simplicial complex.
if( intersect( *itFace, simplex ) == *itFace )
{
isFace = true;
break;
}
}
}
hasFreeFace = !isFace;
if( hasFreeFace )
break;
}
if( hasFreeFace )
admissible.insert( *it );
}
// Step 2: determine principality ------------------------------------
//
// All simplices that are faces of higher-dimensional simplices are
// now removed from the map of admissible simplices.
for( auto&& s : L )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
admissible.erase( *itFace );
}
return admissible;
}
/**
Performs one step of an elementary simplicial collapse in a given
simplicial complex. The function assumes that the given simplices
are *valid* for performing the collapse.
*/
template <class SimplicialComplex, class Simplex> SimplicialComplex elementarySimplicialCollapse(
const Simplex& sigma,
const Simplex& delta,
const SimplicialComplex& K )
{
auto L = K;
L.remove_without_validation( sigma );
L.remove_without_validation( delta );
}
/**
Performs an iterated elementary simplicial collapse until *all* of the
admissible simplices have been collapsed. This leads to the *spine* of
the simplicial complex.
@see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/
template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
using Simplex = typename SimplicialComplex::value_type;
auto L = K;
std::set<Simplex> admissible;
// Step 1: determine free faces --------------------------------------
//
// This first checks which simplices have at least one free face,
// meaning that they may be potentially admissible.
for( auto it = L.begin(); it != L.end(); ++it )
{
if( it->dimension() == 0 )
continue;
// The range of the complex M is sufficient because we have
// already encountered all lower-dimensional simplices that
// precede the current one given by `it`.
//
// This complex will be used for testing free faces.
SimplicialComplex M( L.begin(), it );
bool hasFreeFace = false;
for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
{
bool isFace = false;
for( auto&& simplex : M )
{
if( itFace->dimension() + 1 == simplex.dimension() )
{
// The current face must *not* be a face of another simplex in
// the simplicial complex.
if( intersect( *itFace, simplex ) == *itFace )
{
isFace = true;
break;
}
}
}
hasFreeFace = !isFace;
if( hasFreeFace )
break;
}
if( hasFreeFace )
admissible.insert( *it );
}
// Step 2: determine principality ------------------------------------
//
// All simplices that are faces of higher-dimensional simplices are
// now removed from the map of admissible simplices.
for( auto&& s : L )
{
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
admissible.erase( *itFace );
}
// Step 3: collapse until no admissible simplices are left -----------
while( !admissible.empty() )
{
auto s = *admissible.begin();
bool hasFreeFace = false;
// TODO: this check could be simplified by *storing* the free face
// along with the given simplex
for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
{
auto t = *itFace;
if( isAdmissible( s, t, L ) )
{
L.remove_without_validation( s );
L.remove_without_validation( t );
admissible.erase( s );
// New simplices -----------------------------------------------
//
// Add new admissible simplices that may potentially have been
// spawned by the removal of s.
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&t, &L, &admissible] ( const Simplex& s )
{
if( t != s && isAdmissible( s, L ) )
admissible.insert( s );
}
);
faces.assign( t.begin_boundary(), t.end_boundary() );
std::for_each( faces.begin(), faces.end(),
[&L, &admissible] ( const Simplex& s )
{
if( isAdmissible( s, L ) )
admissible.insert( s );
}
);
hasFreeFace = true;
break;
}
}
// The admissible simplex does not have a free face, so it must not
// be used.
if( !hasFreeFace )
admissible.erase( s );
}
return L;
}
} // namespace topology
} // namespace aleph
#endif
<|endoftext|> |
<commit_before>#pragma once
class HttpRouter
{
public:
private:
};
<commit_msg>update http_router.hpp 修改<commit_after>#pragma once
#include <vector>
#include <map>
#include <string>
#include <functional>
#include "function_traits.hpp"
#include "lexical_cast.hpp"
class HttpRouter
{
class token_parser
{
std::vector<std::string> m_v;
static std::vector<std::string> split(std::string& s, char seperator)
{
std::vector<std::string> v;
int pos = 0;
while (true)
{
pos = s.find(seperator, 0);
if (pos == std::string::npos)
{
if (!s.empty())
v.push_back(s);
break;
}
if (pos != 0)
v.push_back(s.substr(0, pos));
s = s.substr(pos + 1, s.length());
}
return v;
}
public:
token_parser(std::string& s, char seperator)
{
m_v = split(s, seperator);
}
public:
template<typename RequestedType>
typename std::decay<RequestedType>::type get()
{
if (m_v.empty())
throw std::runtime_error("unexpected end of input");
try
{
typedef typename std::decay<RequestedType>::type result_type;
auto it = m_v.begin();
result_type result = lexical_cast<typename std::decay<result_type>::type>(*it);
m_v.erase(it);
return result;
}
catch (std::exception& e)
{
throw std::invalid_argument(std::string("invalid argument: ") + e.what());
}
}
bool empty(){ return m_v.empty(); }
};
typedef std::function<void(token_parser &)> invoker_function;
std::map<std::string, invoker_function> map_invokers;
public:
std::function<void(const std::string&)> log;
template<typename Function>
void assign(std::string const & name, Function f) {
return register_nonmenber_impl<Function>(name, f);
}
void remove_function(std::string const& name) {
this->map_invokers.erase(name);
}
void run(std::string & text) const
{
token_parser parser(text, '/');
while (!parser.empty())
{
// read function name
std::string func_name = parser.get<std::string>();
// look up function
auto it = map_invokers.find(func_name);
if (it == map_invokers.end())
throw std::runtime_error("unknown function: " + func_name);
// call the invoker which controls argument parsing
it->second(parser);
}
}
public:
template<class Signature, typename Function>
void register_nonmenber_impl(std::string const & name, Function f)
{
// instantiate and store the invoker by name
this->map_invokers[name] = std::bind(
&invoker<Function, Signature>::template apply<std::tuple<>>,
f,
std::placeholders::_1,
std::tuple<>()
);
}
private:
template<typename Function, class Signature = Function, size_t N = 0, size_t M = function_traits<Signature>::arity>
struct invoker;
template<typename Function, class Signature, size_t N, size_t M>
struct invoker
{
// add an argument to a Fusion cons-list for each parameter type
template<typename Args>
static inline void apply(Function func, token_parser & parser, Args const & args)
{
typedef typename function_traits<Signature>::template args<N>::type arg_type;
HttpRouter::invoker<Function, Signature, N + 1, M>::apply
(func, parser, std::tuple_cat(args, std::make_tuple(parser.get<arg_type>())));
}
};
template<typename Function, class Signature, size_t M>
struct invoker<Function, Signature, M, M>
{
// the argument list is complete, now call the function
template<typename Args>
static inline void apply(Function func, token_parser &, Args const & args)
{
call(func, args);
}
};
template<int...>
struct IndexTuple{};
template<int N, int... Indexes>
struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>{};
template<int... indexes>
struct MakeIndexes<0, indexes...>
{
typedef IndexTuple<indexes...> type;
};
template<typename F, int ... Indexes, typename ... Args>
static void call_helper(F f, IndexTuple<Indexes...>, std::tuple<Args...> tup)
{
f(std::get<Indexes>(tup)...);
}
template<typename F, typename ... Args>
static void call(F f, std::tuple<Args...> tp)
{
call_helper(f, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
};
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../GameObject.h"
#include "../ComponentScript.h"
#include "../ComponentTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../PhysBody3D.h"
#include "../ComponentCollider.h"
#include "../ModuleGOManager.h"
#include "../Globals.h"
namespace Player_Camera
{
float Player_Camera_distrance_y = 0.0;
float Player_Camera_distrance_z = 0.0;
GameObject* Player_Camera_target = nullptr;
void Player_Camera_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
{
public_float->insert(pair<const char*, float>("dist_y", Player_Camera_distrance_y));
public_float->insert(pair<const char*, float>("dist_z", Player_Camera_distrance_z));
public_gos->insert(pair<const char*, GameObject*>("target", nullptr));
}
void Player_Camera_UpdatePublics(GameObject* game_object)
{
ComponentScript* Player_Camera_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
Player_Camera_distrance_y = Player_Camera_script->public_floats.at("dist_y");
Player_Camera_distrance_z = Player_Camera_script->public_floats.at("dist_z");
Player_Camera_target = Player_Camera_script->public_gos.at("target");
}
void Player_Camera_Start(GameObject* game_object)
{
}
void Player_Camera_Update(GameObject* game_object)
{
Quat Player_Camera_rot = game_object->transform->GetRotation();
float3 Player_Camera_euler_rot = game_object->transform->GetRotationEuler();
game_object->transform->SetRotation(float3(0.0, Player_Camera_euler_rot.y, 0.0));
if (Player_Camera_target != nullptr)
{
game_object->transform->SetRotation(float3(0.0, Player_Camera_target->transform->GetRotationEuler().y, 0.0));
float3 Player_Camera_target_pos = float3::zero;
Player_Camera_target_pos += (float3(game_object->transform->GetForward().Normalized().x, 0.0, game_object->transform->GetForward().Normalized().z) * Player_Camera_distrance_z);
Player_Camera_target_pos += (float3(0.0, Player_Camera_distrance_y, 0.0));
Player_Camera_target_pos += Player_Camera_target->transform->GetPosition();
game_object->transform->SetPosition(Player_Camera_target_pos);
}
}
}<commit_msg>Change camera y and z with car x rotation<commit_after>#include "stdafx.h"
#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../GameObject.h"
#include "../ComponentScript.h"
#include "../ComponentTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../PhysBody3D.h"
#include "../ComponentCollider.h"
#include "../ModuleGOManager.h"
#include "../ComponentCamera.h"
#include "../Globals.h"
namespace Player_Camera
{
float Player_Camera_distrance_y = 0.0;
float Player_Camera_distrance_z = 0.0;
GameObject* Player_Camera_target = nullptr;
float Player_Camera_inclination_separation_y = 0.0;
float Player_Camera_inclination_separation_z = 0.0;
void Player_Camera_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
{
public_float->insert(pair<const char*, float>("dist_y", Player_Camera_distrance_y));
public_float->insert(pair<const char*, float>("dist_z", Player_Camera_distrance_z));
public_gos->insert(pair<const char*, GameObject*>("target", nullptr));
public_float->insert(pair<const char*, float>("inclination separation max and min y", Player_Camera_inclination_separation_y));
public_float->insert(pair<const char*, float>("inclination separation max and min z", Player_Camera_inclination_separation_z));
}
void Player_Camera_UpdatePublics(GameObject* game_object)
{
ComponentScript* Player_Camera_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
Player_Camera_distrance_y = Player_Camera_script->public_floats.at("dist_y");
Player_Camera_distrance_z = Player_Camera_script->public_floats.at("dist_z");
Player_Camera_target = Player_Camera_script->public_gos.at("target");
Player_Camera_inclination_separation_y = Player_Camera_script->public_floats.at("inclination separation max and min y");
Player_Camera_inclination_separation_z = Player_Camera_script->public_floats.at("inclination separation max and min z");
}
void Player_Camera_Start(GameObject* game_object)
{
}
void Player_Camera_Update(GameObject* game_object)
{
Quat Player_Camera_rot = game_object->transform->GetRotation();
float3 Player_Camera_euler_rot = game_object->transform->GetRotationEuler();
game_object->transform->SetRotation(float3(0.0, Player_Camera_euler_rot.y, 0.0));
if (Player_Camera_target != nullptr)
{
game_object->transform->SetRotation(float3(0.0, Player_Camera_target->transform->GetRotationEuler().y, 0.0));
float rotation_x = Player_Camera_target->transform->GetRotationEuler().x;
if (rotation_x > 90)
rotation_x = 90;
else if (rotation_x < -90)
rotation_x = -90;
float3 Player_Camera_target_pos = float3::zero;
Player_Camera_target_pos += (float3(game_object->transform->GetForward().Normalized().x, 0.0, game_object->transform->GetForward().Normalized().z) * (Player_Camera_distrance_z + rotation_x / 90 * Player_Camera_inclination_separation_z));
Player_Camera_target_pos += (float3(0.0, Player_Camera_distrance_y + rotation_x / 90 * Player_Camera_inclination_separation_y, 0.0));
Player_Camera_target_pos += Player_Camera_target->transform->GetPosition();
game_object->transform->SetPosition(Player_Camera_target_pos);
ComponentCamera* Player_Camera_cam = (ComponentCamera*)game_object->GetComponent(ComponentType::C_CAMERA);
if (Player_Camera_cam != nullptr)
{
Player_Camera_cam->LookAt(Player_Camera_target->transform->GetPosition());
}
}
}
}<|endoftext|> |
<commit_before>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_PHYSICAL_DEVICE_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_PHYSICAL_DEVICE_HPP
/** @file
*
* @brief Physical device.
* @author Andreas Weis (der_ghulbus@ghulbus-inc.de)
*/
#include <gbVk/config.hpp>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan.hpp>
#include <optional>
#include <vector>
namespace GHULBUS_VULKAN_NAMESPACE
{
class Device;
class DeviceBuilder;
struct NoSwapchainSupport_T {};
inline constexpr NoSwapchainSupport_T no_swapchain_support {};
class PhysicalDevice {
private:
VkPhysicalDevice m_physicalDevice;
public:
explicit PhysicalDevice(VkPhysicalDevice physical_device);
VkPhysicalDevice getVkPhysicalDevice();
VkPhysicalDeviceProperties getProperties();
VkPhysicalDeviceFeatures getFeatures();
VkPhysicalDeviceMemoryProperties getMemoryProperties();
std::vector<VkQueueFamilyProperties> getQueueFamilyProperties();
VkFormatProperties getFormatProperties(VkFormat format);
std::optional<VkFormat> findSupportedFormat(std::vector<VkFormat> const& candidates,
VkImageTiling tiling, VkFormatFeatureFlags features);
std::optional<VkFormat> findDepthBufferFormat();
VkImageFormatProperties getImageFormatProperties(VkFormat format, VkImageType type,
VkImageTiling tiling, VkImageUsageFlags usage,
VkImageCreateFlags create_flags);
std::optional<uint32_t> findMemoryTypeIndex(VkMemoryPropertyFlags requested_properties);
std::optional<uint32_t> findMemoryTypeIndex(VkMemoryPropertyFlags requested_properties,
VkMemoryRequirements const& requirements);
bool getSurfaceSupport(uint32_t queue_family, VkSurfaceKHR surface);
std::vector<VkLayerProperties> [[deprecated]] enumerateDeviceLayerProperties();
std::vector<VkExtensionProperties> enumerateDeviceExtensionProperties();
std::vector<VkExtensionProperties> enumerateDeviceExtensionProperties(VkLayerProperties layer);
DeviceBuilder createDeviceBuilder(NoSwapchainSupport_T const&);
DeviceBuilder createDeviceBuilder();
Device createDevice();
};
}
#endif
<commit_msg>fixed misplaced deprecated attribute<commit_after>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_PHYSICAL_DEVICE_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_PHYSICAL_DEVICE_HPP
/** @file
*
* @brief Physical device.
* @author Andreas Weis (der_ghulbus@ghulbus-inc.de)
*/
#include <gbVk/config.hpp>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan.hpp>
#include <optional>
#include <vector>
namespace GHULBUS_VULKAN_NAMESPACE
{
class Device;
class DeviceBuilder;
struct NoSwapchainSupport_T {};
inline constexpr NoSwapchainSupport_T no_swapchain_support {};
class PhysicalDevice {
private:
VkPhysicalDevice m_physicalDevice;
public:
explicit PhysicalDevice(VkPhysicalDevice physical_device);
VkPhysicalDevice getVkPhysicalDevice();
VkPhysicalDeviceProperties getProperties();
VkPhysicalDeviceFeatures getFeatures();
VkPhysicalDeviceMemoryProperties getMemoryProperties();
std::vector<VkQueueFamilyProperties> getQueueFamilyProperties();
VkFormatProperties getFormatProperties(VkFormat format);
std::optional<VkFormat> findSupportedFormat(std::vector<VkFormat> const& candidates,
VkImageTiling tiling, VkFormatFeatureFlags features);
std::optional<VkFormat> findDepthBufferFormat();
VkImageFormatProperties getImageFormatProperties(VkFormat format, VkImageType type,
VkImageTiling tiling, VkImageUsageFlags usage,
VkImageCreateFlags create_flags);
std::optional<uint32_t> findMemoryTypeIndex(VkMemoryPropertyFlags requested_properties);
std::optional<uint32_t> findMemoryTypeIndex(VkMemoryPropertyFlags requested_properties,
VkMemoryRequirements const& requirements);
bool getSurfaceSupport(uint32_t queue_family, VkSurfaceKHR surface);
[[deprecated]] std::vector<VkLayerProperties> enumerateDeviceLayerProperties();
std::vector<VkExtensionProperties> enumerateDeviceExtensionProperties();
std::vector<VkExtensionProperties> enumerateDeviceExtensionProperties(VkLayerProperties layer);
DeviceBuilder createDeviceBuilder(NoSwapchainSupport_T const&);
DeviceBuilder createDeviceBuilder();
Device createDevice();
};
}
#endif
<|endoftext|> |
<commit_before>#ifndef GRL_KUKA_DRIVER
#define GRL_KUKA_DRIVER
#include <tuple>
#include <memory>
#include <thread>
#include <boost/asio.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/exception/all.hpp>
#include <boost/config.hpp>
#include <boost/make_shared.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <boost/make_shared.hpp>
#ifdef BOOST_NO_CXX11_ATOMIC_SMART_PTR
#include <boost/thread.hpp>
#endif
#include "Kuka.hpp"
#include "grl/kuka/KukaJAVAdriver.hpp"
#include "grl/kuka/KukaFRIdriver.hpp"
#include "grl/tags.hpp"
namespace grl { namespace robot { namespace arm {
///
///
/// @brief Kuka LBR iiwa Primary Multi Mode Driver, supports communication over FRI and JAVA interfaces
///
/// @todo enable commanding and monitoring to be independently configured for both FRI and JAVA interface.
///
class KukaDriver : public std::enable_shared_from_this<KukaDriver> {
public:
enum ParamIndex {
RobotName,
LocalZMQAddress,
RemoteZMQAddress,
LocalHostKukaKoniUDPAddress,
LocalHostKukaKoniUDPPort,
RemoteHostKukaKoniUDPAddress,
RemoteHostKukaKoniUDPPort,
KukaCommandMode,
KukaMonitorMode
};
/// @todo allow default params
typedef std::tuple<
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string
> Params;
static const Params defaultParams(){
return std::make_tuple(
"Robotiiwa" , // RobotName,
"tcp://0.0.0.0:30010" , // LocalZMQAddress
"tcp://172.31.1.147:30010", // RemoteZMQAddress
"192.170.10.100" , // LocalHostKukaKoniUDPAddress,
"30200" , // LocalHostKukaKoniUDPPort,
"192.170.10.2" , // RemoteHostKukaKoniUDPAddress,
"30200" , // RemoteHostKukaKoniUDPPort
"JAVA" , // KukaCommandMode (options are FRI, JAVA)
"JAVA" // KukaMonitorMode (options are FRI, JAVA)
);
}
KukaDriver(Params params = defaultParams())
: params_(params)
{}
void construct(){ construct(params_);}
bool destruct(){ return JAVAdriverP_->destruct(); }
/// @todo create a function that calls simGetObjectHandle and throws an exception when it fails
/// @warning getting the ik group is optional, so it does not throw an exception
void construct(Params params) {
params_ = params;
// keep driver threads from exiting immediately after creation, because they have work to do!
//device_driver_workP_.reset(new boost::asio::io_service::work(device_driver_io_service));
/// @todo figure out how to re-enable when .so isn't loaded
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("FRI"))
|| boost::iequals(std::get<KukaMonitorMode>(params_),std::string("FRI")))
{
FRIdriverP_.reset(
new grl::robot::arm::KukaFRIdriver(
//device_driver_io_service,
std::make_tuple(
std::string(std::get<LocalHostKukaKoniUDPAddress > (params)),
std::string(std::get<LocalHostKukaKoniUDPPort > (params)),
std::string(std::get<RemoteHostKukaKoniUDPAddress> (params)),
std::string(std::get<RemoteHostKukaKoniUDPPort > (params)),
ms_per_tick ,
grl::robot::arm::KukaFRIClientDataDriver::run_automatically
)
)
);
FRIdriverP_->construct();
}
/// @todo implement reading configuration in both FRI and JAVA mode from JAVA interface
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("JAVA"))){
try {
JAVAdriverP_ = boost::make_shared<KukaJAVAdriver>(params_);
JAVAdriverP_->construct();
// start up the driver thread
/// @todo perhaps allow user to control this?
//driver_threadP.reset(new std::thread([&]{ device_driver_io_service.run(); }));
} catch( boost::exception &e) {
e << errmsg_info("KukaDriver: Unable to connect to ZeroMQ Socket from " +
std::get<LocalZMQAddress> (params_) + " to " +
std::get<RemoteZMQAddress> (params_));
throw;
}
}
}
const Params & getParams(){
return params_;
}
~KukaDriver(){
device_driver_workP_.reset();
if(driver_threadP){
device_driver_io_service.stop();
driver_threadP->join();
}
}
/**
* spin once
*
*/
bool run_one(){
// @todo CHECK FOR REAL DATA BEFORE SENDING COMMANDS
//if(!m_haveReceivedRealDataCount) return;
bool haveNewData = false;
/// @todo make this handled by template driver implementations/extensions
if(JAVAdriverP_.get() != nullptr)
{
std::cout << "commandedpos:" << armState_.commandedPosition;
/////////////////////////////////////////
// Client sends to server asynchronously!
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("JAVA")))
{
JAVAdriverP_->set(armState_.commandedPosition,revolute_joint_angle_open_chain_command_tag());
}
std::cout << "commandedpos:" << armState_.commandedPosition;
haveNewData = JAVAdriverP_->run_one();
if( boost::iequals(std::get<KukaMonitorMode>(params_),std::string("JAVA")))
{
JAVAdriverP_->get(armState_);
}
std::cout << "commandedpos:" << armState_.commandedPosition;
}
if(FRIdriverP_.get() != nullptr)
{
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("FRI")))
{
FRIdriverP_->set(armState_.commandedPosition,revolute_joint_angle_open_chain_command_tag());
}
haveNewData = FRIdriverP_->run_one();
if( boost::iequals(std::get<KukaMonitorMode>(params_),std::string("FRI")))
{
FRIdriverP_->get(armState_);
}
}
return haveNewData;
}
/// set the mode of the arm. Examples: Teach or MoveArmJointServo
/// @see grl::flatbuffer::ArmState in ArmControlState_generated.h
void set(const flatbuffer::ArmState & armControlMode)
{
if(JAVAdriverP_)
{
JAVAdriverP_->set(armControlMode);
}
}
/**
* \brief Set the joint positions for the current interpolation step.
*
* This method is only effective when the client is in a commanding state.
* @param state Object which stores the current state of the robot, including the command to send next
* @param range Array with the new joint positions (in radians)
* @param tag identifier object indicating that revolute joint angle commands should be modified
*/
template<typename Range>
void set(Range&& range, grl::revolute_joint_angle_open_chain_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
boost::copy(range, std::back_inserter(armState_.commandedPosition));
boost::copy(range, std::back_inserter(armState_.commandedPosition_goal));
std::cout << "set commandedpos:" << armState_.commandedPosition;
}
/**
* \brief Set the applied joint torques for the current interpolation step.
*
* This method is only effective when the client is in a commanding state.
* The ControlMode of the robot has to be joint impedance control mode. The
* Client Command Mode has to be torque.
*
* @param state Object which stores the current state of the robot, including the command to send next
* @param torques Array with the applied torque values (in Nm)
* @param tag identifier object indicating that the torqe value command should be modified
*/
template<typename Range>
void set(Range&& range, grl::revolute_joint_torque_open_chain_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
boost::copy(range, std::back_inserter(armState_.commandedTorque));
}
/**
* \brief Set the applied wrench vector of the current interpolation step.
*
* The wrench vector consists of:
* [F_x, F_y, F_z, tau_A, tau_B, tau_C]
*
* F ... forces (in N) applied along the Cartesian axes of the
* currently used motion center.
* tau ... torques (in Nm) applied along the orientation angles
* (Euler angles A, B, C) of the currently used motion center.
*
* This method is only effective when the client is in a commanding state.
* The ControlMode of the robot has to be Cartesian impedance control mode. The
* Client Command Mode has to be wrench.
*
* @param state object storing the command data that will be sent to the physical device
* @param range wrench Applied Cartesian wrench vector, in x, y, z, roll, pitch, yaw force measurments.
* @param tag identifier object indicating that the wrench value command should be modified
*
* @todo perhaps support some specific more useful data layouts
*/
template<typename Range>
void set(Range&& range, grl::cartesian_wrench_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
std::copy(range,armState_.commandedCartesianWrenchFeedForward);
}
/// @todo implement get function
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_angle_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState_.position,output);
}
/// @todo implement get function
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_torque_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState.torque,output);
}
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_torque_external_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState.externalTorque,output);
}
template<typename OutputIterator>
void get(OutputIterator output, grl::cartesian_external_force_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState.externalForce,output);
}
volatile std::size_t m_haveReceivedRealDataCount = 0;
volatile std::size_t m_attemptedCommunicationCount = 0;
volatile std::size_t m_attemptedCommunicationConsecutiveFailureCount = 0;
volatile std::size_t m_attemptedCommunicationConsecutiveSuccessCount = 0;
boost::asio::io_service device_driver_io_service;
std::unique_ptr<boost::asio::io_service::work> device_driver_workP_;
std::unique_ptr<std::thread> driver_threadP;
private:
/// @todo read ms_per_tick from JAVA interface
std::size_t ms_per_tick = 1;
KukaState armState_;
boost::mutex jt_mutex;
boost::shared_ptr<KukaFRIdriver> FRIdriverP_;
boost::shared_ptr<KukaJAVAdriver> JAVAdriverP_;
Params params_;
};
}}}// namespace grl::robot::arm
#endif
<commit_msg>fix minor KukaDriver compiler errors from merge<commit_after>#ifndef GRL_KUKA_DRIVER
#define GRL_KUKA_DRIVER
#include <tuple>
#include <memory>
#include <thread>
#include <boost/asio.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/exception/all.hpp>
#include <boost/config.hpp>
#include <boost/make_shared.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <boost/make_shared.hpp>
#ifdef BOOST_NO_CXX11_ATOMIC_SMART_PTR
#include <boost/thread.hpp>
#endif
#include "Kuka.hpp"
#include "grl/kuka/KukaJAVAdriver.hpp"
#include "grl/kuka/KukaFRIdriver.hpp"
#include "grl/tags.hpp"
namespace grl { namespace robot { namespace arm {
///
///
/// @brief Kuka LBR iiwa Primary Multi Mode Driver, supports communication over FRI and JAVA interfaces
///
/// @todo enable commanding and monitoring to be independently configured for both FRI and JAVA interface.
///
class KukaDriver : public std::enable_shared_from_this<KukaDriver> {
public:
enum ParamIndex {
RobotName,
LocalZMQAddress,
RemoteZMQAddress,
LocalHostKukaKoniUDPAddress,
LocalHostKukaKoniUDPPort,
RemoteHostKukaKoniUDPAddress,
RemoteHostKukaKoniUDPPort,
KukaCommandMode,
KukaMonitorMode
};
/// @todo allow default params
typedef std::tuple<
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string,
std::string
> Params;
static const Params defaultParams(){
return std::make_tuple(
"Robotiiwa" , // RobotName,
"tcp://0.0.0.0:30010" , // LocalZMQAddress
"tcp://172.31.1.147:30010", // RemoteZMQAddress
"192.170.10.100" , // LocalHostKukaKoniUDPAddress,
"30200" , // LocalHostKukaKoniUDPPort,
"192.170.10.2" , // RemoteHostKukaKoniUDPAddress,
"30200" , // RemoteHostKukaKoniUDPPort
"JAVA" , // KukaCommandMode (options are FRI, JAVA)
"JAVA" // KukaMonitorMode (options are FRI, JAVA)
);
}
KukaDriver(Params params = defaultParams())
: params_(params)
{}
void construct(){ construct(params_);}
bool destruct(){ return JAVAdriverP_->destruct(); }
/// @todo create a function that calls simGetObjectHandle and throws an exception when it fails
/// @warning getting the ik group is optional, so it does not throw an exception
void construct(Params params) {
params_ = params;
// keep driver threads from exiting immediately after creation, because they have work to do!
//device_driver_workP_.reset(new boost::asio::io_service::work(device_driver_io_service));
/// @todo figure out how to re-enable when .so isn't loaded
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("FRI"))
|| boost::iequals(std::get<KukaMonitorMode>(params_),std::string("FRI")))
{
FRIdriverP_.reset(
new grl::robot::arm::KukaFRIdriver(
//device_driver_io_service,
std::make_tuple(
std::string(std::get<LocalHostKukaKoniUDPAddress > (params)),
std::string(std::get<LocalHostKukaKoniUDPPort > (params)),
std::string(std::get<RemoteHostKukaKoniUDPAddress> (params)),
std::string(std::get<RemoteHostKukaKoniUDPPort > (params)),
ms_per_tick ,
grl::robot::arm::KukaFRIClientDataDriver::run_automatically
)
)
);
FRIdriverP_->construct();
}
/// @todo implement reading configuration in both FRI and JAVA mode from JAVA interface
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("JAVA"))){
try {
JAVAdriverP_ = boost::make_shared<KukaJAVAdriver>(params_);
JAVAdriverP_->construct();
// start up the driver thread
/// @todo perhaps allow user to control this?
//driver_threadP.reset(new std::thread([&]{ device_driver_io_service.run(); }));
} catch( boost::exception &e) {
e << errmsg_info("KukaDriver: Unable to connect to ZeroMQ Socket from " +
std::get<LocalZMQAddress> (params_) + " to " +
std::get<RemoteZMQAddress> (params_));
throw;
}
}
}
const Params & getParams(){
return params_;
}
~KukaDriver(){
device_driver_workP_.reset();
if(driver_threadP){
device_driver_io_service.stop();
driver_threadP->join();
}
}
/**
* spin once
*
*/
bool run_one(){
// @todo CHECK FOR REAL DATA BEFORE SENDING COMMANDS
//if(!m_haveReceivedRealDataCount) return;
bool haveNewData = false;
/// @todo make this handled by template driver implementations/extensions
if(JAVAdriverP_.get() != nullptr)
{
std::cout << "commandedpos:" << armState_.commandedPosition;
/////////////////////////////////////////
// Client sends to server asynchronously!
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("JAVA")))
{
JAVAdriverP_->set(armState_.commandedPosition,revolute_joint_angle_open_chain_command_tag());
}
std::cout << "commandedpos:" << armState_.commandedPosition;
haveNewData = JAVAdriverP_->run_one();
if( boost::iequals(std::get<KukaMonitorMode>(params_),std::string("JAVA")))
{
JAVAdriverP_->get(armState_);
}
std::cout << "commandedpos:" << armState_.commandedPosition;
}
if(FRIdriverP_.get() != nullptr)
{
if( boost::iequals(std::get<KukaCommandMode>(params_),std::string("FRI")))
{
FRIdriverP_->set(armState_.commandedPosition,revolute_joint_angle_open_chain_command_tag());
}
haveNewData = FRIdriverP_->run_one();
if( boost::iequals(std::get<KukaMonitorMode>(params_),std::string("FRI")))
{
FRIdriverP_->get(armState_);
}
}
return haveNewData;
}
/// set the mode of the arm. Examples: Teach or MoveArmJointServo
/// @see grl::flatbuffer::ArmState in ArmControlState_generated.h
void set(const flatbuffer::ArmState & armControlMode)
{
if(JAVAdriverP_)
{
JAVAdriverP_->set(armControlMode);
}
}
/**
* \brief Set the joint positions for the current interpolation step.
*
* This method is only effective when the client is in a commanding state.
* @param state Object which stores the current state of the robot, including the command to send next
* @param range Array with the new joint positions (in radians)
* @param tag identifier object indicating that revolute joint angle commands should be modified
*/
template<typename Range>
void set(Range&& range, grl::revolute_joint_angle_open_chain_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
boost::copy(range, std::back_inserter(armState_.commandedPosition));
boost::copy(range, std::back_inserter(armState_.commandedPosition_goal));
std::cout << "set commandedpos:" << armState_.commandedPosition;
}
/**
* \brief Set the applied joint torques for the current interpolation step.
*
* This method is only effective when the client is in a commanding state.
* The ControlMode of the robot has to be joint impedance control mode. The
* Client Command Mode has to be torque.
*
* @param state Object which stores the current state of the robot, including the command to send next
* @param torques Array with the applied torque values (in Nm)
* @param tag identifier object indicating that the torqe value command should be modified
*/
template<typename Range>
void set(Range&& range, grl::revolute_joint_torque_open_chain_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
boost::copy(range, std::back_inserter(armState_.commandedTorque));
}
/**
* \brief Set the applied wrench vector of the current interpolation step.
*
* The wrench vector consists of:
* [F_x, F_y, F_z, tau_A, tau_B, tau_C]
*
* F ... forces (in N) applied along the Cartesian axes of the
* currently used motion center.
* tau ... torques (in Nm) applied along the orientation angles
* (Euler angles A, B, C) of the currently used motion center.
*
* This method is only effective when the client is in a commanding state.
* The ControlMode of the robot has to be Cartesian impedance control mode. The
* Client Command Mode has to be wrench.
*
* @param state object storing the command data that will be sent to the physical device
* @param range wrench Applied Cartesian wrench vector, in x, y, z, roll, pitch, yaw force measurments.
* @param tag identifier object indicating that the wrench value command should be modified
*
* @todo perhaps support some specific more useful data layouts
*/
template<typename Range>
void set(Range&& range, grl::cartesian_wrench_command_tag) {
boost::unique_lock<boost::mutex> lock(jt_mutex);
armState_.clearCommands();
std::copy(range,armState_.commandedCartesianWrenchFeedForward);
}
/// @todo implement get function
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_angle_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState_.position,output);
}
/// @todo implement get function
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_torque_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState_.torque,output);
}
template<typename OutputIterator>
void get(OutputIterator output, grl::revolute_joint_torque_external_open_chain_state_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState_.externalTorque,output);
}
template<typename OutputIterator>
void get(OutputIterator output, grl::cartesian_external_force_tag)
{
boost::unique_lock<boost::mutex> lock(jt_mutex);
boost::copy(armState_.externalForce,output);
}
volatile std::size_t m_haveReceivedRealDataCount = 0;
volatile std::size_t m_attemptedCommunicationCount = 0;
volatile std::size_t m_attemptedCommunicationConsecutiveFailureCount = 0;
volatile std::size_t m_attemptedCommunicationConsecutiveSuccessCount = 0;
boost::asio::io_service device_driver_io_service;
std::unique_ptr<boost::asio::io_service::work> device_driver_workP_;
std::unique_ptr<std::thread> driver_threadP;
private:
/// @todo read ms_per_tick from JAVA interface
std::size_t ms_per_tick = 1;
KukaState armState_;
boost::mutex jt_mutex;
boost::shared_ptr<KukaFRIdriver> FRIdriverP_;
boost::shared_ptr<KukaJAVAdriver> JAVAdriverP_;
Params params_;
};
}}}// namespace grl::robot::arm
#endif
<|endoftext|> |
<commit_before>#ifndef __GT_UTILS_SINGLETONS_HPP__
#define __GT_UTILS_SINGLETONS_HPP__
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @brief Macro for declaring singletons.
*
* Intended to be used like:
*
* <pre>
* class SingletonImplementation {
*
* SINGLETON_DECLARATION(SingletonImplementation)
*
* public:
* SingletonImplementation& getInstance();
*
* private:
* SingletonImplementation();
*
* SingletonImplementation(const SingletonImplementation*);
*
* ~SingletonImplementation();
* };
* </pre>
*
* @param SINGLETON_NAME name of declared singleton
*/
#define SINGLETON_DECLARATION(SINGLETON_NAME) \
static std::unique_ptr<SINGLETON_NAME, void (*)(SINGLETON_NAME*)> instance; \
\
static void deleter( \
SINGLETON_NAME* singleton \
);
/**
* @brief Macro for defining singletons.
*
* Intended to be used like:
*
* <pre>
* // class SingletonImplementation {
*
* SINGLETON_DEFINITION(SingletonImplementation, getInstance)
*
* // public:
*
* // methods implementations
*
* // private:
*
* SingletonImplementation::SingletonImplementation() {}
*
* SingletonImplementation::~SingletonImplementation() {}
*
* // }
* </pre>
*
* @param SINGLETON_NAME name of defined singleton
* @param GET_INSTANCE_NAME name of getInstance method
* @param MUTEX_NAME name of mutex to generate
*/
#define SINGLETON_DEFINITION(SINGLETON_NAME,GET_INSTANCE_NAME,MUTEX_NAME) \
boost::mutex MUTEX_NAME; \
\
std::unique_ptr<SINGLETON_NAME, void (*)(SINGLETON_NAME*)> \
SINGLETON_NAME::instance(nullptr, &deleter); \
\
SINGLETON_NAME& SINGLETON_NAME::GET_INSTANCE_NAME() { \
if (!instance) { \
boost::mutex::scoped_lock lock(MUTEX_NAME); \
if (!instance) \
instance = decltype(instance)(new SINGLETON_NAME(), &deleter); \
} \
return *instance; \
} \
\
void SINGLETON_NAME::deleter( \
SINGLETON_NAME* singleton \
) { \
delete singleton; \
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif /* #define __GT_UTILS_SINGLETONS_HPP__ */
<commit_msg>* Sightly improved utils documentation.<commit_after>#ifndef __GT_UTILS_SINGLETONS_HPP__
#define __GT_UTILS_SINGLETONS_HPP__
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @brief Macro for declaring singletons.
*
* <p>Intended to be used like:</p>
*
* <p><pre>
* class SingletonImplementation {
*
* SINGLETON_DECLARATION(SingletonImplementation)
*
* public:
* SingletonImplementation& getInstance();
*
* private:
* SingletonImplementation();
*
* SingletonImplementation(const SingletonImplementation*);
*
* ~SingletonImplementation();
* };
* </pre></p>
*
* @param SINGLETON_NAME name of declared singleton
*/
#define SINGLETON_DECLARATION(SINGLETON_NAME) \
static std::unique_ptr<SINGLETON_NAME, void (*)(SINGLETON_NAME*)> instance; \
\
static void deleter( \
SINGLETON_NAME* singleton \
);
/**
* @brief Macro for defining singletons.
*
* <p>Intended to be used like:</p>
*
* <p><pre>
* // class SingletonImplementation {
*
* SINGLETON_DEFINITION(SingletonImplementation, getInstance)
*
* // public:
*
* // methods implementations
*
* // private:
*
* SingletonImplementation::SingletonImplementation() {}
*
* SingletonImplementation::~SingletonImplementation() {}
*
* // }
* </pre></p>
*
* @param SINGLETON_NAME name of defined singleton
* @param GET_INSTANCE_NAME name of getInstance method
* @param MUTEX_NAME name of mutex to generate
*/
#define SINGLETON_DEFINITION(SINGLETON_NAME,GET_INSTANCE_NAME,MUTEX_NAME) \
boost::mutex MUTEX_NAME; \
\
std::unique_ptr<SINGLETON_NAME, void (*)(SINGLETON_NAME*)> \
SINGLETON_NAME::instance(nullptr, &deleter); \
\
SINGLETON_NAME& SINGLETON_NAME::GET_INSTANCE_NAME() { \
if (!instance) { \
boost::mutex::scoped_lock lock(MUTEX_NAME); \
if (!instance) \
instance = decltype(instance)(new SINGLETON_NAME(), &deleter); \
} \
return *instance; \
} \
\
void SINGLETON_NAME::deleter( \
SINGLETON_NAME* singleton \
) { \
delete singleton; \
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif /* #define __GT_UTILS_SINGLETONS_HPP__ */
<|endoftext|> |
<commit_before>#include <Bindings/Bindings.hpp>
#include <Scene/Scene.hpp>
#include <Script/GameObject.hpp>
#include <Script/GlobalState.hpp>
#include <Script/ViliLuaBridge.hpp>
#include <System/Loaders.hpp>
#include <Transform/UnitVector.hpp>
#include <Transform/Units.hpp>
#include <Triggers/Trigger.hpp>
#include <Triggers/TriggerDatabase.hpp>
#include <Utils/StringUtils.hpp>
#define GAMEOBJECTENV ScriptEngine["__ENVIRONMENTS"][m_envIndex]
namespace obe::Script
{
/*kaguya::LuaTable GameObject::access(kaguya::State* lua) const
{
return (*m_objectScript)["Object"];
}*/
unsigned GameObject::getEnvIndex() const
{
return m_envIndex;
}
kaguya::LuaTable GameObject::access() const
{
return GAMEOBJECTENV["Object"];
}
kaguya::LuaFunction GameObject::getConstructor() const
{
return GAMEOBJECTENV["ObjectInit"];
}
vili::ViliParser GameObjectDatabase::allDefinitions;
vili::ViliParser GameObjectDatabase::allRequires;
vili::ComplexNode*
GameObjectDatabase::GetRequirementsForGameObject(const std::string& type)
{
if (!allRequires.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/")
.add(type)
.add(type + ".obj.vili")
.load(System::Loaders::dataLoader, getGameObjectFile);
if (getGameObjectFile->contains("Requires"))
{
vili::ComplexNode& requiresData =
getGameObjectFile.at<vili::ComplexNode>("Requires");
getGameObjectFile->extractElement(
&getGameObjectFile.at<vili::ComplexNode>("Requires"));
requiresData.setId(type);
allRequires->pushComplexNode(&requiresData);
return &requiresData;
}
return nullptr;
}
return &allRequires.at(type);
}
vili::ComplexNode*
GameObjectDatabase::GetDefinitionForGameObject(const std::string& type)
{
if (!allDefinitions.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/")
.add(type)
.add(type + ".obj.vili")
.load(System::Loaders::dataLoader, getGameObjectFile);
if (getGameObjectFile->contains(type))
{
vili::ComplexNode& definitionData =
getGameObjectFile.at<vili::ComplexNode>(type);
getGameObjectFile->extractElement(
&getGameObjectFile.at<vili::ComplexNode>(type));
definitionData.setId(type);
allDefinitions->pushComplexNode(&definitionData);
return &definitionData;
}
aube::ErrorHandler::Raise(
"ObEngine.Script.GameObjectDatabase.ObjectDefinitionNotFound",
{{"objectType", type}});
return nullptr;
}
return &allDefinitions.at(type);
}
void GameObjectDatabase::ApplyRequirements(GameObject* obj,
vili::ComplexNode& requires)
{
for (vili::Node* currentRequirement : requires.getAll())
{
kaguya::LuaTable requireTable =
ScriptEngine["__ENVIRONMENTS"][obj->getEnvIndex()]["LuaCore"]
["ObjectInitInjectionTable"];
DataBridge::dataToLua(requireTable, currentRequirement);
}
}
// GameObject
std::vector<unsigned int> GameObject::AllEnvs;
GameObject::GameObject(const std::string& type, const std::string& id)
: Identifiable(id), m_localTriggers(nullptr)
{
m_type = type;
}
void GameObject::initialize()
{
if (!m_active)
{
Debug::Log->debug(
"<GameObject> Initialising GameObject '{0}' ({1}) [Env={2}]",
m_id, m_type, m_envIndex);
m_active = true;
GAMEOBJECTENV["__OBJECT_INIT"] = true;
m_localTriggers->trigger("Init");
}
else
Debug::Log->warn("<GameObject> GameObject '{0}' ({1}) has already "
"been initialised",
m_id, m_type);
}
GameObject::~GameObject()
{
Debug::Log->debug("<GameObject> Deleting GameObject '{0}' ({1})", m_id,
m_type);
this->deleteObject();
AllEnvs.erase(std::remove_if(AllEnvs.begin(), AllEnvs.end(),
[this](const unsigned int& envIndex) {
return envIndex == m_envIndex;
}),
AllEnvs.end());
if (m_hasScriptEngine)
{
m_localTriggers.reset();
Triggers::TriggerDatabase::GetInstance()->removeNamespace(
m_privateKey);
}
}
void GameObject::sendInitArgFromLua(const std::string& argName,
kaguya::LuaRef value) const
{
Debug::Log->debug("<GameObject> Sending Local.Init argument {0} to "
"GameObject {1} ({2}) (From Lua)",
argName, m_id, m_type);
m_localTriggers->pushParameterFromLua("Init", argName, value);
}
void GameObject::registerTrigger(std::weak_ptr<Triggers::Trigger> trg,
const std::string& callbackName)
{
m_registeredTriggers.emplace_back(trg, callbackName);
}
void GameObject::loadGameObject(Scene::Scene& world, vili::ComplexNode& obj)
{
Debug::Log->debug("<GameObject> Loading GameObject '{0}' ({1})", m_id,
m_type);
// Script
if (obj.contains(vili::NodeType::DataNode, "permanent"))
{
m_permanent = obj.getDataNode("permanent").get<bool>();
}
if (obj.contains(vili::NodeType::ComplexNode, "Script"))
{
m_hasScriptEngine = true;
m_privateKey =
Utils::String::getRandomKey(Utils::String::Alphabet, 1) +
Utils::String::getRandomKey(
Utils::String::Alphabet + Utils::String::Numbers, 11);
Triggers::TriggerDatabase::GetInstance()->createNamespace(
m_privateKey);
m_localTriggers.reset(
Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(
m_privateKey, "Local"),
Triggers::TriggerGroupPtrRemover);
m_envIndex = CreateNewEnvironment();
Debug::Log->trace(
"<GameObject> GameObject '{}' received Environment ID {}", m_id,
m_envIndex);
AllEnvs.push_back(m_envIndex);
GAMEOBJECTENV["This"] = this;
m_localTriggers->addTrigger("Init")->addTrigger("Delete");
GAMEOBJECTENV["__OBJECT_TYPE"] = m_type;
GAMEOBJECTENV["__OBJECT_ID"] = m_id;
GAMEOBJECTENV["__OBJECT_INIT"] = false;
GAMEOBJECTENV["Private"] = m_privateKey;
executeFile(m_envIndex,
System::Path("Lib/Internal/ObjectInit.lua").find());
if (obj.at("Script").contains(vili::NodeType::DataNode, "source"))
{
const std::string getScrName =
obj.at("Script").getDataNode("source").get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
else if (obj.at("Script").contains(vili::NodeType::ArrayNode,
"sources"))
{
const int scriptListSize =
obj.at("Script").getArrayNode("sources").size();
for (int i = 0; i < scriptListSize; i++)
{
const std::string getScrName = obj.at("Script")
.getArrayNode("sources")
.get(i)
.get<std::string>();
executeFile(m_envIndex, System::Path(getScrName).find());
}
}
}
if (obj.contains(vili::NodeType::ComplexNode, "Animator"))
{
m_objectAnimator = std::make_unique<Animation::Animator>();
const std::string animatorPath =
obj.at("Animator").getDataNode("path").get<std::string>();
if (animatorPath != "")
{
m_objectAnimator->setPath(animatorPath);
m_objectAnimator->loadAnimator();
}
if (obj.at("Animator")
.contains(vili::NodeType::DataNode, "default"))
{
m_objectAnimator->setKey(obj.at("Animator")
.getDataNode("default")
.get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Animation"] = m_objectAnimator.get();
m_hasAnimator = true;
}
// Collider
if (obj.contains(vili::NodeType::ComplexNode, "Collider"))
{
m_objectCollider = world.createCollider(m_id, false);
m_objectNode.addChild(m_objectCollider);
m_objectCollider->load(obj.at("Collider"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Collider"] = m_objectCollider;
m_hasCollider = true;
}
// LevelSprite
if (obj.contains(vili::NodeType::ComplexNode, "LevelSprite"))
{
m_objectLevelSprite = world.createLevelSprite(m_id, false);
m_objectNode.addChild(m_objectLevelSprite);
m_objectLevelSprite->load(obj.at("LevelSprite"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["LevelSprite"] = m_objectLevelSprite;
m_hasLevelSprite = true;
world.reorganizeLayers();
}
}
void GameObject::update()
{
if (m_canUpdate)
{
if (m_active)
{
if (m_hasAnimator)
{
if (m_objectAnimator->getKey() != "")
m_objectAnimator->update();
if (m_hasLevelSprite)
{
m_objectLevelSprite->setTexture(
m_objectAnimator->getTexture());
}
}
}
else
{
this->initialize();
}
}
}
std::string GameObject::getType() const
{
return m_type;
}
bool GameObject::doesHaveAnimator() const
{
return m_hasAnimator;
}
bool GameObject::doesHaveCollider() const
{
return m_hasCollider;
}
bool GameObject::doesHaveLevelSprite() const
{
return m_hasLevelSprite;
}
bool GameObject::doesHaveScriptEngine() const
{
return m_hasScriptEngine;
}
bool GameObject::getUpdateState() const
{
return m_canUpdate;
}
void GameObject::setUpdateState(bool state)
{
m_canUpdate = state;
}
Graphics::LevelSprite* GameObject::getLevelSprite()
{
if (m_hasLevelSprite)
return m_objectLevelSprite;
throw aube::ErrorHandler::Raise(
"ObEngine.Script.GameObject.NoLevelSprite", {{"id", m_id}});
}
Scene::SceneNode* GameObject::getSceneNode()
{
return &m_objectNode;
}
Collision::PolygonalCollider* GameObject::getCollider()
{
if (m_hasCollider)
return m_objectCollider;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoCollider",
{{"id", m_id}});
}
Animation::Animator* GameObject::getAnimator()
{
if (m_hasAnimator)
return m_objectAnimator.get();
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoAnimator",
{{"id", m_id}});
}
void GameObject::useTrigger(const std::string& trNsp,
const std::string& trGrp,
const std::string& trName,
const std::string& callAlias)
{
if (trName == "*")
{
std::vector<std::string> allTrg =
Triggers::TriggerDatabase::GetInstance()
->getAllTriggersNameFromTriggerGroup(trNsp, trGrp);
for (const std::string& triggerName : allTrg)
{
this->useTrigger(
trNsp, trGrp, triggerName,
(Utils::String::occurencesInString(callAlias, "*")
? Utils::String::replace(callAlias, "*", triggerName)
: ""));
}
}
else
{
bool triggerNotFound = true;
for (auto& triggerPair : m_registeredTriggers)
{
if (triggerPair.first.lock() ==
Triggers::TriggerDatabase::GetInstance()->getTrigger(
trNsp, trGrp, trName).lock())
{
triggerNotFound = false;
}
}
if (triggerNotFound)
{
const std::string callbackName =
(callAlias.empty()) ? trNsp + "." + trGrp + "." + trName
: callAlias;
this->registerTrigger(
Triggers::TriggerDatabase::GetInstance()->getTrigger(
trNsp, trGrp, trName),
callbackName);
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName).lock()
->registerEnvironment(m_envIndex, callbackName, &m_active);
}
else
{
const std::string callbackName =
(callAlias.empty()) ? trNsp + "." + trGrp + "." + trName
: callAlias;
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName).lock()
->unregisterEnvironment(m_envIndex);
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName).lock()
->registerEnvironment(m_envIndex, callbackName, &m_active);
}
}
}
void GameObject::removeTrigger(const std::string& trNsp,
const std::string& trGrp,
const std::string& trName) const
{
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName).lock()
->unregisterEnvironment(m_envIndex);
}
void GameObject::exec(const std::string& query) const
{
executeString(m_envIndex, query);
}
void GameObject::deleteObject()
{
Debug::Log->debug("GameObject::deleteObject called for '{0}' ({1})",
m_id, m_type);
m_localTriggers->trigger("Delete");
this->deletable = true;
m_active = false;
for (auto& triggerRef : m_registeredTriggers)
{
if (auto trigger = triggerRef.first.lock())
{
trigger->unregisterEnvironment(m_envIndex);
}
}
// GAMEOBJECTENV = nullptr;
}
void GameObject::setPermanent(bool permanent)
{
m_permanent = permanent;
}
bool GameObject::isPermanent() const
{
return m_permanent;
}
void GameObject::setState(bool state)
{
m_active = state;
}
} // namespace obe::Script<commit_msg>Added meaningful error when source not found in GameObject<commit_after>#include <Bindings/Bindings.hpp>
#include <Scene/Scene.hpp>
#include <Script/GameObject.hpp>
#include <Script/GlobalState.hpp>
#include <Script/ViliLuaBridge.hpp>
#include <System/Loaders.hpp>
#include <Transform/UnitVector.hpp>
#include <Transform/Units.hpp>
#include <Triggers/Trigger.hpp>
#include <Triggers/TriggerDatabase.hpp>
#include <Utils/StringUtils.hpp>
#define GAMEOBJECTENV ScriptEngine["__ENVIRONMENTS"][m_envIndex]
namespace obe::Script
{
/*kaguya::LuaTable GameObject::access(kaguya::State* lua) const
{
return (*m_objectScript)["Object"];
}*/
unsigned GameObject::getEnvIndex() const
{
return m_envIndex;
}
kaguya::LuaTable GameObject::access() const
{
return GAMEOBJECTENV["Object"];
}
kaguya::LuaFunction GameObject::getConstructor() const
{
return GAMEOBJECTENV["ObjectInit"];
}
vili::ViliParser GameObjectDatabase::allDefinitions;
vili::ViliParser GameObjectDatabase::allRequires;
vili::ComplexNode*
GameObjectDatabase::GetRequirementsForGameObject(const std::string& type)
{
if (!allRequires.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/")
.add(type)
.add(type + ".obj.vili")
.load(System::Loaders::dataLoader, getGameObjectFile);
if (getGameObjectFile->contains("Requires"))
{
vili::ComplexNode& requiresData =
getGameObjectFile.at<vili::ComplexNode>("Requires");
getGameObjectFile->extractElement(
&getGameObjectFile.at<vili::ComplexNode>("Requires"));
requiresData.setId(type);
allRequires->pushComplexNode(&requiresData);
return &requiresData;
}
return nullptr;
}
return &allRequires.at(type);
}
vili::ComplexNode*
GameObjectDatabase::GetDefinitionForGameObject(const std::string& type)
{
if (!allDefinitions.root().contains(type))
{
vili::ViliParser getGameObjectFile;
System::Path("Data/GameObjects/")
.add(type)
.add(type + ".obj.vili")
.load(System::Loaders::dataLoader, getGameObjectFile);
if (getGameObjectFile->contains(type))
{
vili::ComplexNode& definitionData =
getGameObjectFile.at<vili::ComplexNode>(type);
getGameObjectFile->extractElement(
&getGameObjectFile.at<vili::ComplexNode>(type));
definitionData.setId(type);
allDefinitions->pushComplexNode(&definitionData);
return &definitionData;
}
aube::ErrorHandler::Raise(
"ObEngine.Script.GameObjectDatabase.ObjectDefinitionNotFound",
{{"objectType", type}});
return nullptr;
}
return &allDefinitions.at(type);
}
void GameObjectDatabase::ApplyRequirements(GameObject* obj,
vili::ComplexNode& requires)
{
for (vili::Node* currentRequirement : requires.getAll())
{
kaguya::LuaTable requireTable =
ScriptEngine["__ENVIRONMENTS"][obj->getEnvIndex()]["LuaCore"]
["ObjectInitInjectionTable"];
DataBridge::dataToLua(requireTable, currentRequirement);
}
}
// GameObject
std::vector<unsigned int> GameObject::AllEnvs;
GameObject::GameObject(const std::string& type, const std::string& id)
: Identifiable(id), m_localTriggers(nullptr)
{
m_type = type;
}
void GameObject::initialize()
{
if (!m_active)
{
Debug::Log->debug(
"<GameObject> Initialising GameObject '{0}' ({1}) [Env={2}]",
m_id, m_type, m_envIndex);
m_active = true;
GAMEOBJECTENV["__OBJECT_INIT"] = true;
m_localTriggers->trigger("Init");
}
else
Debug::Log->warn("<GameObject> GameObject '{0}' ({1}) has already "
"been initialised",
m_id, m_type);
}
GameObject::~GameObject()
{
Debug::Log->debug("<GameObject> Deleting GameObject '{0}' ({1})", m_id,
m_type);
this->deleteObject();
AllEnvs.erase(std::remove_if(AllEnvs.begin(), AllEnvs.end(),
[this](const unsigned int& envIndex) {
return envIndex == m_envIndex;
}),
AllEnvs.end());
if (m_hasScriptEngine)
{
m_localTriggers.reset();
Triggers::TriggerDatabase::GetInstance()->removeNamespace(
m_privateKey);
}
}
void GameObject::sendInitArgFromLua(const std::string& argName,
kaguya::LuaRef value) const
{
Debug::Log->debug("<GameObject> Sending Local.Init argument {0} to "
"GameObject {1} ({2}) (From Lua)",
argName, m_id, m_type);
m_localTriggers->pushParameterFromLua("Init", argName, value);
}
void GameObject::registerTrigger(std::weak_ptr<Triggers::Trigger> trg,
const std::string& callbackName)
{
m_registeredTriggers.emplace_back(trg, callbackName);
}
void GameObject::loadGameObject(Scene::Scene& world, vili::ComplexNode& obj)
{
Debug::Log->debug("<GameObject> Loading GameObject '{0}' ({1})", m_id,
m_type);
// Script
if (obj.contains(vili::NodeType::DataNode, "permanent"))
{
m_permanent = obj.getDataNode("permanent").get<bool>();
}
if (obj.contains(vili::NodeType::ComplexNode, "Script"))
{
m_hasScriptEngine = true;
m_privateKey =
Utils::String::getRandomKey(Utils::String::Alphabet, 1) +
Utils::String::getRandomKey(
Utils::String::Alphabet + Utils::String::Numbers, 11);
Triggers::TriggerDatabase::GetInstance()->createNamespace(
m_privateKey);
m_localTriggers.reset(
Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(
m_privateKey, "Local"),
Triggers::TriggerGroupPtrRemover);
m_envIndex = CreateNewEnvironment();
Debug::Log->trace(
"<GameObject> GameObject '{}' received Environment ID {}", m_id,
m_envIndex);
AllEnvs.push_back(m_envIndex);
GAMEOBJECTENV["This"] = this;
m_localTriggers->addTrigger("Init")->addTrigger("Delete");
GAMEOBJECTENV["__OBJECT_TYPE"] = m_type;
GAMEOBJECTENV["__OBJECT_ID"] = m_id;
GAMEOBJECTENV["__OBJECT_INIT"] = false;
GAMEOBJECTENV["Private"] = m_privateKey;
executeFile(m_envIndex,
System::Path("Lib/Internal/ObjectInit.lua").find());
auto loadSource = [&](const std::string& path) {
const std::string fullPath = System::Path(path).find();
if (fullPath.empty())
{
throw aube::ErrorHandler::Raise(
"obe.Script.GameObject.ScriptFileNotFound",
{{"source", path}});
}
executeFile(m_envIndex, fullPath);
};
if (obj.at("Script").contains(vili::NodeType::DataNode, "source"))
{
loadSource(
obj.at("Script").getDataNode("source").get<std::string>());
}
else if (obj.at("Script").contains(vili::NodeType::ArrayNode,
"sources"))
{
const int scriptListSize =
obj.at("Script").getArrayNode("sources").size();
for (int i = 0; i < scriptListSize; i++)
{
loadSource(obj.at("Script")
.getArrayNode("sources")
.get(i)
.get<std::string>());
}
}
}
if (obj.contains(vili::NodeType::ComplexNode, "Animator"))
{
m_objectAnimator = std::make_unique<Animation::Animator>();
const std::string animatorPath =
obj.at("Animator").getDataNode("path").get<std::string>();
if (animatorPath != "")
{
m_objectAnimator->setPath(animatorPath);
m_objectAnimator->loadAnimator();
}
if (obj.at("Animator")
.contains(vili::NodeType::DataNode, "default"))
{
m_objectAnimator->setKey(obj.at("Animator")
.getDataNode("default")
.get<std::string>());
}
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Animation"] = m_objectAnimator.get();
m_hasAnimator = true;
}
// Collider
if (obj.contains(vili::NodeType::ComplexNode, "Collider"))
{
m_objectCollider = world.createCollider(m_id, false);
m_objectNode.addChild(m_objectCollider);
m_objectCollider->load(obj.at("Collider"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["Collider"] = m_objectCollider;
m_hasCollider = true;
}
// LevelSprite
if (obj.contains(vili::NodeType::ComplexNode, "LevelSprite"))
{
m_objectLevelSprite = world.createLevelSprite(m_id, false);
m_objectNode.addChild(m_objectLevelSprite);
m_objectLevelSprite->load(obj.at("LevelSprite"));
if (m_hasScriptEngine)
GAMEOBJECTENV["Object"]["LevelSprite"] = m_objectLevelSprite;
m_hasLevelSprite = true;
world.reorganizeLayers();
}
}
void GameObject::update()
{
if (m_canUpdate)
{
if (m_active)
{
if (m_hasAnimator)
{
if (m_objectAnimator->getKey() != "")
m_objectAnimator->update();
if (m_hasLevelSprite)
{
m_objectLevelSprite->setTexture(
m_objectAnimator->getTexture());
}
}
}
else
{
this->initialize();
}
}
}
std::string GameObject::getType() const
{
return m_type;
}
bool GameObject::doesHaveAnimator() const
{
return m_hasAnimator;
}
bool GameObject::doesHaveCollider() const
{
return m_hasCollider;
}
bool GameObject::doesHaveLevelSprite() const
{
return m_hasLevelSprite;
}
bool GameObject::doesHaveScriptEngine() const
{
return m_hasScriptEngine;
}
bool GameObject::getUpdateState() const
{
return m_canUpdate;
}
void GameObject::setUpdateState(bool state)
{
m_canUpdate = state;
}
Graphics::LevelSprite* GameObject::getLevelSprite()
{
if (m_hasLevelSprite)
return m_objectLevelSprite;
throw aube::ErrorHandler::Raise(
"ObEngine.Script.GameObject.NoLevelSprite", {{"id", m_id}});
}
Scene::SceneNode* GameObject::getSceneNode()
{
return &m_objectNode;
}
Collision::PolygonalCollider* GameObject::getCollider()
{
if (m_hasCollider)
return m_objectCollider;
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoCollider",
{{"id", m_id}});
}
Animation::Animator* GameObject::getAnimator()
{
if (m_hasAnimator)
return m_objectAnimator.get();
throw aube::ErrorHandler::Raise("ObEngine.Script.GameObject.NoAnimator",
{{"id", m_id}});
}
void GameObject::useTrigger(const std::string& trNsp,
const std::string& trGrp,
const std::string& trName,
const std::string& callAlias)
{
if (trName == "*")
{
std::vector<std::string> allTrg =
Triggers::TriggerDatabase::GetInstance()
->getAllTriggersNameFromTriggerGroup(trNsp, trGrp);
for (const std::string& triggerName : allTrg)
{
this->useTrigger(
trNsp, trGrp, triggerName,
(Utils::String::occurencesInString(callAlias, "*")
? Utils::String::replace(callAlias, "*", triggerName)
: ""));
}
}
else
{
bool triggerNotFound = true;
for (auto& triggerPair : m_registeredTriggers)
{
if (triggerPair.first.lock() ==
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName)
.lock())
{
triggerNotFound = false;
}
}
if (triggerNotFound)
{
const std::string callbackName =
(callAlias.empty()) ? trNsp + "." + trGrp + "." + trName
: callAlias;
this->registerTrigger(
Triggers::TriggerDatabase::GetInstance()->getTrigger(
trNsp, trGrp, trName),
callbackName);
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName)
.lock()
->registerEnvironment(m_envIndex, callbackName, &m_active);
}
else
{
const std::string callbackName =
(callAlias.empty()) ? trNsp + "." + trGrp + "." + trName
: callAlias;
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName)
.lock()
->unregisterEnvironment(m_envIndex);
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName)
.lock()
->registerEnvironment(m_envIndex, callbackName, &m_active);
}
}
}
void GameObject::removeTrigger(const std::string& trNsp,
const std::string& trGrp,
const std::string& trName) const
{
Triggers::TriggerDatabase::GetInstance()
->getTrigger(trNsp, trGrp, trName)
.lock()
->unregisterEnvironment(m_envIndex);
}
void GameObject::exec(const std::string& query) const
{
executeString(m_envIndex, query);
}
void GameObject::deleteObject()
{
Debug::Log->debug("GameObject::deleteObject called for '{0}' ({1})",
m_id, m_type);
m_localTriggers->trigger("Delete");
this->deletable = true;
m_active = false;
for (auto& triggerRef : m_registeredTriggers)
{
if (auto trigger = triggerRef.first.lock())
{
trigger->unregisterEnvironment(m_envIndex);
}
}
// GAMEOBJECTENV = nullptr;
}
void GameObject::setPermanent(bool permanent)
{
m_permanent = permanent;
}
bool GameObject::isPermanent() const
{
return m_permanent;
}
void GameObject::setState(bool state)
{
m_active = state;
}
} // namespace obe::Script<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (c) 2010 David Malone <dwmalone@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#pragma once
#include <vector>
namespace seastar {
using rss_key_type = compat::basic_string_view<uint8_t>;
// Mellanox Linux's driver key
static constexpr uint8_t default_rsskey_40bytes[] = {
0xd1, 0x81, 0xc6, 0x2c, 0xf7, 0xf4, 0xdb, 0x5b,
0x19, 0x83, 0xa2, 0xfc, 0x94, 0x3e, 0x1a, 0xdb,
0xd9, 0x38, 0x9e, 0x6b, 0xd1, 0x03, 0x9c, 0x2c,
0xa7, 0x44, 0x99, 0xad, 0x59, 0x3d, 0x56, 0xd9,
0xf3, 0x25, 0x3c, 0x06, 0x2a, 0xdc, 0x1f, 0xfc
};
// Intel's i40e PMD default RSS key
static constexpr uint8_t default_rsskey_52bytes[] = {
0x44, 0x39, 0x79, 0x6b, 0xb5, 0x4c, 0x50, 0x23,
0xb6, 0x75, 0xea, 0x5b, 0x12, 0x4f, 0x9f, 0x30,
0xb8, 0xa2, 0xc0, 0x3d, 0xdf, 0xdc, 0x4d, 0x02,
0xa0, 0x8c, 0x9b, 0x33, 0x4a, 0xf6, 0x4a, 0x4c,
0x05, 0xc6, 0xfa, 0x34, 0x39, 0x58, 0xd8, 0x55,
0x7d, 0x99, 0x58, 0x3a, 0xe1, 0x38, 0xc9, 0x2e,
0x81, 0x15, 0x03, 0x66
};
template<typename T>
static inline uint32_t
toeplitz_hash(rss_key_type key, const T& data)
{
uint32_t hash = 0, v;
u_int i, b;
/* XXXRW: Perhaps an assertion about key length vs. data length? */
v = (key[0]<<24) + (key[1]<<16) + (key[2] <<8) + key[3];
for (i = 0; i < data.size(); i++) {
for (b = 0; b < 8; b++) {
if (data[i] & (1<<(7-b)))
hash ^= v;
v <<= 1;
if ((i + 4) < key.size() &&
(key[i+4] & (1<<(7-b))))
v |= 1;
}
}
return (hash);
}
}
<commit_msg>net: Fix global buffer overflow around rss_key_type<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (c) 2010 David Malone <dwmalone@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#pragma once
#include <vector>
namespace seastar {
using rss_key_type = compat::basic_string_view<uint8_t>;
// Mellanox Linux's driver key
static constexpr uint8_t default_rsskey_40bytes_v[] = {
0xd1, 0x81, 0xc6, 0x2c, 0xf7, 0xf4, 0xdb, 0x5b,
0x19, 0x83, 0xa2, 0xfc, 0x94, 0x3e, 0x1a, 0xdb,
0xd9, 0x38, 0x9e, 0x6b, 0xd1, 0x03, 0x9c, 0x2c,
0xa7, 0x44, 0x99, 0xad, 0x59, 0x3d, 0x56, 0xd9,
0xf3, 0x25, 0x3c, 0x06, 0x2a, 0xdc, 0x1f, 0xfc
};
static constexpr rss_key_type default_rsskey_40bytes{default_rsskey_40bytes_v, sizeof(default_rsskey_40bytes_v)};
// Intel's i40e PMD default RSS key
static constexpr uint8_t default_rsskey_52bytes_v[] = {
0x44, 0x39, 0x79, 0x6b, 0xb5, 0x4c, 0x50, 0x23,
0xb6, 0x75, 0xea, 0x5b, 0x12, 0x4f, 0x9f, 0x30,
0xb8, 0xa2, 0xc0, 0x3d, 0xdf, 0xdc, 0x4d, 0x02,
0xa0, 0x8c, 0x9b, 0x33, 0x4a, 0xf6, 0x4a, 0x4c,
0x05, 0xc6, 0xfa, 0x34, 0x39, 0x58, 0xd8, 0x55,
0x7d, 0x99, 0x58, 0x3a, 0xe1, 0x38, 0xc9, 0x2e,
0x81, 0x15, 0x03, 0x66
};
static constexpr rss_key_type default_rsskey_52bytes{default_rsskey_52bytes_v, sizeof(default_rsskey_52bytes_v)};
template<typename T>
static inline uint32_t
toeplitz_hash(rss_key_type key, const T& data)
{
uint32_t hash = 0, v;
u_int i, b;
/* XXXRW: Perhaps an assertion about key length vs. data length? */
v = (key[0]<<24) + (key[1]<<16) + (key[2] <<8) + key[3];
for (i = 0; i < data.size(); i++) {
for (b = 0; b < 8; b++) {
if (data[i] & (1<<(7-b)))
hash ^= v;
v <<= 1;
if ((i + 4) < key.size() &&
(key[i+4] & (1<<(7-b))))
v |= 1;
}
}
return (hash);
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dgladbinterface.h"
#include <QMessageBox>
#include <stdexcept>
namespace {
class DGLConnectOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>&) override {
const char* pattern = "connected to ";
if (input.size() && input[0].substr(0, strlen(pattern)) == pattern) {
return true;
} else {
return false;
}
}
};
class DGLEmptyOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>&) override {
for (size_t i = 0; i < input.size(); i++) {
if (input[i].size()) {
return false;
}
}
return true;
}
};
class DGLDeviceOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>& output) override {
if (!input.size() || input[0] != "List of devices attached ") {
return false;
}
for (size_t i = 1; i < input.size(); i++) {
if (!input[i].size()) {
continue;
}
size_t pos = input[i].find('\t');
if (pos != std::string::npos && pos > 0) {
output.push_back(input[i].substr(0, pos));
} else {
output.push_back(input[i]);
}
}
return true;
}
};
}
DGLAdbHandler::~DGLAdbHandler() {
std::set<DGLAdbCookie*>::iterator i = m_RefCookies.begin();
while (i != m_RefCookies.end()) {
delete *(i++);
}
}
void DGLAdbHandler::refCookie(DGLAdbCookie* cookie) {
m_RefCookies.insert(cookie);
}
void DGLAdbHandler::unrefCookie(DGLAdbCookie* cookie) {
m_RefCookies.erase(cookie);
}
DGLAdbCookie::DGLAdbCookie(DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter)
: m_OutputFilter(filter), m_Handler(handler)
, m_DelayTimer(nullptr) {
m_Handler->refCookie(this);
}
DGLAdbCookie::~DGLAdbCookie() {
m_Handler->unrefCookie(this);
if (m_DelayTimer) {
delete m_DelayTimer;
}
}
void DGLAdbCookie::filterOutput(const std::vector<std::string>& lines) {
if (m_OutputFilter.get()) {
std::vector<std::string> filteredLines;
if (m_OutputFilter->filter(lines, filteredLines)) {
onDone(filteredLines);
} else {
std::ostringstream msg;
msg << "Cannot parse adb output: " << std::endl;
for (size_t i = 0; i < lines.size(); i++) {
msg << lines[i] << std::endl;
}
onFailed(msg.str());
}
} else {
onDone(lines);
}
}
void DGLAdbCookie::onDone(const std::vector<std::string>& data) {
m_Handler->done(data);
}
void DGLAdbCookie::processAfterDelay(int msec) {
if (!m_DelayTimer) {
m_DelayTimer = new QTimer();
m_DelayTimer->setSingleShot(true);
}
m_DelayTimer->setInterval(msec);
CONNASSERT(m_DelayTimer, SIGNAL(timeout()), this, SLOT(process()));
m_DelayTimer->start();
}
void DGLAdbCookie::onFailed(const std::string& reason) { m_Handler->failed(reason); }
DGLAdbCookieImpl::DGLAdbCookieImpl(const std::string& adbPath,
const std::vector<std::string>& params,
DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter)
: DGLAdbCookie(handler, filter), m_adbPath(adbPath), m_params(params), m_Deleted(false) {
m_process = new DGLBaseQTProcess();
m_process->setParent(this);
CONNASSERT(m_process->getProcess(),
SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(handleProcessFinished(int, QProcess::ExitStatus)));
CONNASSERT(m_process->getProcess(), SIGNAL(error(QProcess::ProcessError)),
this, SLOT(handleProcessError(QProcess::ProcessError)));
}
void DGLAdbCookieImpl::process() {
if (!m_adbPath.size()) {
onFailed(tr(
"ADB path is not set, go to Tools->Configuration->Android to "
"set it.").toStdString());
} else {
m_process->run(m_adbPath, "", m_params,
m_OutputFilter.get() != nullptr);
}
}
void DGLAdbCookieImpl::handleProcessError(QProcess::ProcessError) {
onFailed(m_process->getProcess()->errorString().toStdString());
if (!m_Deleted) {
m_Deleted = true;
disconnect();
deleteLater();
}
}
void DGLAdbCookieImpl::handleProcessFinished(int code,
QProcess::ExitStatus status) {
if (status == QProcess::NormalExit) {
QProcess* process = m_process->getProcess();
QByteArray qData = process->readAllStandardError();
qData.append(process->readAllStandardOutput());
QList<QByteArray> qLines = qData.split('\n');
std::vector<std::string> lines;
bool suException = false;
foreach(QByteArray qLine, qLines) {
// skip adb server startup messages.
if (qLine[0] == '*') {
if (qLine.contains("daemon not running")) {
continue;
}
if (qLine.contains("daemon started successfully")) {
continue;
}
}
// skip ChainsDD su non-fatal exception ant it's stacktrace
if (suException) {
if (qLine.contains("at ") ||
qLine.contains("Can't connect to activity manager")) {
continue;
}
suException = false;
} else {
if (qLine.contains("Error type 2")) {
suException = true;
continue;
}
}
lines.push_back(
QString(qLine.replace("\r", QByteArray())).toStdString());
}
if (code) {
if (lines[0].find("error:") == 0) {
onFailed(lines[0]);
} else {
std::ostringstream msg;
msg << "Adb process exit code :" << code << ":" << std::endl;
msg << QString(m_process->getProcess()->readAll())
.toStdString();
onFailed(msg.str());
}
} else {
// success
filterOutput(lines);
}
} else {
onFailed("ADB process crashed");
}
if (!m_Deleted) {
m_Deleted = true;
disconnect();
deleteLater();
}
}
DGLAdbCookieFactory::DGLAdbCookieFactory(const std::string& adbPath)
: m_adbPath(adbPath) {}
const std::string& DGLAdbCookieFactory::getAdbPath() { return m_adbPath; }
DGLAdbCookie* DGLAdbCookieFactory::CreateCookie(
const std::vector<std::string>& params, DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter) {
return new DGLAdbCookieImpl(m_adbPath, params, handler, filter);
}
DGLAdbInterface* DGLAdbInterface::get() {
if (!s_self) {
s_self = std::make_shared<DGLAdbInterface>();
}
return s_self.get();
}
void DGLAdbInterface::setAdbCookieFactory(
std::shared_ptr<DGLAdbCookieFactoryBase> factory) {
m_factory = factory;
}
const std::string DGLAdbInterface::getAdbPath() const {
DGLAdbCookieFactory* factory =
dynamic_cast<DGLAdbCookieFactory*>(m_factory.get());
if (factory) {
return factory->getAdbPath();
}
return "";
}
std::shared_ptr<DGLAdbInterface> DGLAdbInterface::s_self;
DGLAdbCookie* DGLAdbInterface::killServer(DGLAdbHandler* handler) {
std::vector<std::string> params;
params.push_back("kill-server");
return invokeAdb(params, handler, std::make_shared<DGLEmptyOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::connect(const std::string& address,
DGLAdbHandler* handler) {
std::vector<std::string> params;
params.push_back("connect");
params.push_back(address);
return invokeAdb(params, handler,
std::make_shared<DGLConnectOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::getDevices(DGLAdbHandler* handler) {
std::vector<std::string> params(1, "devices");
return invokeAdb(params, handler,
std::make_shared<DGLDeviceOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::invokeOnDevice(
const std::string& serial, const std::vector<std::string>& params,
DGLAdbHandler* handler, std::shared_ptr<DGLAdbOutputFilter> filter) {
std::vector<std::string> deviceParams(2 + params.size());
deviceParams[0] = "-s";
deviceParams[1] = serial;
std::copy(params.begin(), params.end(), deviceParams.begin() + 2);
DGLAdbCookie* ret = m_factory->CreateCookie(deviceParams, handler, filter);
return ret;
}
DGLAdbCookie* DGLAdbInterface::invokeAdb(
const std::vector<std::string>& params, DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter) {
DGLAdbCookie* ret = m_factory->CreateCookie(params, handler, filter);
return ret;
}
<commit_msg>Android ADB interface: adapt a bit to new adb text output<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dgladbinterface.h"
#include <QMessageBox>
#include <stdexcept>
namespace {
std::string trim(const std::string &str)
{
auto trimmedBegin = std::find_if_not(str.begin(), str.end(), [](int character){return std::isspace(character);});
auto trimmedEnd = std::find_if_not(str.rbegin(),str.rend(),[](int character){return std::isspace(character);}).base();
return (trimmedEnd <= trimmedBegin ? std::string() : std::string(trimmedBegin, trimmedEnd));
}
class DGLConnectOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>&) override {
const char* pattern = "connected to ";
if (input.size() && input[0].substr(0, strlen(pattern)) == pattern) {
return true;
} else {
return false;
}
}
};
class DGLEmptyOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>&) override {
for (size_t i = 0; i < input.size(); i++) {
if (input[i].size()) {
return false;
}
}
return true;
}
};
class DGLDeviceOutputFilter : public DGLAdbOutputFilter {
virtual bool filter(const std::vector<std::string>& input,
std::vector<std::string>& output) override {
if (!input.size() || trim(input[0]) != "List of devices attached") {
return false;
}
for (size_t i = 1; i < input.size(); i++) {
if (!input[i].size()) {
continue;
}
size_t pos = input[i].find('\t');
if (pos != std::string::npos && pos > 0) {
output.push_back(input[i].substr(0, pos));
} else {
output.push_back(input[i]);
}
}
return true;
}
};
}
DGLAdbHandler::~DGLAdbHandler() {
std::set<DGLAdbCookie*>::iterator i = m_RefCookies.begin();
while (i != m_RefCookies.end()) {
delete *(i++);
}
}
void DGLAdbHandler::refCookie(DGLAdbCookie* cookie) {
m_RefCookies.insert(cookie);
}
void DGLAdbHandler::unrefCookie(DGLAdbCookie* cookie) {
m_RefCookies.erase(cookie);
}
DGLAdbCookie::DGLAdbCookie(DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter)
: m_OutputFilter(filter), m_Handler(handler)
, m_DelayTimer(nullptr) {
m_Handler->refCookie(this);
}
DGLAdbCookie::~DGLAdbCookie() {
m_Handler->unrefCookie(this);
if (m_DelayTimer) {
delete m_DelayTimer;
}
}
void DGLAdbCookie::filterOutput(const std::vector<std::string>& lines) {
if (m_OutputFilter.get()) {
std::vector<std::string> filteredLines;
if (m_OutputFilter->filter(lines, filteredLines)) {
onDone(filteredLines);
} else {
std::ostringstream msg;
msg << "Cannot parse adb output: " << std::endl;
for (size_t i = 0; i < lines.size(); i++) {
msg << lines[i] << std::endl;
}
onFailed(msg.str());
}
} else {
onDone(lines);
}
}
void DGLAdbCookie::onDone(const std::vector<std::string>& data) {
m_Handler->done(data);
}
void DGLAdbCookie::processAfterDelay(int msec) {
if (!m_DelayTimer) {
m_DelayTimer = new QTimer();
m_DelayTimer->setSingleShot(true);
}
m_DelayTimer->setInterval(msec);
CONNASSERT(m_DelayTimer, SIGNAL(timeout()), this, SLOT(process()));
m_DelayTimer->start();
}
void DGLAdbCookie::onFailed(const std::string& reason) { m_Handler->failed(reason); }
DGLAdbCookieImpl::DGLAdbCookieImpl(const std::string& adbPath,
const std::vector<std::string>& params,
DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter)
: DGLAdbCookie(handler, filter), m_adbPath(adbPath), m_params(params), m_Deleted(false) {
m_process = new DGLBaseQTProcess();
m_process->setParent(this);
CONNASSERT(m_process->getProcess(),
SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(handleProcessFinished(int, QProcess::ExitStatus)));
CONNASSERT(m_process->getProcess(), SIGNAL(error(QProcess::ProcessError)),
this, SLOT(handleProcessError(QProcess::ProcessError)));
}
void DGLAdbCookieImpl::process() {
if (!m_adbPath.size()) {
onFailed(tr(
"ADB path is not set, go to Tools->Configuration->Android to "
"set it.").toStdString());
} else {
m_process->run(m_adbPath, "", m_params,
m_OutputFilter.get() != nullptr);
}
}
void DGLAdbCookieImpl::handleProcessError(QProcess::ProcessError) {
onFailed(m_process->getProcess()->errorString().toStdString());
if (!m_Deleted) {
m_Deleted = true;
disconnect();
deleteLater();
}
}
void DGLAdbCookieImpl::handleProcessFinished(int code,
QProcess::ExitStatus status) {
if (status == QProcess::NormalExit) {
QProcess* process = m_process->getProcess();
QByteArray qData = process->readAllStandardError();
qData.append(process->readAllStandardOutput());
QList<QByteArray> qLines = qData.split('\n');
std::vector<std::string> lines;
bool suException = false;
foreach(QByteArray qLine, qLines) {
// skip adb server startup messages.
if (qLine[0] == '*') {
if (qLine.contains("daemon not running")) {
continue;
}
if (qLine.contains("daemon started successfully")) {
continue;
}
}
// skip ChainsDD su non-fatal exception ant it's stacktrace
if (suException) {
if (qLine.contains("at ") ||
qLine.contains("Can't connect to activity manager")) {
continue;
}
suException = false;
} else {
if (qLine.contains("Error type 2")) {
suException = true;
continue;
}
}
lines.push_back(
QString(qLine.replace("\r", QByteArray())).toStdString());
}
if (code) {
if (lines[0].find("error:") == 0) {
onFailed(lines[0]);
} else {
std::ostringstream msg;
msg << "Adb process exit code :" << code << ":" << std::endl;
msg << QString(m_process->getProcess()->readAll())
.toStdString();
onFailed(msg.str());
}
} else {
// success
filterOutput(lines);
}
} else {
onFailed("ADB process crashed");
}
if (!m_Deleted) {
m_Deleted = true;
disconnect();
deleteLater();
}
}
DGLAdbCookieFactory::DGLAdbCookieFactory(const std::string& adbPath)
: m_adbPath(adbPath) {}
const std::string& DGLAdbCookieFactory::getAdbPath() { return m_adbPath; }
DGLAdbCookie* DGLAdbCookieFactory::CreateCookie(
const std::vector<std::string>& params, DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter) {
return new DGLAdbCookieImpl(m_adbPath, params, handler, filter);
}
DGLAdbInterface* DGLAdbInterface::get() {
if (!s_self) {
s_self = std::make_shared<DGLAdbInterface>();
}
return s_self.get();
}
void DGLAdbInterface::setAdbCookieFactory(
std::shared_ptr<DGLAdbCookieFactoryBase> factory) {
m_factory = factory;
}
const std::string DGLAdbInterface::getAdbPath() const {
DGLAdbCookieFactory* factory =
dynamic_cast<DGLAdbCookieFactory*>(m_factory.get());
if (factory) {
return factory->getAdbPath();
}
return "";
}
std::shared_ptr<DGLAdbInterface> DGLAdbInterface::s_self;
DGLAdbCookie* DGLAdbInterface::killServer(DGLAdbHandler* handler) {
std::vector<std::string> params;
params.push_back("kill-server");
return invokeAdb(params, handler, std::make_shared<DGLEmptyOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::connect(const std::string& address,
DGLAdbHandler* handler) {
std::vector<std::string> params;
params.push_back("connect");
params.push_back(address);
return invokeAdb(params, handler,
std::make_shared<DGLConnectOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::getDevices(DGLAdbHandler* handler) {
std::vector<std::string> params(1, "devices");
return invokeAdb(params, handler,
std::make_shared<DGLDeviceOutputFilter>());
}
DGLAdbCookie* DGLAdbInterface::invokeOnDevice(
const std::string& serial, const std::vector<std::string>& params,
DGLAdbHandler* handler, std::shared_ptr<DGLAdbOutputFilter> filter) {
std::vector<std::string> deviceParams(2 + params.size());
deviceParams[0] = "-s";
deviceParams[1] = serial;
std::copy(params.begin(), params.end(), deviceParams.begin() + 2);
DGLAdbCookie* ret = m_factory->CreateCookie(deviceParams, handler, filter);
return ret;
}
DGLAdbCookie* DGLAdbInterface::invokeAdb(
const std::vector<std::string>& params, DGLAdbHandler* handler,
std::shared_ptr<DGLAdbOutputFilter> filter) {
DGLAdbCookie* ret = m_factory->CreateCookie(params, handler, filter);
return ret;
}
<|endoftext|> |
<commit_before>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
#include <opencog/query/PatternMatch.h>
#include <opencog/guile/SchemeSmob.h>
#include <opencog/guile/SchemeEval.h>
DefaultForwardChainerCB::DefaultForwardChainerCB(AtomSpace* as) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the target
* uses temporary atomspace to limit the search space
*
* xxx this method uses SchemeEval and SchemeSmob for transferring handles
* from main atomspace to temporary atomspace.I tried to use AddAtom but
* it was not working.Handles were not being passed.So I ended up using SchemeEval
* with a hack (delete previously created SchemEval instance in order to use SchemeEval
* with another atomspace)
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle target = fcmem.get_cur_target();
if (target == Handle::UNDEFINED or NodeCast(target))
throw InvalidParamException(TRACE_INFO,
"Needs a target atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(target)) {
AtomSpace rule_atomspace;
SchemeEval* sceval = new SchemeEval(&rule_atomspace);
//Handle target_cpy=rule_atomspace.addAtom(target); xxx this doesn't work
Handle target_cpy = sceval->eval_h(SchemeSmob::to_string(target)); //xxx this works
//copy rules to the temporary atomspace
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
//rule_atomspace.addAtom(r->get_handle()); xxx this doesn't work
sceval->eval_h(SchemeSmob::to_string(r->get_handle())); //xxx this works
}
//create bindlink with target as an implicant
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(target_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
//pattern match
DefaultImplicator imp(&rule_atomspace);
try {
PatternMatch pm;
pm.do_bindlink(bind_link, imp);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
//get matched bindLinks
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
delete sceval; //delete to use SchemeEval with another atomspace.this might be a hack.
//push back handles to main atomspace
for (Handle h : bindlinks) {
//auto bindlink = as_->addAtom(h);
SchemeEval *sc = new SchemeEval(as_);
auto bindlink = sc->eval_h(SchemeSmob::to_string(h));
chosen_bindlinks.push_back(bindlink);
}
}
//trying to find specialized rules that contain the target node
if (NodeCast(target)) {
chosen_bindlinks = get_rootlinks(target, as_, BIND_LINK);
}
//find the rules containing the bindLink in copied_back
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
cout << "RULE FOUND" << endl;
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that contain @param htarget
*
* @param htarget handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle htarget, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(htarget, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, htarget)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_input(FCMemory& fcmem)
{
Handle htarget = fcmem.get_cur_target();
//get everything associated with the target handle
HandleSeq inputs = as_->getNeighbors(htarget, true, true, LINK, true);
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_target(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_target_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
for (Handle t : tlist) {
float fitness = pc.target_tv_fitness(t);
tournament_elem[t] = fitness;
}
return pc.tournament_select(tournament_elem);
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
PatternMatch pm;
try {
pm.do_bindlink(cur_rule->get_handle(), *fcpm_);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
return fcpm_->get_products();
}
<commit_msg>Remove the hack, now that bug in #1380 is fixed.<commit_after>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
#include <opencog/query/PatternMatch.h>
#include <opencog/guile/SchemeSmob.h>
DefaultForwardChainerCB::DefaultForwardChainerCB(AtomSpace* as) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the target
* uses temporary atomspace to limit the search space
*
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle target = fcmem.get_cur_target();
if (target == Handle::UNDEFINED or NodeCast(target))
throw InvalidParamException(TRACE_INFO,
"Needs a target atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(target)) {
AtomSpace rule_atomspace;
Handle target_cpy = rule_atomspace.addAtom(target);
// Copy rules to the temporary atomspace.
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
rule_atomspace.addAtom(r->get_handle());
}
// Create bindlink with target as an implicant.
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(target_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
// Pattern match.
DefaultImplicator imp(&rule_atomspace);
try {
PatternMatch pm;
pm.do_bindlink(bind_link, imp);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
// Get matched bindLinks.
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
// Copy handles to main atomspace.
for (Handle h : bindlinks) {
chosen_bindlinks.push_back(as_->addAtom(h));
}
}
// Try to find specialized rules that contain the target node.
if (NodeCast(target)) {
chosen_bindlinks = get_rootlinks(target, as_, BIND_LINK);
}
// Find the rules containing the bindLink in copied_back.
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
cout << "RULE FOUND" << endl;
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that contain @param htarget
*
* @param htarget handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle htarget, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(htarget, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, htarget)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_input(FCMemory& fcmem)
{
Handle htarget = fcmem.get_cur_target();
//get everything associated with the target handle
HandleSeq inputs = as_->getNeighbors(htarget, true, true, LINK, true);
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_target(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_target_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
for (Handle t : tlist) {
float fitness = pc.target_tv_fitness(t);
tournament_elem[t] = fitness;
}
return pc.tournament_select(tournament_elem);
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
PatternMatch pm;
try {
pm.do_bindlink(cur_rule->get_handle(), *fcpm_);
} catch (InvalidParamException& e) {
cout << "VALIDATION FAILED:" << endl << e.what() << endl;
}
return fcpm_->get_products();
}
<|endoftext|> |
<commit_before>#pragma once
#include <gcl/mp/type_traits.hpp>
#include <tuple>
namespace gcl::mp::type_traits
{
// Limitations : compilers support
// Clang 11.0.0 : does not support "Lambdas in unevaluated contexts" (P0315R4)
// MsVC 19.28 : "error C2057: expected constant expression" in consteval context
// (like static_assert<std::is_same_v<>>)
// GCC 10.2 : OK
// template <
// typename T,
// template <typename...> class PackType = std::tuple,
// typename = std::enable_if_t<type_traits::is_template_v<T>>>
// using pack_arguments = std::remove_reference_t<decltype([]<template <typename...> typename Type, typename... Ts>(
// Type<Ts...>) constexpr { return PackType<Ts...>{}; }(std::declval<T>()))>;
template <
typename T,
template <typename...> class PackType = std::tuple,
typename = std::enable_if_t<type_traits::is_template_v<T>>>
class pack_arguments {
template <template <typename...> typename Type, typename... Ts>
static auto impl(Type<Ts...>)
{ // type deducer
return PackType<Ts...>{};
}
public:
using type = decltype(impl(std::declval<T>()));
};
template <
typename T,
template <typename...> class PackType = std::tuple,
typename = std::enable_if_t<type_traits::is_template_v<T>>>
using pack_arguments_t = typename pack_arguments<T, PackType>::type;
template <typename T, typename U>
struct concatenate;
template <template <typename...> typename T, typename ... Ts, typename ... Us>
struct concatenate<T<Ts...>, T<Us...>>
{
using type = T<Ts..., Us...>;
};
template <typename T, typename U>
using concatenate_t = typename concatenate<T,U>::type;
template <std::size_t N, typename... Ts>
using type_at = typename std::tuple_element<N, std::tuple<Ts...>>;
template <std::size_t N, typename... Ts>
using type_at_t = typename type_at<N, Ts...>::type;
template <typename to_find, typename pack_type>
class index_of {
template <template <typename...> class PackType, typename... PackArgs>
consteval static auto impl(PackType<PackArgs...>)
{
constexpr auto index =
[]<typename TupleType, std::size_t... I>(TupleType, std::index_sequence<I...>) consteval
{
constexpr bool matches[] = {std::is_same_v<to_find, std::tuple_element_t<I, TupleType>>...};
static_assert(std::size(matches) == sizeof...(I));
return std::distance(matches, std::find(matches, matches + sizeof...(I), true));
}
(std::tuple<PackArgs...>{}, std::make_index_sequence<sizeof...(PackArgs)>{});
static_assert(index != sizeof...(PackArgs), "index_of : no match");
return index;
}
public:
constexpr static auto value = impl(pack_type{});
};
template <typename to_find, typename pack_type>
constexpr static auto index_of_v = index_of<to_find, pack_type>::value;
template <typename T, typename... Ts>
using contains = std::disjunction<std::is_same<T, Ts>...>;
template <typename T, typename... Ts>
static constexpr inline auto contains_v = contains<T, Ts...>::value;
template <typename T, template <typename> typename trait>
struct filters;
template <template <typename...> typename T, template <typename> typename trait, typename... Ts>
struct filters<T<Ts...>, trait> {
template <typename Type>
using impl = std::conditional_t<trait<Type>::value, std::tuple<Type>, std::tuple<>>;
public:
using type = pack_arguments_t<decltype(std::tuple_cat(impl<Ts>{}...)), T>;
};
template <typename T, template <typename> typename trait>
using filters_t = typename filters<T, trait>::type;
}
namespace gcl::mp
{
template <typename T, typename = std::enable_if_t<gcl::mp::type_traits::is_template_v<T>>>
struct pack_traits;
template <template <typename...> typename T, typename... Ts>
struct pack_traits<T<Ts...>> {
using type = T<Ts...>;
using arguments = type_traits::pack_arguments_t<type>;
template <template <class...> class template_type>
using unpack_as = type_traits::pack_arguments_t<type, template_type>;
template <size_t N>
using type_at = type_traits::type_at_t<N, Ts...>; // typename std::tuple_element<N, arguments>::type;
template <typename U>
static constexpr inline auto index_of_v = gcl::mp::type_traits::index_of_v<U, arguments>;
static constexpr inline auto size = std::tuple_size_v<arguments>;
template <typename U>
static constexpr inline auto contains = type_traits::contains_v<U, Ts...>;
template <template <class...> class template_type>
static inline constexpr auto is_instance_of_v = type_traits::is_instance_of_v<type, template_type>;
template <template <typename> typename trait>
using satisfy_trait_t = std::conjunction<trait<Ts>...>;
template <template <typename> typename trait>
constexpr static inline bool satisfy_trait_v = satisfy_trait_t<trait>::value; //(trait<Ts>::value && ...)
template <template <typename> typename trait>
using filters = type_traits::filters_t<T<Ts...>, trait>;
};
template <typename... Ts>
struct pack_type { // empty type that has variadic template-type parameters
// use this instead of std::tuple to pack template-type parameters,
// if your optimization level does not skip unused variables for some reasons
};
template <typename... Ts>
struct super : Ts... {};
template <template <typename...> class base_type, typename... Ts>
struct partial {
// differs type instanciation with partial template-type parameters
template <typename... Us, typename = std::enable_if_t<sizeof...(Us) >= 1>>
using type = base_type<Ts..., Us...>;
};
}
namespace gcl::mp::type_traits::tests
{
static_assert(std::is_same_v<gcl::mp::type_traits::type_at_t<2, char, bool, int, float>, int>);
static_assert(gcl::mp::type_traits::contains_v<int, char, bool, int, float>);
static_assert(gcl::mp::partial<std::is_same, int>::type<int>::value);
static_assert(gcl::mp::partial<std::is_same>::type<int, int>::value);
namespace pack_arguments
{
template <typename... Ts>
struct pack_type {};
using toto = typename gcl::mp::type_traits::pack_arguments_t<pack_type<int, double, float>, std::tuple>;
using titi = typename gcl::mp::type_traits::pack_arguments_t<pack_type<int, double, float>>;
static_assert(std::is_same_v<titi, toto>);
static_assert(std::is_same_v<titi, std::tuple<int, double, float>>);
static_assert(
std::is_same_v<pack_type<int, double, float>, gcl::mp::type_traits::pack_arguments_t<titi, pack_type>>);
}
namespace concatenate
{
template <typename... Ts>
struct pack {};
using T1 = pack<int, double>;
using T2 = pack<char, float>;
static_assert(std::is_same_v<concatenate_t<T1, T2>, pack<int, double, char, float>>);
}
namespace filters
{
template <typename... Ts>
struct pack {};
using T1 = pack<int, int*,char, char*, float>;
static_assert(std::is_same_v<filters_t<T1, std::is_pointer>, pack<int*, char*>>);
}
namespace index_of
{
template <typename... Ts>
struct pack {};
using type_pack = pack<int, double, char, float>;
static_assert(gcl::mp::type_traits::index_of_v<char, type_pack> == 2);
}
}
namespace gcl::mp::tests::pack_traits
{
template <typename... Ts>
struct pack_type {};
using base_type = pack_type<int, char, float>;
using pack_traits_type = gcl::mp::pack_traits<base_type>;
static_assert(std::is_same_v<pack_traits_type::type, base_type>);
static_assert(pack_traits_type::size == 3);
static_assert(pack_traits_type::size == std::tuple_size_v<pack_traits_type::arguments>);
static_assert(std::is_same_v<pack_traits_type::arguments, std::tuple<int, char, float>>);
static_assert(std::is_same_v<base_type, pack_traits_type::unpack_as<pack_type>>);
static_assert(pack_traits_type::is_instance_of_v<pack_type>);
static_assert(std::is_same_v<pack_traits_type::type_at<1>, char>);
static_assert(pack_traits_type::contains<char>);
static_assert(pack_traits_type::satisfy_trait_v<std::is_standard_layout>);
static_assert(not pack_traits_type::satisfy_trait_v<std::is_pointer>);
static_assert(pack_traits_type::index_of_v<char> == 1);
namespace filters
{
using T1 = pack_type<int, int*, char, char*, float>;
using T1_pack_trait = gcl::mp::pack_traits<T1>;
static_assert(std::is_same_v<pack_type<int*, char*>, T1_pack_trait::filters<std::is_pointer>>);
}
}
<commit_msg>[mp::type_traits] : index_of : add first_index_of, last_index_of<commit_after>#pragma once
#include <gcl/mp/type_traits.hpp>
#include <tuple>
#include <array>
namespace gcl::mp::type_traits
{
// Limitations : compilers support
// Clang 11.0.0 : does not support "Lambdas in unevaluated contexts" (P0315R4)
// MsVC 19.28 : "error C2057: expected constant expression" in consteval context
// (like static_assert<std::is_same_v<>>)
// GCC 10.2 : OK
// template <
// typename T,
// template <typename...> class PackType = std::tuple,
// typename = std::enable_if_t<type_traits::is_template_v<T>>>
// using pack_arguments = std::remove_reference_t<decltype([]<template <typename...> typename Type, typename... Ts>(
// Type<Ts...>) constexpr { return PackType<Ts...>{}; }(std::declval<T>()))>;
template <
typename T,
template <typename...> class PackType = std::tuple,
typename = std::enable_if_t<type_traits::is_template_v<T>>>
class pack_arguments {
template <template <typename...> typename Type, typename... Ts>
static auto impl(Type<Ts...>)
{ // type deducer
return PackType<Ts...>{};
}
public:
using type = decltype(impl(std::declval<T>()));
};
template <
typename T,
template <typename...> class PackType = std::tuple,
typename = std::enable_if_t<type_traits::is_template_v<T>>>
using pack_arguments_t = typename pack_arguments<T, PackType>::type;
template <typename T, typename U>
struct concatenate;
template <template <typename...> typename T, typename ... Ts, typename ... Us>
struct concatenate<T<Ts...>, T<Us...>>
{
using type = T<Ts..., Us...>;
};
template <typename T, typename U>
using concatenate_t = typename concatenate<T,U>::type;
template <std::size_t N, typename... Ts>
using type_at = typename std::tuple_element<N, std::tuple<Ts...>>;
template <std::size_t N, typename... Ts>
using type_at_t = typename type_at<N, Ts...>::type;
template <typename to_find, typename pack_type>
class index_of {
template <auto distance_algorithm, template <typename...> class PackType, typename... PackArgs>
consteval static auto impl(PackType<PackArgs...>)
{
constexpr auto index =
[]<typename TupleType, std::size_t... I>(TupleType, std::index_sequence<I...>) consteval
{
constexpr std::array<bool, sizeof...(I)> matches = {
std::is_same_v<to_find, std::tuple_element_t<I, TupleType>>...};
static_assert(std::size(matches) == sizeof...(I));
using matches_iterator_type = decltype(std::cbegin(matches));
return distance_algorithm(matches);
}
(std::tuple<PackArgs...>{}, std::make_index_sequence<sizeof...(PackArgs)>{});
static_assert(index != sizeof...(PackArgs), "index_of : no match");
return index;
}
constexpr static auto from_begin = []<class ContainerType>(ContainerType container) consteval
{
return std::distance(std::cbegin(container), std::find(std::cbegin(container), std::cend(container), true));
};
constexpr static auto from_end = []<class ContainerType>(ContainerType container) consteval
{
return std::size(container) - 1 -
std::distance(
std::crbegin(container), std::find(std::crbegin(container), std::crend(container), true));
};
public:
constexpr static auto value = impl<from_begin>(pack_type{});
constexpr static auto first_value = value;
constexpr static auto last_value = impl<from_end>(pack_type{});
};
template <typename to_find, typename pack_type>
constexpr static auto index_of_v = index_of<to_find, pack_type>::value;
template <typename to_find, typename pack_type>
constexpr static auto first_index_of_v = index_of<to_find, pack_type>::first_value;
template <typename to_find, typename pack_type>
constexpr static auto last_index_of_v = index_of<to_find, pack_type>::last_value;
template <typename T, typename... Ts>
using contains = std::disjunction<std::is_same<T, Ts>...>;
template <typename T, typename... Ts>
static constexpr inline auto contains_v = contains<T, Ts...>::value;
template <typename T, template <typename> typename trait>
struct filters;
template <template <typename...> typename T, template <typename> typename trait, typename... Ts>
struct filters<T<Ts...>, trait> {
template <typename Type>
using impl = std::conditional_t<trait<Type>::value, std::tuple<Type>, std::tuple<>>;
public:
using type = pack_arguments_t<decltype(std::tuple_cat(impl<Ts>{}...)), T>;
};
template <typename T, template <typename> typename trait>
using filters_t = typename filters<T, trait>::type;
}
namespace gcl::mp
{
template <typename T, typename = std::enable_if_t<gcl::mp::type_traits::is_template_v<T>>>
struct pack_traits;
template <template <typename...> typename T, typename... Ts>
struct pack_traits<T<Ts...>> {
using type = T<Ts...>;
using arguments = type_traits::pack_arguments_t<type>;
template <template <class...> class template_type>
using unpack_as = type_traits::pack_arguments_t<type, template_type>;
template <size_t N>
using type_at = type_traits::type_at_t<N, Ts...>; // typename std::tuple_element<N, arguments>::type;
template <typename U>
static constexpr inline auto index_of_v = gcl::mp::type_traits::index_of_v<U, arguments>;
template <typename U>
static constexpr inline auto first_index_of_v = gcl::mp::type_traits::first_index_of_v<U, arguments>;
template <typename U>
static constexpr inline auto last_index_of_v = gcl::mp::type_traits::last_index_of_v<U, arguments>;
static constexpr inline auto size = std::tuple_size_v<arguments>;
template <typename U>
static constexpr inline auto contains = type_traits::contains_v<U, Ts...>;
template <template <class...> class template_type>
static inline constexpr auto is_instance_of_v = type_traits::is_instance_of_v<type, template_type>;
template <template <typename> typename trait>
using satisfy_trait_t = std::conjunction<trait<Ts>...>;
template <template <typename> typename trait>
constexpr static inline bool satisfy_trait_v = satisfy_trait_t<trait>::value; //(trait<Ts>::value && ...)
template <template <typename> typename trait>
using filters = type_traits::filters_t<T<Ts...>, trait>;
};
template <typename... Ts>
struct pack_type { // empty type that has variadic template-type parameters
// use this instead of std::tuple to pack template-type parameters,
// if your optimization level does not skip unused variables for some reasons
};
template <typename... Ts>
struct super : Ts... {};
template <template <typename...> class base_type, typename... Ts>
struct partial {
// differs type instanciation with partial template-type parameters
template <typename... Us, typename = std::enable_if_t<sizeof...(Us) >= 1>>
using type = base_type<Ts..., Us...>;
};
}
namespace gcl::mp::type_traits::tests
{
static_assert(std::is_same_v<gcl::mp::type_traits::type_at_t<2, char, bool, int, float>, int>);
static_assert(gcl::mp::type_traits::contains_v<int, char, bool, int, float>);
static_assert(gcl::mp::partial<std::is_same, int>::type<int>::value);
static_assert(gcl::mp::partial<std::is_same>::type<int, int>::value);
namespace pack_arguments
{
template <typename... Ts>
struct pack_type {};
using toto = typename gcl::mp::type_traits::pack_arguments_t<pack_type<int, double, float>, std::tuple>;
using titi = typename gcl::mp::type_traits::pack_arguments_t<pack_type<int, double, float>>;
static_assert(std::is_same_v<titi, toto>);
static_assert(std::is_same_v<titi, std::tuple<int, double, float>>);
static_assert(
std::is_same_v<pack_type<int, double, float>, gcl::mp::type_traits::pack_arguments_t<titi, pack_type>>);
}
namespace concatenate
{
template <typename... Ts>
struct pack {};
using T1 = pack<int, double>;
using T2 = pack<char, float>;
static_assert(std::is_same_v<concatenate_t<T1, T2>, pack<int, double, char, float>>);
}
namespace filters
{
template <typename... Ts>
struct pack {};
using T1 = pack<int, int*,char, char*, float>;
static_assert(std::is_same_v<filters_t<T1, std::is_pointer>, pack<int*, char*>>);
}
namespace index_of
{
template <typename... Ts>
struct pack {};
using type_pack = pack<int, double, char, float>;
static_assert(gcl::mp::type_traits::index_of_v<char, type_pack> == 2);
}
}
namespace gcl::mp::tests::pack_traits
{
template <typename... Ts>
struct pack_type {};
using base_type = pack_type<int, char, float>;
using pack_traits_type = gcl::mp::pack_traits<base_type>;
static_assert(std::is_same_v<pack_traits_type::type, base_type>);
static_assert(pack_traits_type::size == 3);
static_assert(pack_traits_type::size == std::tuple_size_v<pack_traits_type::arguments>);
static_assert(std::is_same_v<pack_traits_type::arguments, std::tuple<int, char, float>>);
static_assert(std::is_same_v<base_type, pack_traits_type::unpack_as<pack_type>>);
static_assert(pack_traits_type::is_instance_of_v<pack_type>);
static_assert(std::is_same_v<pack_traits_type::type_at<1>, char>);
static_assert(pack_traits_type::contains<char>);
static_assert(pack_traits_type::satisfy_trait_v<std::is_standard_layout>);
static_assert(not pack_traits_type::satisfy_trait_v<std::is_pointer>);
using pack_type_with_repetitions = pack_type<int, char, double, int, char>;
using pack_type_with_repetitions_trait = gcl::mp::pack_traits<pack_type_with_repetitions>;
static_assert(pack_type_with_repetitions_trait::index_of_v<char> == 1);
static_assert(pack_type_with_repetitions_trait::first_index_of_v<char> == 1);
static_assert(pack_type_with_repetitions_trait::last_index_of_v<char> == 4);
namespace filters
{
using T1 = pack_type<int, int*, char, char*, float>;
using T1_pack_trait = gcl::mp::pack_traits<T1>;
static_assert(std::is_same_v<pack_type<int*, char*>, T1_pack_trait::filters<std::is_pointer>>);
}
}
<|endoftext|> |
<commit_before><commit_msg>legion: getting type tags right for default constructors of IndexSpaceT and IndexPartitionT<commit_after><|endoftext|> |
<commit_before>/*
This file is part of KDE
Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
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, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kcolordialog.h>
#include <kcolormimedata.h>
#include <QtGui/QClipboard>
static const char description[] =
I18N_NOOP("KDE Color Chooser");
static const char version[] = "v1.0.1";
int main(int argc, char *argv[])
{
KAboutData aboutData("kcolorchooser", 0, ki18n("KColorChooser"),
version, ki18n(description), KAboutData::License_BSD,
ki18n("(c) 2000, Waldo Bastian"));
aboutData.addAuthor(ki18n("Waldo Bastian"),KLocalizedString(), "bastian@kde.org");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("print", ki18n("Print the selected color to stdout"));
options.add("color <color>", ki18n("Set initially selected color"));
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
KColorDialog dlg;
QColor color = KColorMimeData::fromMimeData( QApplication::clipboard()->mimeData( QClipboard::Clipboard ));
if (!color.isValid()) {
color = Qt::blue; // Just a color
}
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->isSet("color")) {
QColor c = QColor(args->getOption("color"));
if (c.isValid())
color = c;
}
dlg.setColor(color);
app.connect(&dlg, SIGNAL(finished()), SLOT(quit()));
dlg.show();
app.exec();
const QColor c = dlg.color();
if ( args->isSet("print") && c.isValid() ) {
std::cout << c.name().toUtf8().constData() << std::endl;
}
args->clear();
}
<commit_msg>Add Help button<commit_after>/*
This file is part of KDE
Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
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, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kcolordialog.h>
#include <kcolormimedata.h>
#include <khelpmenu.h>
#include <QtGui/QClipboard>
static const char description[] =
I18N_NOOP("KDE Color Chooser");
static const char version[] = "v1.0.1";
int main(int argc, char *argv[])
{
KAboutData aboutData("kcolorchooser", 0, ki18n("KColorChooser"),
version, ki18n(description), KAboutData::License_BSD,
ki18n("(c) 2000, Waldo Bastian"));
aboutData.addAuthor(ki18n("Waldo Bastian"),KLocalizedString(), "bastian@kde.org");
aboutData.setProductName("kdelibs/kdeui");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("print", ki18n("Print the selected color to stdout"));
options.add("color <color>", ki18n("Set initially selected color"));
KCmdLineArgs::addCmdLineOptions( options );
KApplication app;
KColorDialog dlg;
KHelpMenu *help = new KHelpMenu(&dlg, &aboutData);
QColor color = KColorMimeData::fromMimeData( QApplication::clipboard()->mimeData( QClipboard::Clipboard ));
if (!color.isValid()) {
color = Qt::blue; // Just a color
}
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->isSet("color")) {
QColor c = QColor(args->getOption("color"));
if (c.isValid())
color = c;
}
dlg.setButtons(KDialog::Help | KDialog::Close);
dlg.setButtonMenu(KDialog::Help, (QMenu *)(help->menu()));
dlg.setColor(color);
app.connect(&dlg, SIGNAL(finished()), SLOT(quit()));
dlg.show();
app.exec();
const QColor c = dlg.color();
if ( args->isSet("print") && c.isValid() ) {
std::cout << c.name().toUtf8().constData() << std::endl;
}
args->clear();
}
<|endoftext|> |
<commit_before>#include "types.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "fs.h"
#include "stat.h"
#include "kalloc.hh"
#include "file.hh"
#include "bits.hh"
#include "amd64.h"
#include "cpu.hh"
#include "sampler.h"
#define LOGHEADER_SZ (sizeof(struct logheader) + \
sizeof(((struct logheader*)0)->cpu[0])*NCPU)
static volatile u64 selector;
static volatile u64 period;
struct pmu {
void (*config)(u64 ctr, u64 sel, u64 val);
u64 cntval_bits;
};
struct pmu pmu;
struct pmulog {
u64 count;
u64 capacity;
struct pmuevent *event;
__padout__;
} __mpalign__;
struct pmulog pmulog[NCPU] __mpalign__;
//
// AMD stuff
//
static void
amdconfig(u64 ctr, u64 sel, u64 val)
{
writemsr(MSR_AMD_PERF_SEL0 | ctr, 0);
writemsr(MSR_AMD_PERF_CNT0 | ctr, val);
writemsr(MSR_AMD_PERF_SEL0 | ctr, sel);
}
struct pmu amdpmu = { amdconfig, 48 };
//
// Intel stuff
//
static void
intelconfig(u64 ctr, u64 sel, u64 val)
{
writemsr(MSR_INTEL_PERF_SEL0 | ctr, 0);
writemsr(MSR_INTEL_PERF_CNT0 | ctr, val);
writemsr(MSR_INTEL_PERF_SEL0 | ctr, sel);
}
// XXX
struct pmu intelpmu = { intelconfig, 48 };
void
sampdump(void)
{
for (int c = 0; c < NCPU; c++) {
struct pmulog *l = &pmulog[c];
cprintf("%u samples %lu\n", c, l->count);
for (u64 i = 0; i < 4 && i < l->count; i++)
cprintf(" %lx\n", l->event[i].rip);
}
}
void
sampconf(void)
{
pushcli();
pmu.config(0, selector, -period);
popcli();
}
void
sampstart(void)
{
pushcli();
for(struct cpu *c = cpus; c < cpus+ncpu; c++) {
if(c == cpus+mycpu()->id)
continue;
lapic_sampconf(c->hwid);
}
sampconf();
popcli();
}
static int
samplog(struct trapframe *tf)
{
struct pmulog *l;
struct pmuevent *e;
l = &pmulog[mycpu()->id];
if (l->count == l->capacity)
return 0;
e = &l->event[l->count];
e->rip = tf->rip;
getcallerpcs((void*)tf->rbp, e->trace, NELEM(e->trace));
l->count++;
return 1;
}
int
sampintr(struct trapframe *tf)
{
// Acquire locks that we only acquire during NMI.
// NMIs are disabled until the next iret.
// Linux unmasks LAPIC.PC after every interrupt (perf_event.c)
lapicpc(0);
// Only level-triggered interrupts require an lapiceoi.
u64 cnt = rdpmc(0);
if (cnt & (1ULL << (pmu.cntval_bits - 1)))
return 0;
if (samplog(tf))
pmu.config(0, selector, -period);
return 1;
}
static int
readlog(char *dst, u32 off, u32 n)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
int ret = 0;
u64 cur = 0;
for (p = &pmulog[0]; p != q && n != 0; p++) {
u64 len = p->count * sizeof(struct pmuevent);
char *buf = (char*)p->event;
if (cur <= off && off < cur+len) {
u64 boff = off-cur;
u64 cc = MIN(len-boff, n);
memmove(dst, buf+boff, cc);
n -= cc;
ret += cc;
off += cc;
dst += cc;
}
cur += len;
}
return ret;
}
static void
sampstat(struct inode *ip, struct stat *st)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
u64 sz = 0;
sz += LOGHEADER_SZ;
for (p = &pmulog[0]; p != q; p++)
sz += p->count * sizeof(struct pmuevent);
st->dev = ip->dev;
st->ino = ip->inum;
st->type = ip->type;
st->nlink = ip->nlink;
st->size = sz;
}
static int
sampread(struct inode *ip, char *dst, u32 off, u32 n)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
struct logheader *hdr;
int ret;
int i;
ret = 0;
if (off < LOGHEADER_SZ) {
u64 len = LOGHEADER_SZ;
u64 cc;
hdr = (logheader*) kmalloc(len, "logheader");
if (hdr == nullptr)
return -1;
hdr->ncpus = NCPU;
i = 0;
for (p = &pmulog[0]; p != q; p++) {
u64 sz = p->count * sizeof(struct pmuevent);
hdr->cpu[i].offset = len;
hdr->cpu[i].size = sz;
len += sz;
i++;
}
cc = MIN(LOGHEADER_SZ-off, n);
memmove(dst, (char*)hdr + off, cc);
kmfree(hdr, LOGHEADER_SZ);
n -= cc;
ret += cc;
off += cc;
dst += cc;
}
if (off >= LOGHEADER_SZ)
ret += readlog(dst, off-LOGHEADER_SZ, n);
return ret;
}
static int
sampwrite(struct inode *ip, char *buf, u32 off, u32 n)
{
struct sampconf *conf;
if (n != sizeof(*conf))
return -1;
conf = (struct sampconf*)buf;
switch(conf->op) {
case SAMP_ENABLE:
selector = conf->selector;
period = conf->period;
sampstart();
break;
case SAMP_DISABLE:
selector = 0;
period = 0;
sampstart();
break;
}
return n;
}
void
initsamp(void)
{
if (myid() == mpbcpu()) {
u32 name[4];
char *s = (char *)name;
name[3] = 0;
cpuid(0, 0, &name[0], &name[2], &name[1]);
if (VERBOSE)
cprintf("%s\n", s);
if (!strcmp(s, "AuthenticAMD"))
pmu = amdpmu;
else if (!strcmp(s, "GenuineIntel"))
pmu = intelpmu;
else
panic("Unknown Manufacturer");
}
// enable RDPMC at CPL > 0
u64 cr4 = rcr4();
lcr4(cr4 | CR4_PCE);
void *p = ksalloc(slab_perf);
if (p == nullptr)
panic("initprof: ksalloc");
pmulog[myid()].event = (pmuevent*) p;
pmulog[myid()].capacity = PERFSIZE / sizeof(struct pmuevent);
devsw[SAMPLER].write = sampwrite;
devsw[SAMPLER].read = sampread;
devsw[SAMPLER].stat = sampstat;
}
<commit_msg>A hack to reset sampler counts<commit_after>#include "types.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "fs.h"
#include "stat.h"
#include "kalloc.hh"
#include "file.hh"
#include "bits.hh"
#include "amd64.h"
#include "cpu.hh"
#include "sampler.h"
#define LOGHEADER_SZ (sizeof(struct logheader) + \
sizeof(((struct logheader*)0)->cpu[0])*NCPU)
static volatile u64 selector;
static volatile u64 period;
struct pmu {
void (*config)(u64 ctr, u64 sel, u64 val);
u64 cntval_bits;
};
struct pmu pmu;
struct pmulog {
u64 count;
u64 capacity;
struct pmuevent *event;
__padout__;
} __mpalign__;
struct pmulog pmulog[NCPU] __mpalign__;
//
// AMD stuff
//
static void
amdconfig(u64 ctr, u64 sel, u64 val)
{
writemsr(MSR_AMD_PERF_SEL0 | ctr, 0);
writemsr(MSR_AMD_PERF_CNT0 | ctr, val);
writemsr(MSR_AMD_PERF_SEL0 | ctr, sel);
}
struct pmu amdpmu = { amdconfig, 48 };
//
// Intel stuff
//
static void
intelconfig(u64 ctr, u64 sel, u64 val)
{
writemsr(MSR_INTEL_PERF_SEL0 | ctr, 0);
writemsr(MSR_INTEL_PERF_CNT0 | ctr, val);
writemsr(MSR_INTEL_PERF_SEL0 | ctr, sel);
}
// XXX
struct pmu intelpmu = { intelconfig, 48 };
void
sampdump(void)
{
for (int c = 0; c < NCPU; c++) {
struct pmulog *l = &pmulog[c];
cprintf("%u samples %lu\n", c, l->count);
for (u64 i = 0; i < 4 && i < l->count; i++)
cprintf(" %lx\n", l->event[i].rip);
}
}
void
sampconf(void)
{
pushcli();
if (selector)
pmulog[myid()].count = 0;
pmu.config(0, selector, -period);
popcli();
}
void
sampstart(void)
{
pushcli();
for(struct cpu *c = cpus; c < cpus+ncpu; c++) {
if(c == cpus+mycpu()->id)
continue;
lapic_sampconf(c->hwid);
}
sampconf();
popcli();
}
static int
samplog(struct trapframe *tf)
{
struct pmulog *l;
struct pmuevent *e;
l = &pmulog[mycpu()->id];
if (l->count == l->capacity)
return 0;
e = &l->event[l->count];
e->rip = tf->rip;
getcallerpcs((void*)tf->rbp, e->trace, NELEM(e->trace));
l->count++;
return 1;
}
int
sampintr(struct trapframe *tf)
{
// Acquire locks that we only acquire during NMI.
// NMIs are disabled until the next iret.
// Linux unmasks LAPIC.PC after every interrupt (perf_event.c)
lapicpc(0);
// Only level-triggered interrupts require an lapiceoi.
u64 cnt = rdpmc(0);
if (cnt & (1ULL << (pmu.cntval_bits - 1)))
return 0;
if (samplog(tf))
pmu.config(0, selector, -period);
return 1;
}
static int
readlog(char *dst, u32 off, u32 n)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
int ret = 0;
u64 cur = 0;
for (p = &pmulog[0]; p != q && n != 0; p++) {
u64 len = p->count * sizeof(struct pmuevent);
char *buf = (char*)p->event;
if (cur <= off && off < cur+len) {
u64 boff = off-cur;
u64 cc = MIN(len-boff, n);
memmove(dst, buf+boff, cc);
n -= cc;
ret += cc;
off += cc;
dst += cc;
}
cur += len;
}
return ret;
}
static void
sampstat(struct inode *ip, struct stat *st)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
u64 sz = 0;
sz += LOGHEADER_SZ;
for (p = &pmulog[0]; p != q; p++)
sz += p->count * sizeof(struct pmuevent);
st->dev = ip->dev;
st->ino = ip->inum;
st->type = ip->type;
st->nlink = ip->nlink;
st->size = sz;
}
static int
sampread(struct inode *ip, char *dst, u32 off, u32 n)
{
struct pmulog *q = &pmulog[NCPU];
struct pmulog *p;
struct logheader *hdr;
int ret;
int i;
ret = 0;
if (off < LOGHEADER_SZ) {
u64 len = LOGHEADER_SZ;
u64 cc;
hdr = (logheader*) kmalloc(len, "logheader");
if (hdr == nullptr)
return -1;
hdr->ncpus = NCPU;
i = 0;
for (p = &pmulog[0]; p != q; p++) {
u64 sz = p->count * sizeof(struct pmuevent);
hdr->cpu[i].offset = len;
hdr->cpu[i].size = sz;
len += sz;
i++;
}
cc = MIN(LOGHEADER_SZ-off, n);
memmove(dst, (char*)hdr + off, cc);
kmfree(hdr, LOGHEADER_SZ);
n -= cc;
ret += cc;
off += cc;
dst += cc;
}
if (off >= LOGHEADER_SZ)
ret += readlog(dst, off-LOGHEADER_SZ, n);
return ret;
}
static int
sampwrite(struct inode *ip, char *buf, u32 off, u32 n)
{
struct sampconf *conf;
if (n != sizeof(*conf))
return -1;
conf = (struct sampconf*)buf;
switch(conf->op) {
case SAMP_ENABLE:
selector = conf->selector;
period = conf->period;
sampstart();
break;
case SAMP_DISABLE:
selector = 0;
period = 0;
sampstart();
break;
}
return n;
}
void
initsamp(void)
{
if (myid() == mpbcpu()) {
u32 name[4];
char *s = (char *)name;
name[3] = 0;
cpuid(0, 0, &name[0], &name[2], &name[1]);
if (VERBOSE)
cprintf("%s\n", s);
if (!strcmp(s, "AuthenticAMD"))
pmu = amdpmu;
else if (!strcmp(s, "GenuineIntel"))
pmu = intelpmu;
else
panic("Unknown Manufacturer");
}
// enable RDPMC at CPL > 0
u64 cr4 = rcr4();
lcr4(cr4 | CR4_PCE);
void *p = ksalloc(slab_perf);
if (p == nullptr)
panic("initprof: ksalloc");
pmulog[myid()].event = (pmuevent*) p;
pmulog[myid()].capacity = PERFSIZE / sizeof(struct pmuevent);
devsw[SAMPLER].write = sampwrite;
devsw[SAMPLER].read = sampread;
devsw[SAMPLER].stat = sampstat;
}
<|endoftext|> |
<commit_before>#include "mugen_background.h"
#include <math.h>
#include <ostream>
#include <cstring>
#include <string>
#include <algorithm>
#include "globals.h"
#include "mugen_sprite.h"
#include "util/bitmap.h"
//static double pi = 3.14159265;
using namespace std;
static double interpolate(double f1, double f2, double p){
return (f1 * (1.0 - p)) + (f2 * p);
}
static int calculateTile( int length, int width ){
int loc = 0;
for( int i = 1; ; ++i ){
if( loc > length )return i;
loc+=width;
}
}
static void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){
const int height = bmp.getHeight();
const int w = bmp.getWidth();
int movex = 0;
//double z = 1.0 / z1;
//const double z_add = ((1.0 / z2) - z) / (y2 - y1);
Global::debug(3) << "background leftx " << leftx << endl;
for (int localy = 0; localy < height; ++localy ){
//int width = bmp.getWidth()*z;
const double range = (double)localy / (double)height;
const double scale = interpolate(top, bot, range) - top;
//const double newHeight = height*((yscalestart+(yoffset*yscaledelta))/100);
//const double yscale = (newHeight/height);
movex = (int)(leftx + (leftx - xoffset) * scale);
bmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);
//z += z_add;
//Global::debug(1) << "Height: " << height << " | yscalestart: " << yscalestart << " | yscaledelta: " << yscaledelta << " | yoffset: " << yoffset << " | New Height: " << newHeight << " | yscale: " << yscale << endl;
}
}
// mugen background
MugenBackground::MugenBackground( const unsigned long int &ticker ):
type(Normal),
groupNumber(-1),
imageNumber(-1),
actionno(-1),
id(0),
layerno(0),
startx(0),
starty(0),
deltax(1),
deltay(1),
trans(None),
alphalow(0),
alphahigh(0),
mask(true),
tilex(0),
tiley(0),
tilespacingx(0),
tilespacingy(0),
windowdeltax(0),
windowdeltay(0),
xscaletop(0),
xscalebot(0),
yscalestart(100),
yscaledelta(100),
positionlink(false),
velocityx(0),
velocityy(0),
sinx_amp(0),
sinx_period(0),
sinx_offset(0),
sinx_angle(0),
siny_amp(0),
siny_period(0),
siny_offset(0),
siny_angle(0),
xoffset(0),
yoffset(0),
movex(0),
movey(0),
velx(0),
vely(0),
stageTicker( ticker ),
x(0),
y(0),
visible(true),
enabled(true),
controller_offsetx(0),
controller_offsety(0),
sprite(0),
spriteBmp(0),
action(0),
linked(0),
runLink(false){
}
MugenBackground::MugenBackground( const MugenBackground © ):
stageTicker( copy.stageTicker ){
}
MugenBackground::~MugenBackground(){
// Kill the bmp
if( spriteBmp )delete spriteBmp;
}
MugenBackground & MugenBackground::operator=( const MugenBackground © ){
return *this;
}
void MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){
if (enabled){
movex = movey = 0;
movex += x * deltax;
movey += y * deltay;
velx += velocityx;
vely += velocityy;
/* how much should sin_angle be incremented by each frame?
* I think the total angle should be (ticks % sin_period) * 2pi / sin_period
* M (decimal) is the magnitude in pixels (amp)
* P (decimal) is the period in game ticks (period)
* O (decimal) is the time offset in game ticks (offset)
* From updates.txt: M * sine ((ticks+O)/P * 2 * Pi)
* sinx_amp * sin((stageTicker+sinx_offset)/sinx_period * 2 * pi)) ? useless it seems
*/
//sin_angle += 0.00005;
sinx_angle += 0.00005;
siny_angle += 0.00005;
if( type == Anim ) action->logic();
this->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));
this->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));
}
}
void MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){
if (visible){
switch( type ){
case Normal:{
// Normal is a sprite
// see if we need to tile this beyatch
int tilexloc = x;
const int width = spriteBmp->getWidth();
const int height = spriteBmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile (this crap doesn't work needs fix)
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = width + tilespacingx;
const int addh = height + tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
draw( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Parallax:{
// This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth
doParallax( *spriteBmp, *work, x, y, xoffset, xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);
break;
}
case Anim:{
// there is no sprite use our action!
//action->render( x, y, *work );
// Need to tile as well
int tilexloc = x;
const int width = action->getCurrentFrame()->bmp->getWidth();
const int height = action->getCurrentFrame()->bmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = tilespacingx;
const int addh = tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
action->render( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Dummy:
// Do nothing
default:
break;
}
}
}
void MugenBackground::preload( const int xaxis, const int yaxis ){
// Do positionlink crap
if (positionlink && !runLink){
if (linked){
linked->setPositionLink(this);
}
runLink = true;
}
if(sprite){
// Lets load our sprite
spriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength));
// Set our initial offsets
xoffset = 160 + (xaxis - sprite->x) + startx;
yoffset = (yaxis - sprite->y) + starty;
velx = vely = 0;
}
else{
// Set our initial offsets
xoffset = 160 + (xaxis) + startx;
yoffset = (yaxis) + starty;
velx = vely = 0;
}
}
void MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){
// This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha
switch( trans ){
case Addalpha:{
// Need to figure out blend correctly addalpha is given to two locations low and high ?
Bitmap::transBlender( 255, 255, 255, alphalow );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add:{
// this additive 100% I assume... not totally sure
Bitmap::addBlender( 255, 255, 255, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add1:{
// 50%
Bitmap::addBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Sub:{
// Shadow effect
Bitmap::differenceBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case None:
default:{
if( mask )spriteBmp->draw( ourx,oury, work );
else spriteBmp->Blit( ourx, oury, work );
break;
}
}
}
// Lets do our positionlink stuff
void MugenBackground::setPositionLink(MugenBackground *bg){
if (positionlink){
if (linked){
linked->setPositionLink(bg);
return;
}
}
bg->startx += startx;
bg->starty += starty;
bg->deltax = deltax;
bg->deltay = deltay;
bg->sinx_amp = sinx_amp;
bg->sinx_offset = sinx_offset;
bg->sinx_period = sinx_period;
bg->siny_amp = siny_amp;
bg->siny_offset = siny_offset;
bg->siny_period = siny_period;
bg->velocityx = velocityx;
bg->velocityy = velocityy;
//Global::debug(1) << "Positionlinked bg: " << bg->name << " set to x: " << bg->startx << " y: " << bg->starty << endl;
}
<commit_msg>Corrected parallax offset<commit_after>#include "mugen_background.h"
#include <math.h>
#include <ostream>
#include <cstring>
#include <string>
#include <algorithm>
#include "globals.h"
#include "mugen_sprite.h"
#include "util/bitmap.h"
//static double pi = 3.14159265;
using namespace std;
static double interpolate(double f1, double f2, double p){
return (f1 * (1.0 - p)) + (f2 * p);
}
static int calculateTile( int length, int width ){
int loc = 0;
for( int i = 1; ; ++i ){
if( loc > length )return i;
loc+=width;
}
}
static void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){
const int height = bmp.getHeight();
const int w = bmp.getWidth();
int movex = 0;
//double z = 1.0 / z1;
//const double z_add = ((1.0 / z2) - z) / (y2 - y1);
Global::debug(3) << "background leftx " << leftx << endl;
for (int localy = 0; localy < height; ++localy ){
//int width = bmp.getWidth()*z;
const double range = (double)localy / (double)height;
const double scale = interpolate(top, bot, range) - top;
//const double newHeight = height*((yscalestart+(yoffset*yscaledelta))/100);
//const double yscale = (newHeight/height);
movex = (int)(leftx + (leftx - xoffset) * scale);
bmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);
//z += z_add;
//Global::debug(1) << "Height: " << height << " | yscalestart: " << yscalestart << " | yscaledelta: " << yscaledelta << " | yoffset: " << yoffset << " | New Height: " << newHeight << " | yscale: " << yscale << endl;
}
}
// mugen background
MugenBackground::MugenBackground( const unsigned long int &ticker ):
type(Normal),
groupNumber(-1),
imageNumber(-1),
actionno(-1),
id(0),
layerno(0),
startx(0),
starty(0),
deltax(1),
deltay(1),
trans(None),
alphalow(0),
alphahigh(0),
mask(true),
tilex(0),
tiley(0),
tilespacingx(0),
tilespacingy(0),
windowdeltax(0),
windowdeltay(0),
xscaletop(0),
xscalebot(0),
yscalestart(100),
yscaledelta(100),
positionlink(false),
velocityx(0),
velocityy(0),
sinx_amp(0),
sinx_period(0),
sinx_offset(0),
sinx_angle(0),
siny_amp(0),
siny_period(0),
siny_offset(0),
siny_angle(0),
xoffset(0),
yoffset(0),
movex(0),
movey(0),
velx(0),
vely(0),
stageTicker( ticker ),
x(0),
y(0),
visible(true),
enabled(true),
controller_offsetx(0),
controller_offsety(0),
sprite(0),
spriteBmp(0),
action(0),
linked(0),
runLink(false){
}
MugenBackground::MugenBackground( const MugenBackground © ):
stageTicker( copy.stageTicker ){
}
MugenBackground::~MugenBackground(){
// Kill the bmp
if( spriteBmp )delete spriteBmp;
}
MugenBackground & MugenBackground::operator=( const MugenBackground © ){
return *this;
}
void MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){
if (enabled){
movex = movey = 0;
movex += x * deltax;
movey += y * deltay;
velx += velocityx;
vely += velocityy;
/* how much should sin_angle be incremented by each frame?
* I think the total angle should be (ticks % sin_period) * 2pi / sin_period
* M (decimal) is the magnitude in pixels (amp)
* P (decimal) is the period in game ticks (period)
* O (decimal) is the time offset in game ticks (offset)
* From updates.txt: M * sine ((ticks+O)/P * 2 * Pi)
* sinx_amp * sin((stageTicker+sinx_offset)/sinx_period * 2 * pi)) ? useless it seems
*/
//sin_angle += 0.00005;
sinx_angle += 0.00005;
siny_angle += 0.00005;
if( type == Anim ) action->logic();
this->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));
this->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));
}
}
void MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){
if (visible){
switch( type ){
case Normal:{
// Normal is a sprite
// see if we need to tile this beyatch
int tilexloc = x;
const int width = spriteBmp->getWidth();
const int height = spriteBmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile (this crap doesn't work needs fix)
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = width + tilespacingx;
const int addh = height + tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
draw( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Parallax:{
// This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth
doParallax( *spriteBmp, *work, x, y, xoffset/2, xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);
break;
}
case Anim:{
// there is no sprite use our action!
//action->render( x, y, *work );
// Need to tile as well
int tilexloc = x;
const int width = action->getCurrentFrame()->bmp->getWidth();
const int height = action->getCurrentFrame()->bmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = tilespacingx;
const int addh = tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
action->render( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Dummy:
// Do nothing
default:
break;
}
}
}
void MugenBackground::preload( const int xaxis, const int yaxis ){
// Do positionlink crap
if (positionlink && !runLink){
if (linked){
linked->setPositionLink(this);
}
runLink = true;
}
if(sprite){
// Lets load our sprite
spriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength));
// Set our initial offsets
xoffset = 160 + (xaxis - sprite->x) + startx;
yoffset = (yaxis - sprite->y) + starty;
velx = vely = 0;
}
else{
// Set our initial offsets
xoffset = 160 + (xaxis) + startx;
yoffset = (yaxis) + starty;
velx = vely = 0;
}
}
void MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){
// This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha
switch( trans ){
case Addalpha:{
// Need to figure out blend correctly addalpha is given to two locations low and high ?
Bitmap::transBlender( 255, 255, 255, alphalow );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add:{
// this additive 100% I assume... not totally sure
Bitmap::addBlender( 255, 255, 255, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add1:{
// 50%
Bitmap::addBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Sub:{
// Shadow effect
Bitmap::differenceBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case None:
default:{
if( mask )spriteBmp->draw( ourx,oury, work );
else spriteBmp->Blit( ourx, oury, work );
break;
}
}
}
// Lets do our positionlink stuff
void MugenBackground::setPositionLink(MugenBackground *bg){
if (positionlink){
if (linked){
linked->setPositionLink(bg);
return;
}
}
bg->startx += startx;
bg->starty += starty;
bg->deltax = deltax;
bg->deltay = deltay;
bg->sinx_amp = sinx_amp;
bg->sinx_offset = sinx_offset;
bg->sinx_period = sinx_period;
bg->siny_amp = siny_amp;
bg->siny_offset = siny_offset;
bg->siny_period = siny_period;
bg->velocityx = velocityx;
bg->velocityy = velocityy;
//Global::debug(1) << "Positionlinked bg: " << bg->name << " set to x: " << bg->startx << " y: " << bg->starty << endl;
}
<|endoftext|> |
<commit_before>/*
* Part of Appstream, a library for accessing AppStream on-disk database
* Copyright 2014 Sune Vuorela <sune@vuorela.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "component.h"
#include "screenshot.h"
#include <QSharedData>
#include <QStringList>
#include <QUrl>
#include <QMultiHash>
using namespace Appstream;
class Appstream::ComponentData : public QSharedData {
public:
QStringList m_categories;
QStringList m_compulsoryForDesktops;
QString m_description;
QString m_developerName;
QStringList m_extends;
QStringList m_extensions;
QString m_icon;
QString m_id;
Component::Kind m_kind;
QString m_name;
QStringList m_packageNames;
QString m_projectGroup;
QString m_projectLicense;
QString m_summary;
QHash<QString, QUrl> m_iconUrls;
QMultiHash<Component::UrlKind, QUrl> m_urls;
QList<Appstream::Screenshot> m_screenshots;
QMultiHash<Provides::Kind, Provides> m_provides;
QHash<Component::BundleKind, QString> m_bundles;
bool operator==(const ComponentData& other) const {
if(m_categories != other.m_categories) {
return false;
}
if(m_compulsoryForDesktops != other.m_compulsoryForDesktops) {
return false;
}
if(m_description != other.m_description) {
return false;
}
if(m_developerName != other.m_developerName) {
return false;
}
if(m_extends != other.m_extends) {
return false;
}
if(m_icon != other.m_icon) {
return false;
}
if(m_iconUrls != other.m_iconUrls) {
return false;
}
if(m_id != other.m_id) {
return false;
}
if(m_kind != other.m_kind) {
return false;
}
if(m_name != other.m_name) {
return false;
}
if(m_packageNames != other.m_packageNames) {
return false;
}
if(m_projectGroup != other.m_projectGroup) {
return false;
}
if(m_projectLicense != other.m_projectLicense) {
return false;
}
if(m_summary != other.m_summary) {
return false;
}
if(m_urls != other.m_urls) {
return false;
}
if(m_screenshots != other.m_screenshots) {
return false;
}
if(m_provides != other.m_provides) {
return false;
}
if(m_bundles != other.m_bundles) {
return false;
}
// we don't check for m_extensions, since this is auto-generated and not a specific property of a component.
return true;
}
};
QStringList Component::categories() const {
return d->m_categories;
}
QStringList Component::compulsoryForDesktops() const {
return d->m_compulsoryForDesktops;
}
QString Component::description() const {
return d->m_description;
}
QString Component::developerName() const {
return d->m_developerName;
}
bool Component::hasCategory(const QString& category) const {
return d->m_categories.contains(category);
}
QString Component::icon() const {
return d->m_icon;
}
QUrl Component::iconUrl(const QSize& size) const {
QString sizeStr;
// if no size was specified, we assume 64x64
if (size.isValid())
sizeStr = QStringLiteral("%1x%2").arg(size.width()).arg(size.height());
else
sizeStr = QStringLiteral("64x64");
return d->m_iconUrls.value(sizeStr);
}
QString Component::id() const {
return d->m_id;
}
bool Component::isCompulsoryForDesktop(const QString& desktop) const {
return d->m_compulsoryForDesktops.contains(desktop);
}
Component::Kind Component::kind() const {
return d->m_kind;
}
QString Component::name() const {
return d->m_name;
}
QStringList Component::packageNames() const {
return d->m_packageNames;
}
QString Component::projectGroup() const {
return d->m_projectGroup;
}
QString Component::projectLicense() const {
return d->m_projectLicense;
}
void Component::setCategories(const QStringList& categories) {
d->m_categories = categories;
}
void Component::setCompulsoryForDesktops(const QStringList& desktops) {
d->m_compulsoryForDesktops = desktops;
}
void Component::setDescription(const QString& description) {
d->m_description = description;
}
void Component::setDeveloperName(const QString& developerName) {
d->m_developerName = developerName;
}
void Component::setIcon(const QString& icon) {
d->m_icon = icon;
}
void Component::addIconUrl(const QUrl& iconUrl, const QSize& size) {
QString sizeStr;
// if no size was specified, we assume 64x64
if (size.isValid())
sizeStr = QStringLiteral("%1x%2").arg(size.width()).arg(size.height());
else
sizeStr = QStringLiteral("64x64");
d->m_iconUrls.insert(sizeStr, iconUrl);
}
void Component::setId(const QString& id) {
d->m_id = id;
}
void Component::setKind(Component::Kind kind) {
d->m_kind = kind;
}
void Component::setName(const QString& name) {
d->m_name = name;
}
void Component::setPackageNames(const QStringList& packageNames) {
d->m_packageNames = packageNames;
}
void Component::setProjectGroup(const QString& group) {
d->m_projectGroup = group;
}
void Component::setProjectLicense(const QString& license){
d->m_projectLicense = license;
}
void Component::setSummary(const QString& summary){
d->m_summary = summary;
}
QString Component::summary() const {
return d->m_summary;
}
QStringList Component::extends() const {
return d->m_extends;
}
void Component::setExtends(const QStringList& extends) {
d->m_extends = extends;
}
QStringList Component::extensions() const {
return d->m_extensions;
}
void Component::setExtensions(const QStringList& extensions) {
d->m_extensions = extensions;
}
Component::Component(const Component& other) : d(other.d) {
}
Component::Component() : d(new ComponentData) {
}
Component& Component::operator=(const Component& other) {
this->d = other.d;
return *this;
}
void Component::setUrls(const QMultiHash< Component::UrlKind, QUrl >& urls) {
d->m_urls = urls;
}
QList< QUrl > Component::urls(Component::UrlKind kind) const {
return d->m_urls.values(kind);
}
QMultiHash< Component::UrlKind, QUrl > Component::urls() const {
return d->m_urls;
}
void Component::setBundles(const QHash< Component::BundleKind, QString >& bundles) {
d->m_bundles = bundles;
}
QString Component::bundle(Component::BundleKind kind) const {
return d->m_bundles.value(kind);
}
QHash< Component::BundleKind, QString > Component::bundles() const {
return d->m_bundles;
}
bool Component::operator==(const Component& other) {
if(this->d == other.d) {
return true;
}
if(this->d && other.d) {
return *(this->d) == *other.d;
}
return false;
}
Component::~Component() = default;
typedef QHash<Component::Kind, QString> KindMap;
Q_GLOBAL_STATIC_WITH_ARGS(KindMap, kindMap, ( {
{ Component::KindAddon, QLatin1String("addon") },
{ Component::KindCodec, QLatin1String("codec") },
{ Component::KindDesktop, QLatin1String("desktop") },
{ Component::KindFont, QLatin1String("font") },
{ Component::KindGeneric, QLatin1String("generic") },
{ Component::KindInputmethod, QLatin1String("inputmethod") },
{ Component::KindAddon, QLatin1String("firmware") },
{ Component::KindUnknown, QLatin1String("unknown") }
}
));
QString Component::kindToString(Component::Kind kind) {
return kindMap->value(kind);
}
Component::Kind Component::stringToKind(const QString& kindString) {
if(kindString == QLatin1String("generic")) {
return KindGeneric;
}
if (kindString == QLatin1String("desktop")) {
return KindDesktop;
}
if (kindString == QLatin1String("font")) {
return KindFont;
}
if (kindString == QLatin1String("codec")) {
return KindCodec;
}
if (kindString==QLatin1String("inputmethod")) {
return KindInputmethod;
}
if (kindString == QLatin1String("addon")) {
return KindAddon;
}
if (kindString == QLatin1String("firmware")) {
return KindFirmware;
}
return KindUnknown;
}
void Component::setScreenshots(const QList< Screenshot >& screenshots) {
d->m_screenshots = screenshots;
}
QList< Screenshot > Component::screenshots() const {
return d->m_screenshots;
}
Component::UrlKind Component::stringToUrlKind(const QString& urlKindString) {
if (urlKindString == QLatin1String("homepage")) {
return UrlKindHomepage;
}
if (urlKindString == QLatin1String("bugtracker")) {
return UrlKindBugtracker;
}
if (urlKindString == QLatin1String("faq")) {
return UrlKindFaq;
}
if (urlKindString == QLatin1String("help")) {
return UrlKindHelp;
}
if (urlKindString == QLatin1String("donation")) {
return UrlKindDonation;
}
return UrlKindUnknown;
}
typedef QHash<Component::UrlKind, QString> UrlKindMap;
Q_GLOBAL_STATIC_WITH_ARGS(UrlKindMap, urlKindMap, ({
{ Component::UrlKindBugtracker, QLatin1String("bugtracker") },
{ Component::UrlKindDonation, QLatin1String("donation") },
{ Component::UrlKindFaq, QLatin1String("faq") },
{ Component::UrlKindHelp, QLatin1String("help") },
{ Component::UrlKindHomepage, QLatin1String("homepage") },
{ Component::UrlKindUnknown, QLatin1String("unknown") },
}));
QString Component::urlKindToString(Component::UrlKind kind) {
return urlKindMap->value(kind);
}
QString Component::bundleKindToString(Component::BundleKind kind) {
switch (kind) {
case Component::BundleKindLimba:
return QStringLiteral("limba");
case Component::BundleKindXdgApp:
return QStringLiteral("xdg-app");
default:
return QString();
}
}
Component::BundleKind Component::stringToBundleKind(const QString& bundleKindString) {
if (bundleKindString == QLatin1String("limba")) {
return BundleKindLimba;
}
if (bundleKindString == QLatin1String("xdg-app")) {
return BundleKindXdgApp;
}
return BundleKindUnknown;
}
QList< Appstream::Provides > Component::provides() const {
return d->m_provides.values();
}
QList<Appstream::Provides> Component::provides(Provides::Kind kind) const {
return d->m_provides.values(kind);
}
void Component::setProvides(const QList<Appstream::Provides>& provides) {
Q_FOREACH(const Appstream::Provides& provide, provides) {
d->m_provides.insertMulti(provide.kind(), provide);
}
}
bool Component::isValid() const
{
return !d->m_name.isEmpty();
}
<commit_msg>qt: Properly check for component validity<commit_after>/*
* Part of Appstream, a library for accessing AppStream on-disk database
* Copyright 2014 Sune Vuorela <sune@vuorela.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "component.h"
#include "screenshot.h"
#include <QSharedData>
#include <QStringList>
#include <QUrl>
#include <QMultiHash>
using namespace Appstream;
class Appstream::ComponentData : public QSharedData {
public:
QStringList m_categories;
QStringList m_compulsoryForDesktops;
QString m_description;
QString m_developerName;
QStringList m_extends;
QStringList m_extensions;
QString m_icon;
QString m_id;
Component::Kind m_kind;
QString m_name;
QStringList m_packageNames;
QString m_projectGroup;
QString m_projectLicense;
QString m_summary;
QHash<QString, QUrl> m_iconUrls;
QMultiHash<Component::UrlKind, QUrl> m_urls;
QList<Appstream::Screenshot> m_screenshots;
QMultiHash<Provides::Kind, Provides> m_provides;
QHash<Component::BundleKind, QString> m_bundles;
bool operator==(const ComponentData& other) const {
if(m_categories != other.m_categories) {
return false;
}
if(m_compulsoryForDesktops != other.m_compulsoryForDesktops) {
return false;
}
if(m_description != other.m_description) {
return false;
}
if(m_developerName != other.m_developerName) {
return false;
}
if(m_extends != other.m_extends) {
return false;
}
if(m_icon != other.m_icon) {
return false;
}
if(m_iconUrls != other.m_iconUrls) {
return false;
}
if(m_id != other.m_id) {
return false;
}
if(m_kind != other.m_kind) {
return false;
}
if(m_name != other.m_name) {
return false;
}
if(m_packageNames != other.m_packageNames) {
return false;
}
if(m_projectGroup != other.m_projectGroup) {
return false;
}
if(m_projectLicense != other.m_projectLicense) {
return false;
}
if(m_summary != other.m_summary) {
return false;
}
if(m_urls != other.m_urls) {
return false;
}
if(m_screenshots != other.m_screenshots) {
return false;
}
if(m_provides != other.m_provides) {
return false;
}
if(m_bundles != other.m_bundles) {
return false;
}
// we don't check for m_extensions, since this is auto-generated and not a specific property of a component.
return true;
}
};
QStringList Component::categories() const {
return d->m_categories;
}
QStringList Component::compulsoryForDesktops() const {
return d->m_compulsoryForDesktops;
}
QString Component::description() const {
return d->m_description;
}
QString Component::developerName() const {
return d->m_developerName;
}
bool Component::hasCategory(const QString& category) const {
return d->m_categories.contains(category);
}
QString Component::icon() const {
return d->m_icon;
}
QUrl Component::iconUrl(const QSize& size) const {
QString sizeStr;
// if no size was specified, we assume 64x64
if (size.isValid())
sizeStr = QStringLiteral("%1x%2").arg(size.width()).arg(size.height());
else
sizeStr = QStringLiteral("64x64");
return d->m_iconUrls.value(sizeStr);
}
QString Component::id() const {
return d->m_id;
}
bool Component::isCompulsoryForDesktop(const QString& desktop) const {
return d->m_compulsoryForDesktops.contains(desktop);
}
Component::Kind Component::kind() const {
return d->m_kind;
}
QString Component::name() const {
return d->m_name;
}
QStringList Component::packageNames() const {
return d->m_packageNames;
}
QString Component::projectGroup() const {
return d->m_projectGroup;
}
QString Component::projectLicense() const {
return d->m_projectLicense;
}
void Component::setCategories(const QStringList& categories) {
d->m_categories = categories;
}
void Component::setCompulsoryForDesktops(const QStringList& desktops) {
d->m_compulsoryForDesktops = desktops;
}
void Component::setDescription(const QString& description) {
d->m_description = description;
}
void Component::setDeveloperName(const QString& developerName) {
d->m_developerName = developerName;
}
void Component::setIcon(const QString& icon) {
d->m_icon = icon;
}
void Component::addIconUrl(const QUrl& iconUrl, const QSize& size) {
QString sizeStr;
// if no size was specified, we assume 64x64
if (size.isValid())
sizeStr = QStringLiteral("%1x%2").arg(size.width()).arg(size.height());
else
sizeStr = QStringLiteral("64x64");
d->m_iconUrls.insert(sizeStr, iconUrl);
}
void Component::setId(const QString& id) {
d->m_id = id;
}
void Component::setKind(Component::Kind kind) {
d->m_kind = kind;
}
void Component::setName(const QString& name) {
d->m_name = name;
}
void Component::setPackageNames(const QStringList& packageNames) {
d->m_packageNames = packageNames;
}
void Component::setProjectGroup(const QString& group) {
d->m_projectGroup = group;
}
void Component::setProjectLicense(const QString& license){
d->m_projectLicense = license;
}
void Component::setSummary(const QString& summary){
d->m_summary = summary;
}
QString Component::summary() const {
return d->m_summary;
}
QStringList Component::extends() const {
return d->m_extends;
}
void Component::setExtends(const QStringList& extends) {
d->m_extends = extends;
}
QStringList Component::extensions() const {
return d->m_extensions;
}
void Component::setExtensions(const QStringList& extensions) {
d->m_extensions = extensions;
}
Component::Component(const Component& other) : d(other.d) {
}
Component::Component() : d(new ComponentData) {
}
Component& Component::operator=(const Component& other) {
this->d = other.d;
return *this;
}
void Component::setUrls(const QMultiHash< Component::UrlKind, QUrl >& urls) {
d->m_urls = urls;
}
QList< QUrl > Component::urls(Component::UrlKind kind) const {
return d->m_urls.values(kind);
}
QMultiHash< Component::UrlKind, QUrl > Component::urls() const {
return d->m_urls;
}
void Component::setBundles(const QHash< Component::BundleKind, QString >& bundles) {
d->m_bundles = bundles;
}
QString Component::bundle(Component::BundleKind kind) const {
return d->m_bundles.value(kind);
}
QHash< Component::BundleKind, QString > Component::bundles() const {
return d->m_bundles;
}
bool Component::operator==(const Component& other) {
if(this->d == other.d) {
return true;
}
if(this->d && other.d) {
return *(this->d) == *other.d;
}
return false;
}
Component::~Component() = default;
typedef QHash<Component::Kind, QString> KindMap;
Q_GLOBAL_STATIC_WITH_ARGS(KindMap, kindMap, ( {
{ Component::KindAddon, QLatin1String("addon") },
{ Component::KindCodec, QLatin1String("codec") },
{ Component::KindDesktop, QLatin1String("desktop") },
{ Component::KindFont, QLatin1String("font") },
{ Component::KindGeneric, QLatin1String("generic") },
{ Component::KindInputmethod, QLatin1String("inputmethod") },
{ Component::KindAddon, QLatin1String("firmware") },
{ Component::KindUnknown, QLatin1String("unknown") }
}
));
QString Component::kindToString(Component::Kind kind) {
return kindMap->value(kind);
}
Component::Kind Component::stringToKind(const QString& kindString) {
if(kindString == QLatin1String("generic")) {
return KindGeneric;
}
if (kindString == QLatin1String("desktop")) {
return KindDesktop;
}
if (kindString == QLatin1String("font")) {
return KindFont;
}
if (kindString == QLatin1String("codec")) {
return KindCodec;
}
if (kindString==QLatin1String("inputmethod")) {
return KindInputmethod;
}
if (kindString == QLatin1String("addon")) {
return KindAddon;
}
if (kindString == QLatin1String("firmware")) {
return KindFirmware;
}
return KindUnknown;
}
void Component::setScreenshots(const QList< Screenshot >& screenshots) {
d->m_screenshots = screenshots;
}
QList< Screenshot > Component::screenshots() const {
return d->m_screenshots;
}
Component::UrlKind Component::stringToUrlKind(const QString& urlKindString) {
if (urlKindString == QLatin1String("homepage")) {
return UrlKindHomepage;
}
if (urlKindString == QLatin1String("bugtracker")) {
return UrlKindBugtracker;
}
if (urlKindString == QLatin1String("faq")) {
return UrlKindFaq;
}
if (urlKindString == QLatin1String("help")) {
return UrlKindHelp;
}
if (urlKindString == QLatin1String("donation")) {
return UrlKindDonation;
}
return UrlKindUnknown;
}
typedef QHash<Component::UrlKind, QString> UrlKindMap;
Q_GLOBAL_STATIC_WITH_ARGS(UrlKindMap, urlKindMap, ({
{ Component::UrlKindBugtracker, QLatin1String("bugtracker") },
{ Component::UrlKindDonation, QLatin1String("donation") },
{ Component::UrlKindFaq, QLatin1String("faq") },
{ Component::UrlKindHelp, QLatin1String("help") },
{ Component::UrlKindHomepage, QLatin1String("homepage") },
{ Component::UrlKindUnknown, QLatin1String("unknown") },
}));
QString Component::urlKindToString(Component::UrlKind kind) {
return urlKindMap->value(kind);
}
QString Component::bundleKindToString(Component::BundleKind kind) {
switch (kind) {
case Component::BundleKindLimba:
return QStringLiteral("limba");
case Component::BundleKindXdgApp:
return QStringLiteral("xdg-app");
default:
return QString();
}
}
Component::BundleKind Component::stringToBundleKind(const QString& bundleKindString) {
if (bundleKindString == QLatin1String("limba")) {
return BundleKindLimba;
}
if (bundleKindString == QLatin1String("xdg-app")) {
return BundleKindXdgApp;
}
return BundleKindUnknown;
}
QList< Appstream::Provides > Component::provides() const {
return d->m_provides.values();
}
QList<Appstream::Provides> Component::provides(Provides::Kind kind) const {
return d->m_provides.values(kind);
}
void Component::setProvides(const QList<Appstream::Provides>& provides) {
Q_FOREACH(const Appstream::Provides& provide, provides) {
d->m_provides.insertMulti(provide.kind(), provide);
}
}
bool Component::isValid() const
{
return !d->m_id.isEmpty() &&
!d->m_name.isEmpty() &&
!d->m_summary.isEmpty();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "contextpropertyinfo.h"
#include "infobackend.h"
QMap <QString, QString> constructionStringMap;
QMap <QString, QString> typeMap;
QMap <QString, QString> docMap;
QMap <QString, QString> pluginMap;
QMap <QString, bool> providedMap;
/* Mocked infobackend */
InfoBackend* currentBackend = NULL;
InfoBackend* InfoBackend::instance(const QString &backendName)
{
if (currentBackend)
return currentBackend;
else {
currentBackend = new InfoBackend();
return currentBackend;
}
}
QString InfoBackend::constructionStringForKey(QString key) const
{
if (constructionStringMap.contains(key))
return constructionStringMap.value(key);
else
return QString();
}
QString InfoBackend::typeForKey(QString key) const
{
if (typeMap.contains(key))
return typeMap.value(key);
else
return QString();
}
QString InfoBackend::docForKey(QString key) const
{
if (docMap.contains(key))
return docMap.value(key);
else
return QString();
}
QString InfoBackend::pluginForKey(QString key) const
{
if (pluginMap.contains(key))
return pluginMap.value(key);
else
return QString();
}
bool InfoBackend::keyExists(QString key) const
{
if (typeMap.contains(key))
return true;
else
return false;
}
bool InfoBackend::keyProvided(QString key) const
{
if (providedMap.contains(key))
return providedMap.value(key);
else
return false;
}
void InfoBackend::connectNotify(const char *signal)
{
}
void InfoBackend::disconnectNotify(const char *signal)
{
}
void InfoBackend::fireKeysChanged(const QStringList& keys)
{
emit keysChanged(keys);
}
void InfoBackend::fireKeysAdded(const QStringList& keys)
{
emit keysAdded(keys);
}
void InfoBackend::fireKeysRemoved(const QStringList& keys)
{
emit keysRemoved(keys);
}
void InfoBackend::fireKeyDataChanged(const QString& key)
{
emit keyDataChanged(key);
}
/* ContextRegistryInfoUnitTest */
class ContextPropertyInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void key();
void doc();
void type();
void exists();
void provided();
void providerDBusName();
void providerDBusType();
void plugin();
void constructionString();
void typeChanged();
void providerChanged();
void providedChanged();
void pluginChanged();
};
void ContextPropertyInfoUnitTest::initTestCase()
{
constructionStringMap.clear();
constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.contextd");
constructionStringMap.insert("Media.NowPlaying", "session:com.nokia.musicplayer");
typeMap.clear();
typeMap.insert("Battery.Charging", "TRUTH");
typeMap.insert("Media.NowPlaying", "STRING");
docMap.clear();
docMap.insert("Battery.Charging", "Battery.Charging doc");
docMap.insert("Media.NowPlaying", "Media.NowPlaying doc");
pluginMap.clear();
pluginMap.insert("Battery.Charging", "contextkit-dbus");
pluginMap.insert("Media.NowPlaying", "contextkit-dbus");
providedMap.clear();
providedMap.insert("Battery.Charging", true);
providedMap.insert("Media.NowPlaying", true);
}
void ContextPropertyInfoUnitTest::key()
{
ContextPropertyInfo p("Battery.Charging");
QCOMPARE(p.key(), QString("Battery.Charging"));
}
void ContextPropertyInfoUnitTest::doc()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.doc(), QString("Battery.Charging doc"));
QCOMPARE(p2.doc(), QString("Media.NowPlaying doc"));
QCOMPARE(p3.doc(), QString());
}
void ContextPropertyInfoUnitTest::type()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.type(), QString("TRUTH"));
QCOMPARE(p2.type(), QString("STRING"));
QCOMPARE(p3.type(), QString());
}
void ContextPropertyInfoUnitTest::exists()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.exists(), true);
QCOMPARE(p2.exists(), true);
QCOMPARE(p3.exists(), false);
}
void ContextPropertyInfoUnitTest::provided()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.provided(), true);
QCOMPARE(p2.provided(), true);
QCOMPARE(p3.provided(), false);
}
void ContextPropertyInfoUnitTest::providerDBusName()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd"));
QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer"));
QCOMPARE(p3.providerDBusName(), QString());
}
void ContextPropertyInfoUnitTest::providerDBusType()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus);
QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus);
QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus);
}
void ContextPropertyInfoUnitTest::plugin()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.plugin(), QString("contextkit-dbus"));
QCOMPARE(p2.plugin(), QString("contextkit-dbus"));
QCOMPARE(p3.plugin(), QString());
}
void ContextPropertyInfoUnitTest::constructionString()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd"));
QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer"));
QCOMPARE(p3.constructionString(), QString());
}
void ContextPropertyInfoUnitTest::typeChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(typeChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
typeMap.insert("Battery.Charging", "INT");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
QCOMPARE(args.at(0).toString(), QString("INT"));
}
void ContextPropertyInfoUnitTest::providerChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(providerChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.robot");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
QCOMPARE(args.at(0).toString(), QString("org.freedesktop.ContextKit.robot"));
}
void ContextPropertyInfoUnitTest::providedChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(providedChanged(bool)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
providedMap.insert("Battery.Charging", false);
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
}
void ContextPropertyInfoUnitTest::pluginChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy1(&p, SIGNAL(pluginChanged(QString, QString)));
QSignalSpy spy2(&p, SIGNAL(providerChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy1.count(), 0);
QCOMPARE(spy2.count(), 0);
pluginMap.insert("Battery.Charging", "test.so");
constructionStringMap.insert("Battery.Charging", "secret:something");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy1.count(), 1);
QList<QVariant> args1 = spy1.takeFirst();
QCOMPARE(args1.at(0).toString(), QString("test.so"));
QCOMPARE(args1.at(1).toString(), QString("secret:something"));
QCOMPARE(spy2.count(), 1);
QList<QVariant> args2 = spy2.takeFirst();
QCOMPARE(args2.at(0).toString(), QString(""));
}
#include "contextpropertyinfounittest.moc"
QTEST_MAIN(ContextPropertyInfoUnitTest);
<commit_msg>DBus type changed.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "contextpropertyinfo.h"
#include "infobackend.h"
QMap <QString, QString> constructionStringMap;
QMap <QString, QString> typeMap;
QMap <QString, QString> docMap;
QMap <QString, QString> pluginMap;
QMap <QString, bool> providedMap;
/* Mocked infobackend */
InfoBackend* currentBackend = NULL;
InfoBackend* InfoBackend::instance(const QString &backendName)
{
if (currentBackend)
return currentBackend;
else {
currentBackend = new InfoBackend();
return currentBackend;
}
}
QString InfoBackend::constructionStringForKey(QString key) const
{
if (constructionStringMap.contains(key))
return constructionStringMap.value(key);
else
return QString();
}
QString InfoBackend::typeForKey(QString key) const
{
if (typeMap.contains(key))
return typeMap.value(key);
else
return QString();
}
QString InfoBackend::docForKey(QString key) const
{
if (docMap.contains(key))
return docMap.value(key);
else
return QString();
}
QString InfoBackend::pluginForKey(QString key) const
{
if (pluginMap.contains(key))
return pluginMap.value(key);
else
return QString();
}
bool InfoBackend::keyExists(QString key) const
{
if (typeMap.contains(key))
return true;
else
return false;
}
bool InfoBackend::keyProvided(QString key) const
{
if (providedMap.contains(key))
return providedMap.value(key);
else
return false;
}
void InfoBackend::connectNotify(const char *signal)
{
}
void InfoBackend::disconnectNotify(const char *signal)
{
}
void InfoBackend::fireKeysChanged(const QStringList& keys)
{
emit keysChanged(keys);
}
void InfoBackend::fireKeysAdded(const QStringList& keys)
{
emit keysAdded(keys);
}
void InfoBackend::fireKeysRemoved(const QStringList& keys)
{
emit keysRemoved(keys);
}
void InfoBackend::fireKeyDataChanged(const QString& key)
{
emit keyDataChanged(key);
}
/* ContextRegistryInfoUnitTest */
class ContextPropertyInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void key();
void doc();
void type();
void exists();
void provided();
void providerDBusName();
void providerDBusType();
void plugin();
void constructionString();
void typeChanged();
void providerChanged();
void providedChanged();
void pluginChanged();
void dbusTypeChanged();
};
void ContextPropertyInfoUnitTest::initTestCase()
{
constructionStringMap.clear();
constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.contextd");
constructionStringMap.insert("Media.NowPlaying", "session:com.nokia.musicplayer");
typeMap.clear();
typeMap.insert("Battery.Charging", "TRUTH");
typeMap.insert("Media.NowPlaying", "STRING");
docMap.clear();
docMap.insert("Battery.Charging", "Battery.Charging doc");
docMap.insert("Media.NowPlaying", "Media.NowPlaying doc");
pluginMap.clear();
pluginMap.insert("Battery.Charging", "contextkit-dbus");
pluginMap.insert("Media.NowPlaying", "contextkit-dbus");
providedMap.clear();
providedMap.insert("Battery.Charging", true);
providedMap.insert("Media.NowPlaying", true);
}
void ContextPropertyInfoUnitTest::key()
{
ContextPropertyInfo p("Battery.Charging");
QCOMPARE(p.key(), QString("Battery.Charging"));
}
void ContextPropertyInfoUnitTest::doc()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.doc(), QString("Battery.Charging doc"));
QCOMPARE(p2.doc(), QString("Media.NowPlaying doc"));
QCOMPARE(p3.doc(), QString());
}
void ContextPropertyInfoUnitTest::type()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.type(), QString("TRUTH"));
QCOMPARE(p2.type(), QString("STRING"));
QCOMPARE(p3.type(), QString());
}
void ContextPropertyInfoUnitTest::exists()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.exists(), true);
QCOMPARE(p2.exists(), true);
QCOMPARE(p3.exists(), false);
}
void ContextPropertyInfoUnitTest::provided()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.provided(), true);
QCOMPARE(p2.provided(), true);
QCOMPARE(p3.provided(), false);
}
void ContextPropertyInfoUnitTest::providerDBusName()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd"));
QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer"));
QCOMPARE(p3.providerDBusName(), QString());
}
void ContextPropertyInfoUnitTest::providerDBusType()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus);
QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus);
QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus);
}
void ContextPropertyInfoUnitTest::plugin()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.plugin(), QString("contextkit-dbus"));
QCOMPARE(p2.plugin(), QString("contextkit-dbus"));
QCOMPARE(p3.plugin(), QString());
}
void ContextPropertyInfoUnitTest::constructionString()
{
ContextPropertyInfo p1("Battery.Charging");
ContextPropertyInfo p2("Media.NowPlaying");
ContextPropertyInfo p3("Does.Not.Exist");
QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd"));
QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer"));
QCOMPARE(p3.constructionString(), QString());
}
void ContextPropertyInfoUnitTest::typeChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(typeChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
typeMap.insert("Battery.Charging", "INT");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
QCOMPARE(args.at(0).toString(), QString("INT"));
}
void ContextPropertyInfoUnitTest::providerChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(providerChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.robot");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
QCOMPARE(args.at(0).toString(), QString("org.freedesktop.ContextKit.robot"));
}
void ContextPropertyInfoUnitTest::providedChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(providedChanged(bool)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
providedMap.insert("Battery.Charging", false);
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 1);
QList<QVariant> args = spy.takeFirst();
}
void ContextPropertyInfoUnitTest::pluginChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy1(&p, SIGNAL(pluginChanged(QString, QString)));
QSignalSpy spy2(&p, SIGNAL(providerChanged(QString)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy1.count(), 0);
QCOMPARE(spy2.count(), 0);
pluginMap.insert("Battery.Charging", "test.so");
constructionStringMap.insert("Battery.Charging", "secret:something");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy1.count(), 1);
QList<QVariant> args1 = spy1.takeFirst();
QCOMPARE(args1.at(0).toString(), QString("test.so"));
QCOMPARE(args1.at(1).toString(), QString("secret:something"));
QCOMPARE(spy2.count(), 1);
QList<QVariant> args2 = spy2.takeFirst();
QCOMPARE(args2.at(0).toString(), QString(""));
}
void ContextPropertyInfoUnitTest::dbusTypeChanged()
{
ContextPropertyInfo p("Battery.Charging");
QSignalSpy spy(&p, SIGNAL(providerDBusTypeChanged(QDBusConnection::BusType)));
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
QCOMPARE(spy.count(), 0);
constructionStringMap.insert("Battery.Charging", "session:org.freedesktop.ContextKit.contextd");
currentBackend->fireKeyDataChanged(QString("Battery.Charging"));
// WE DON'T EMIT THE DBUS TYPE CHANGED ANYMORE!
QCOMPARE(spy.count(), 0);
}
#include "contextpropertyinfounittest.moc"
QTEST_MAIN(ContextPropertyInfoUnitTest);
<|endoftext|> |
<commit_before>#include "InjectOpenGLIntrinsics.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "CodeGen_GPU_Dev.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
class InjectOpenGLIntrinsics : public IRMutator {
public:
InjectOpenGLIntrinsics()
: inside_kernel_loop(false) {
}
Scope<int> scope;
bool inside_kernel_loop;
private:
using IRMutator::visit;
void visit(const Provide *provide) {
if (!inside_kernel_loop) {
IRMutator::visit(provide);
return;
}
internal_assert(provide->values.size() == 1) << "GLSL currently only supports single-valued stores.\n";
user_assert(provide->args.size() == 3) << "GLSL stores requires three coordinates.\n";
// Create glsl_texture_store(name, name.buffer, x, y, c, value)
// intrinsic.
vector<Expr> args(6);
args[0] = provide->name;
args[1] = Variable::make(Handle(), provide->name + ".buffer");
for (size_t i = 0; i < provide->args.size(); i++) {
args[i + 2] = provide->args[i];
}
args[5] = mutate(provide->values[0]);
stmt = Evaluate::make(
Call::make(args[5].type(), Call::glsl_texture_store, args, Call::Intrinsic));
}
void visit(const Call *call) {
if (!inside_kernel_loop || call->call_type == Call::Intrinsic) {
IRMutator::visit(call);
return;
}
string name = call->name;
if (call->call_type == Call::Halide && call->func.outputs() > 1) {
name = name + '.' + int_to_string(call->value_index);
}
user_assert(call->args.size() == 3) << "GLSL loads requires three coordinates.\n";
// Create glsl_texture_load(name, name.buffer, x, y, c) intrinsic.
vector<Expr> args(5);
args[0] = call->name;
args[1] = Variable::make(Handle(), call->name + ".buffer");
for (size_t i = 0; i < call->args.size(); i++) {
string d = int_to_string(i);
string min_name = name + ".min." + d;
string min_name_constrained = min_name + ".constrained";
if (scope.contains(min_name_constrained)) {
min_name = min_name_constrained;
}
string extent_name = name + ".extent." + d;
string extent_name_constrained = extent_name + ".constrained";
if (scope.contains(extent_name_constrained)) {
extent_name = extent_name_constrained;
}
Expr min = Variable::make(Int(32), min_name);
Expr extent = Variable::make(Int(32), extent_name);
// Normalize the two spatial coordinates x,y
args[i + 2] = (i < 2)
? (Cast::make(Float(32), call->args[i] - min) + 0.5f) / extent
: call->args[i] - min;
}
expr = Call::make(call->type, Call::glsl_texture_load,
args, Call::Intrinsic,
Function(), 0, call->image, call->param);
}
void visit(const LetStmt *let) {
// Discover constrained versions of things.
bool constrained_version_exists = ends_with(let->name, ".constrained");
if (constrained_version_exists) {
scope.push(let->name, 0);
}
IRMutator::visit(let);
if (constrained_version_exists) {
scope.pop(let->name);
}
}
void visit(const For *loop) {
bool old_kernel_loop = inside_kernel_loop;
if (loop->for_type == For::Parallel &&
CodeGen_GPU_Dev::is_gpu_block_var(loop->name)) {
inside_kernel_loop = true;
}
IRMutator::visit(loop);
inside_kernel_loop = old_kernel_loop;
}
};
// Rewrite all GPU loops to have a min of zero
class ZeroGPULoopMins : public IRMutator {
using IRMutator::visit;
void visit(const For *op) {
IRMutator::visit(op);
if (CodeGen_GPU_Dev::is_gpu_var(op->name) && !is_zero(op->min)) {
op = stmt.as<For>();
internal_assert(op);
Expr adjusted = Variable::make(Int(32), op->name) + op->min;
Stmt body = substitute(op->name, adjusted, op->body);
stmt = For::make(op->name, 0, op->extent, op->for_type, body);
}
}
};
Stmt inject_opengl_intrinsics(Stmt s) {
ZeroGPULoopMins z;
s = z.mutate(s);
InjectOpenGLIntrinsics gl;
return gl.mutate(s);
}
}
}
<commit_msg>Don't convert Extern calls to GLSL intrinsics<commit_after>#include "InjectOpenGLIntrinsics.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "CodeGen_GPU_Dev.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
class InjectOpenGLIntrinsics : public IRMutator {
public:
InjectOpenGLIntrinsics()
: inside_kernel_loop(false) {
}
Scope<int> scope;
bool inside_kernel_loop;
private:
using IRMutator::visit;
void visit(const Provide *provide) {
if (!inside_kernel_loop) {
IRMutator::visit(provide);
return;
}
internal_assert(provide->values.size() == 1) << "GLSL currently only supports single-valued stores.\n";
user_assert(provide->args.size() == 3) << "GLSL stores requires three coordinates.\n";
// Create glsl_texture_store(name, name.buffer, x, y, c, value)
// intrinsic.
vector<Expr> args(6);
args[0] = provide->name;
args[1] = Variable::make(Handle(), provide->name + ".buffer");
for (size_t i = 0; i < provide->args.size(); i++) {
args[i + 2] = provide->args[i];
}
args[5] = mutate(provide->values[0]);
stmt = Evaluate::make(
Call::make(args[5].type(), Call::glsl_texture_store, args, Call::Intrinsic));
}
void visit(const Call *call) {
if (!inside_kernel_loop ||
call->call_type == Call::Intrinsic || call->call_type == Call::Extern) {
IRMutator::visit(call);
return;
}
string name = call->name;
if (call->call_type == Call::Halide && call->func.outputs() > 1) {
name = name + '.' + int_to_string(call->value_index);
}
user_assert(call->args.size() == 3) << "GLSL loads requires three coordinates.\n";
// Create glsl_texture_load(name, name.buffer, x, y, c) intrinsic.
vector<Expr> args(5);
args[0] = call->name;
args[1] = Variable::make(Handle(), call->name + ".buffer");
for (size_t i = 0; i < call->args.size(); i++) {
string d = int_to_string(i);
string min_name = name + ".min." + d;
string min_name_constrained = min_name + ".constrained";
if (scope.contains(min_name_constrained)) {
min_name = min_name_constrained;
}
string extent_name = name + ".extent." + d;
string extent_name_constrained = extent_name + ".constrained";
if (scope.contains(extent_name_constrained)) {
extent_name = extent_name_constrained;
}
Expr min = Variable::make(Int(32), min_name);
Expr extent = Variable::make(Int(32), extent_name);
// Normalize the two spatial coordinates x,y
args[i + 2] = (i < 2)
? (Cast::make(Float(32), call->args[i] - min) + 0.5f) / extent
: call->args[i] - min;
}
expr = Call::make(call->type, Call::glsl_texture_load,
args, Call::Intrinsic,
Function(), 0, call->image, call->param);
}
void visit(const LetStmt *let) {
// Discover constrained versions of things.
bool constrained_version_exists = ends_with(let->name, ".constrained");
if (constrained_version_exists) {
scope.push(let->name, 0);
}
IRMutator::visit(let);
if (constrained_version_exists) {
scope.pop(let->name);
}
}
void visit(const For *loop) {
bool old_kernel_loop = inside_kernel_loop;
if (loop->for_type == For::Parallel &&
CodeGen_GPU_Dev::is_gpu_block_var(loop->name)) {
inside_kernel_loop = true;
}
IRMutator::visit(loop);
inside_kernel_loop = old_kernel_loop;
}
};
// Rewrite all GPU loops to have a min of zero
class ZeroGPULoopMins : public IRMutator {
using IRMutator::visit;
void visit(const For *op) {
IRMutator::visit(op);
if (CodeGen_GPU_Dev::is_gpu_var(op->name) && !is_zero(op->min)) {
op = stmt.as<For>();
internal_assert(op);
Expr adjusted = Variable::make(Int(32), op->name) + op->min;
Stmt body = substitute(op->name, adjusted, op->body);
stmt = For::make(op->name, 0, op->extent, op->for_type, body);
}
}
};
Stmt inject_opengl_intrinsics(Stmt s) {
ZeroGPULoopMins z;
s = z.mutate(s);
InjectOpenGLIntrinsics gl;
return gl.mutate(s);
}
}
}
<|endoftext|> |
<commit_before>#include "styleContext.h"
#include "platform.h"
#include "builders.h"
#include "scene/scene.h"
#include "data/propertyItem.h"
#define DUMP(...) //do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0)
namespace Tangram {
const static char DATA_ID[] = "\xff""\xff""data";
const static char ATTR_ID[] = "\xff""\xff""attr";
const static char FUNC_ID[] = "\xff""\xff""fns";
StyleContext::StyleContext() {
m_ctx = duk_create_heap_default();
// add empty feature_object
duk_push_object(m_ctx);
// assign instance to feature_object
duk_push_pointer(m_ctx, this);
if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) {
LOGE("Ctx not assigned");
}
// put object in global scope
if (!duk_put_global_string(m_ctx, "feature")) {
LOGE("Feature not assigned");
}
DUMP("init\n");
}
StyleContext::~StyleContext() {
duk_destroy_heap(m_ctx);
}
void StyleContext::initFunctions(const Scene& _scene) {
if (_scene.id == m_sceneId) {
return;
}
m_sceneId = _scene.id;
auto arr_idx = duk_push_array(m_ctx);
int id = 0;
for (auto& function : _scene.functions()) {
LOGD("compile '%s'", function.c_str());
duk_push_string(m_ctx, function.c_str());
duk_push_string(m_ctx, "");
if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) {
duk_put_prop_index(m_ctx, arr_idx, id);
} else {
LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
}
id++;
}
if (!duk_put_global_string(m_ctx, FUNC_ID)) {
LOGE("'fns' object not set");
}
DUMP("setScene - %d functions\n", id);
}
void StyleContext::setFeature(const Feature& _feature) {
m_feature = &_feature;
for (auto& item : _feature.props.items()) {
addAccessor(item.key);
}
}
void StyleContext::setGlobalZoom(float _zoom) {
static const std::string _key("$zoom");
if (_zoom != m_globalZoom) {
setGlobal(_key, _zoom);
}
}
void StyleContext::setGlobal(const std::string& _key, const Value& _val) {
Value& entry = m_globals[_key];
if (entry == _val) { return; }
entry = _val;
if (_val.is<float>()) {
duk_push_number(m_ctx, _val.get<float>());
duk_put_global_string(m_ctx, _key.c_str());
if (_key == "$zoom") { m_globalZoom = _val.get<float>(); }
} else if (_val.is<std::string>()) {
duk_push_string(m_ctx, _val.get<std::string>().c_str());
duk_put_global_string(m_ctx, _key.c_str());
}
}
const Value& StyleContext::getGlobal(const std::string& _key) const {
const static Value NOT_FOUND(none_type{});
auto it = m_globals.find(_key);
if (it != m_globals.end()) {
return it->second;
}
return NOT_FOUND;
}
void StyleContext::clear() {
m_feature = nullptr;
}
bool StyleContext::addFunction(const std::string& _name, const std::string& _func) {
duk_push_string(m_ctx, _func.c_str());
duk_push_string(m_ctx, _name.c_str());
if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) {
LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1));
return false;
}
// Put function in global scope
duk_put_global_string(m_ctx, _name.c_str());
DUMP("addFunction\n");
return true;
}
bool StyleContext::evalFilter(FunctionID _id) const {
if (!duk_get_global_string(m_ctx, FUNC_ID)) {
LOGE("EvalFilterFn - functions not initialized");
return false;
}
if (!duk_get_prop_index(m_ctx, -1, _id)) {
LOGE("EvalFilterFn - function %d not set", _id);
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
}
bool result = false;
if (duk_is_boolean(m_ctx, -1)) {
result = duk_get_boolean(m_ctx, -1);
}
// pop result
duk_pop(m_ctx);
// pop fns obj
duk_pop(m_ctx);
DUMP("evalFilterFn\n");
return result;
}
bool StyleContext::evalFilterFn(const std::string& _name) {
if (!duk_get_global_string(m_ctx, _name.c_str())) {
LOGE("EvalFilter %s", _name.c_str());
return false;
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
}
bool result = false;
if (duk_is_boolean(m_ctx, -1)) {
result = duk_get_boolean(m_ctx, -1);
}
// pop result
duk_pop(m_ctx);
DUMP("evalFilterFn\n");
return result;
}
bool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const {
_val = none_type{};
if (duk_is_string(m_ctx, -1)) {
std::string value(duk_get_string(m_ctx, -1));
_val = StyleParam::parseString(_key, value);
} else if (duk_is_boolean(m_ctx, -1)) {
bool value = duk_get_boolean(m_ctx, -1);
switch (_key) {
case StyleParamKey::interactive:
case StyleParamKey::visible:
_val = value;
break;
case StyleParamKey::extrude:
_val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);
break;
default:
break;
}
} else if (duk_is_array(m_ctx, -1)) {
duk_get_prop_string(m_ctx, -1, "length");
int len = duk_get_int(m_ctx, -1);
duk_pop(m_ctx);
switch (_key) {
case StyleParamKey::extrude: {
if (len != 2) {
LOGW("Wrong array size for extrusion: '%d'.", len);
break;
}
duk_get_prop_index(m_ctx, -1, 0);
double v1 = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 1);
double v2 = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
_val = glm::vec2(v1, v2);
break;
}
case StyleParamKey::color:
case StyleParamKey::outline_color:
case StyleParamKey::font_fill:
case StyleParamKey::font_stroke_color: {
if (len < 3 || len > 4) {
LOGW("Wrong array size for color: '%d'.", len);
break;
}
duk_get_prop_index(m_ctx, -1, 0);
double r = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 1);
double g = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 2);
double b = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
double a = 1.0;
if (len == 4) {
duk_get_prop_index(m_ctx, -1, 3);
a = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
}
_val = (((uint32_t)(255.0 * a) & 0xff) << 24) |
(((uint32_t)(255.0 * r) & 0xff)<< 16) |
(((uint32_t)(255.0 * g) & 0xff)<< 8) |
(((uint32_t)(255.0 * b) & 0xff));
break;
}
default:
break;
}
} else if (duk_is_number(m_ctx, -1)) {
switch (_key) {
case StyleParamKey::width:
case StyleParamKey::outline_width: {
// TODO more efficient way to return pixels.
// atm this only works by return value as string
double v = duk_get_number(m_ctx, -1);
_val = StyleParam::Width{static_cast<float>(v)};
break;
}
case StyleParamKey::font_stroke_width: {
_val = static_cast<float>(duk_get_number(m_ctx, -1));
break;
}
case StyleParamKey::order:
case StyleParamKey::priority:
case StyleParamKey::color:
case StyleParamKey::outline_color:
case StyleParamKey::font_fill:
case StyleParamKey::font_stroke_color: {
_val = static_cast<uint32_t>(duk_get_uint(m_ctx, -1));
break;
}
default:
break;
}
} else {
LOGW("Unhandled return type from Javascript function.");
}
duk_pop(m_ctx);
DUMP("parseStyleResult\n");
return !_val.is<none_type>();
}
bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const {
if (!duk_get_global_string(m_ctx, FUNC_ID)) {
LOGE("EvalFilterFn - functions array not initialized");
return false;
}
if (!duk_get_prop_index(m_ctx, -1, _id)) {
LOGE("EvalFilterFn - function %d not set", _id);
}
// pop fns array
duk_remove(m_ctx, -2);
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
return false;
}
return parseStyleResult(_key, _val);
}
bool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) {
if (!duk_get_global_string(m_ctx, name.c_str())) {
LOGE("EvalFilter %s", name.c_str());
return false;
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalStyleFn: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
return false;
}
return parseStyleResult(_key, _val);
}
void StyleContext::addAccessor(const std::string& _name) {
auto it = m_accessors.find(_name);
if (it != m_accessors.end()) {
return;
}
auto entry = m_accessors.emplace(_name, Accessor{_name, this});
if (!entry.second) {
return; // hmm, already added..
}
Accessor& attr = (*entry.first).second;
// push 'feature' obj onto stack
if (!duk_get_global_string(m_ctx, "feature")) {
LOGE("'feature' not in global scope");
return;
}
// push property name
duk_push_string(m_ctx, _name.c_str());
// push getter function
duk_push_c_function(m_ctx, jsPropertyGetter, 0 /*nargs*/);
duk_push_pointer(m_ctx, (void*)&attr);
duk_put_prop_string(m_ctx, -2, ATTR_ID);
// push setter function
// duk_push_c_function(m_ctx, jsPropertySetter, 1 /*nargs*/);
// duk_push_pointer(m_ctx, (void*)&attr);
// duk_put_prop_string(m_ctx, -2, ATTR_ID);
// stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ]
duk_def_prop(m_ctx, -3,
DUK_DEFPROP_HAVE_GETTER |
// DUK_DEFPROP_HAVE_SETTER |
// DUK_DEFPROP_WRITABLE |
// DUK_DEFPROP_HAVE_ENUMERABLE |
// DUK_DEFPROP_ENUMERABLE |
// DUK_DEFPROP_HAVE_CONFIGURABLE |
0);
// pop feature obj
duk_pop(m_ctx);
DUMP("addAccessor\n");
}
duk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) {
// Storing state for a Duktape/C function:
// http://duktape.org/guide.html#programming.9
duk_push_current_function(_ctx);
duk_get_prop_string(_ctx, -1, ATTR_ID);
auto* attr = static_cast<const Accessor*> (duk_to_pointer(_ctx, -1));
if (!attr || !attr->ctx || !attr->ctx->m_feature) {
LOGE("Error: no context set %p %p",
attr,
attr ? attr->ctx : nullptr);
duk_pop(_ctx);
return 0;
}
auto it = attr->ctx->m_feature->props.get(attr->key);
if (it.is<std::string>()) {
duk_push_string(_ctx, it.get<std::string>().c_str());
} else if (it.is<float>()) {
duk_push_number(_ctx, it.get<float>());
} else {
duk_push_undefined(_ctx);
}
return 1;
}
duk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) {
return 0;
}
}
<commit_msg>fix: StyleContext, cleanup stack on error<commit_after>#include "styleContext.h"
#include "platform.h"
#include "builders.h"
#include "scene/scene.h"
#include "data/propertyItem.h"
#define DUMP(...) // do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0)
#define DBG(...) do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0)
namespace Tangram {
const static char DATA_ID[] = "\xff""\xff""data";
const static char ATTR_ID[] = "\xff""\xff""attr";
const static char FUNC_ID[] = "\xff""\xff""fns";
StyleContext::StyleContext() {
m_ctx = duk_create_heap_default();
// add empty feature_object
duk_push_object(m_ctx);
// assign instance to feature_object
duk_push_pointer(m_ctx, this);
if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) {
LOGE("Ctx not assigned");
}
// put object in global scope
if (!duk_put_global_string(m_ctx, "feature")) {
LOGE("Feature not assigned");
}
DUMP("init\n");
}
StyleContext::~StyleContext() {
duk_destroy_heap(m_ctx);
}
void StyleContext::initFunctions(const Scene& _scene) {
if (_scene.id == m_sceneId) {
return;
}
m_sceneId = _scene.id;
auto arr_idx = duk_push_array(m_ctx);
int id = 0;
for (auto& function : _scene.functions()) {
LOGD("compile '%s'", function.c_str());
duk_push_string(m_ctx, function.c_str());
duk_push_string(m_ctx, "");
if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) {
duk_put_prop_index(m_ctx, arr_idx, id);
} else {
LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
}
id++;
}
if (!duk_put_global_string(m_ctx, FUNC_ID)) {
LOGE("'fns' object not set");
}
DUMP("setScene - %d functions\n", id);
}
void StyleContext::setFeature(const Feature& _feature) {
m_feature = &_feature;
for (auto& item : _feature.props.items()) {
addAccessor(item.key);
}
}
void StyleContext::setGlobalZoom(float _zoom) {
static const std::string _key("$zoom");
if (_zoom != m_globalZoom) {
setGlobal(_key, _zoom);
}
}
void StyleContext::setGlobal(const std::string& _key, const Value& _val) {
Value& entry = m_globals[_key];
if (entry == _val) { return; }
entry = _val;
if (_val.is<float>()) {
duk_push_number(m_ctx, _val.get<float>());
duk_put_global_string(m_ctx, _key.c_str());
if (_key == "$zoom") { m_globalZoom = _val.get<float>(); }
} else if (_val.is<std::string>()) {
duk_push_string(m_ctx, _val.get<std::string>().c_str());
duk_put_global_string(m_ctx, _key.c_str());
}
}
const Value& StyleContext::getGlobal(const std::string& _key) const {
const static Value NOT_FOUND(none_type{});
auto it = m_globals.find(_key);
if (it != m_globals.end()) {
return it->second;
}
return NOT_FOUND;
}
void StyleContext::clear() {
m_feature = nullptr;
}
bool StyleContext::addFunction(const std::string& _name, const std::string& _func) {
duk_push_string(m_ctx, _func.c_str());
duk_push_string(m_ctx, _name.c_str());
if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) {
LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1));
return false;
}
// Put function in global scope
duk_put_global_string(m_ctx, _name.c_str());
DUMP("addFunction\n");
return true;
}
bool StyleContext::evalFilter(FunctionID _id) const {
if (!duk_get_global_string(m_ctx, FUNC_ID)) {
LOGE("EvalFilterFn - functions not initialized");
return false;
}
if (!duk_get_prop_index(m_ctx, -1, _id)) {
LOGE("EvalFilterFn - function %d not set", _id);
duk_pop(m_ctx);
DBG("evalFilterFn\n");
return false;
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
duk_pop(m_ctx);
DBG("evalFilterFn\n");
return false;
}
bool result = false;
if (duk_is_boolean(m_ctx, -1)) {
result = duk_get_boolean(m_ctx, -1);
}
// pop result
duk_pop(m_ctx);
// pop fns obj
duk_pop(m_ctx);
DUMP("evalFilterFn\n");
return result;
}
bool StyleContext::evalFilterFn(const std::string& _name) {
if (!duk_get_global_string(m_ctx, _name.c_str())) {
LOGE("EvalFilter %s", _name.c_str());
return false;
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
}
bool result = false;
if (duk_is_boolean(m_ctx, -1)) {
result = duk_get_boolean(m_ctx, -1);
}
// pop result
duk_pop(m_ctx);
DUMP("evalFilterFn\n");
return result;
}
bool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const {
_val = none_type{};
if (duk_is_string(m_ctx, -1)) {
std::string value(duk_get_string(m_ctx, -1));
_val = StyleParam::parseString(_key, value);
} else if (duk_is_boolean(m_ctx, -1)) {
bool value = duk_get_boolean(m_ctx, -1);
switch (_key) {
case StyleParamKey::interactive:
case StyleParamKey::visible:
_val = value;
break;
case StyleParamKey::extrude:
_val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);
break;
default:
break;
}
} else if (duk_is_array(m_ctx, -1)) {
duk_get_prop_string(m_ctx, -1, "length");
int len = duk_get_int(m_ctx, -1);
duk_pop(m_ctx);
switch (_key) {
case StyleParamKey::extrude: {
if (len != 2) {
LOGW("Wrong array size for extrusion: '%d'.", len);
break;
}
duk_get_prop_index(m_ctx, -1, 0);
double v1 = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 1);
double v2 = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
_val = glm::vec2(v1, v2);
break;
}
case StyleParamKey::color:
case StyleParamKey::outline_color:
case StyleParamKey::font_fill:
case StyleParamKey::font_stroke_color: {
if (len < 3 || len > 4) {
LOGW("Wrong array size for color: '%d'.", len);
break;
}
duk_get_prop_index(m_ctx, -1, 0);
double r = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 1);
double g = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
duk_get_prop_index(m_ctx, -1, 2);
double b = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
double a = 1.0;
if (len == 4) {
duk_get_prop_index(m_ctx, -1, 3);
a = duk_get_number(m_ctx, -1);
duk_pop(m_ctx);
}
_val = (((uint32_t)(255.0 * a) & 0xff) << 24) |
(((uint32_t)(255.0 * r) & 0xff)<< 16) |
(((uint32_t)(255.0 * g) & 0xff)<< 8) |
(((uint32_t)(255.0 * b) & 0xff));
break;
}
default:
break;
}
} else if (duk_is_number(m_ctx, -1)) {
switch (_key) {
case StyleParamKey::width:
case StyleParamKey::outline_width: {
// TODO more efficient way to return pixels.
// atm this only works by return value as string
double v = duk_get_number(m_ctx, -1);
_val = StyleParam::Width{static_cast<float>(v)};
break;
}
case StyleParamKey::font_stroke_width: {
_val = static_cast<float>(duk_get_number(m_ctx, -1));
break;
}
case StyleParamKey::order:
case StyleParamKey::priority:
case StyleParamKey::color:
case StyleParamKey::outline_color:
case StyleParamKey::font_fill:
case StyleParamKey::font_stroke_color: {
_val = static_cast<uint32_t>(duk_get_uint(m_ctx, -1));
break;
}
default:
break;
}
} else {
LOGW("Unhandled return type from Javascript function.");
}
duk_pop(m_ctx);
DUMP("parseStyleResult\n");
return !_val.is<none_type>();
}
bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const {
if (!duk_get_global_string(m_ctx, FUNC_ID)) {
LOGE("EvalFilterFn - functions array not initialized");
return false;
}
if (!duk_get_prop_index(m_ctx, -1, _id)) {
LOGE("EvalFilterFn - function %d not set", _id);
}
// pop fns array
duk_remove(m_ctx, -2);
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
return false;
}
return parseStyleResult(_key, _val);
}
bool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) {
if (!duk_get_global_string(m_ctx, name.c_str())) {
LOGE("EvalFilter %s", name.c_str());
return false;
}
if (duk_pcall(m_ctx, 0) != 0) {
LOGE("EvalStyleFn: %s", duk_safe_to_string(m_ctx, -1));
duk_pop(m_ctx);
return false;
}
return parseStyleResult(_key, _val);
}
void StyleContext::addAccessor(const std::string& _name) {
auto it = m_accessors.find(_name);
if (it != m_accessors.end()) {
return;
}
auto entry = m_accessors.emplace(_name, Accessor{_name, this});
if (!entry.second) {
return; // hmm, already added..
}
Accessor& attr = (*entry.first).second;
// push 'feature' obj onto stack
if (!duk_get_global_string(m_ctx, "feature")) {
LOGE("'feature' not in global scope");
return;
}
// push property name
duk_push_string(m_ctx, _name.c_str());
// push getter function
duk_push_c_function(m_ctx, jsPropertyGetter, 0 /*nargs*/);
duk_push_pointer(m_ctx, (void*)&attr);
duk_put_prop_string(m_ctx, -2, ATTR_ID);
// push setter function
// duk_push_c_function(m_ctx, jsPropertySetter, 1 /*nargs*/);
// duk_push_pointer(m_ctx, (void*)&attr);
// duk_put_prop_string(m_ctx, -2, ATTR_ID);
// stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ]
duk_def_prop(m_ctx, -3,
DUK_DEFPROP_HAVE_GETTER |
// DUK_DEFPROP_HAVE_SETTER |
// DUK_DEFPROP_WRITABLE |
// DUK_DEFPROP_HAVE_ENUMERABLE |
// DUK_DEFPROP_ENUMERABLE |
// DUK_DEFPROP_HAVE_CONFIGURABLE |
0);
// pop feature obj
duk_pop(m_ctx);
DUMP("addAccessor\n");
}
duk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) {
// Storing state for a Duktape/C function:
// http://duktape.org/guide.html#programming.9
duk_push_current_function(_ctx);
duk_get_prop_string(_ctx, -1, ATTR_ID);
auto* attr = static_cast<const Accessor*> (duk_to_pointer(_ctx, -1));
if (!attr || !attr->ctx || !attr->ctx->m_feature) {
LOGE("Error: no context set %p %p",
attr,
attr ? attr->ctx : nullptr);
duk_pop(_ctx);
return 0;
}
auto it = attr->ctx->m_feature->props.get(attr->key);
if (it.is<std::string>()) {
duk_push_string(_ctx, it.get<std::string>().c_str());
} else if (it.is<float>()) {
duk_push_number(_ctx, it.get<float>());
} else {
duk_push_undefined(_ctx);
}
return 1;
}
duk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) {
return 0;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Games/GameManager.hpp>
namespace Hearthstonepp
{
void GameManager::ProcessNextStep(Game& game, Step step)
{
switch (step)
{
case Step::BEGIN_FIRST:
game.step = step;
game.BeginFirst();
break;
default:
break;
}
}
} // namespace Hearthstonepp<commit_msg>[ci skip] feat(game-state): Add code to process BEGIN_SHUFFLE step<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Games/GameManager.hpp>
namespace Hearthstonepp
{
void GameManager::ProcessNextStep(Game& game, Step step)
{
switch (step)
{
case Step::BEGIN_FIRST:
game.step = step;
game.BeginFirst();
break;
case Step::BEGIN_SHUFFLE:
game.step = step;
game.BeginShuffle();
break;
default:
break;
}
}
} // namespace Hearthstonepp<|endoftext|> |
<commit_before>#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"
using namespace cv;
using namespace std;
const char *win = "Flying Pancake";
static bool reverseMirror = true;
int main(int argc, char **argv)
{
if (argc > 2) {
fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
exit(1);
}
else if (argc == 2) {
if (!strcmp(argv[1], "-r"))
reverseMirror = false;
else {
fprintf(stderr, "Usage: videoBall [-r]\n");
exit(1);
}
}
int cam = 0; // default camera
VideoCapture cap(cam);
if (!cap.isOpened()) {
fprintf(stderr, "Error: Cannot open camera %d\n", cam);
exit(1);
}
namedWindow(win, CV_WINDOW_AUTOSIZE);
Mat fgMaskMOG;
BackgroundSubtractorMOG2 MOG;
Mat inputFrame, outFrame;
cap >> inputFrame;
int height = inputFrame.rows;
int width = inputFrame.cols;
// initial position
Point pt;
pt.x = width / 2;
pt.y = height / 2;
// initial momentum
Point momentum;
momentum.x = 0;
momentum.y = 0;
Mat circ;
cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
cvtColor(inputFrame, circ, CV_BGR2GRAY);
int count = 0;
int sum;
Mat reverseFrame;
Mat ballFrame, handFrame;
Mat foregroundMask, backgroundMask;
Point small;
int score=0, left=0, right=0;
int timer = 50; // 50 frames between points are scored
while(++count) {
cap >> inputFrame;
if (reverseMirror) {
inputFrame.copyTo(reverseFrame);
flip(reverseFrame, inputFrame, 1);
}
cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
MOG(inputFrame, fgMaskMOG);
foregroundMask = fgMaskMOG > THRESH;
backgroundMask = fgMaskMOG <= THRESH;
score = pongDir(&momentum, &pt, height, width);
if (!score) { // still moving
// blank canvas
circ.setTo(Scalar(0, 0, 0));
Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
ballFrame = circ(ballRegion);
fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); // clean up
fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
handFrame = fgMaskMOG(ballRegion);
int halfRad = RADIUS / 2;
// top left
small.x = halfRad; small.y = halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x < width / 2 ? sum : 0;
momentum.y += sum;
// top right
small.x = 3 * halfRad; small.y = halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x >= width / 2 ? -sum : 0;
momentum.y += sum;
// bottom left
small.x = halfRad; small.y = 3 * halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x < width / 2 ? sum : 0;
momentum.y -= sum;
// bottom right
small.x = 3 * halfRad; small.y = 3 * halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x >= width / 2 ? -sum : 0;
momentum.y -= sum;
}else if (!timer--){
//someone scored, so decrement timer and reset when timer = 0
timer = 50;
reset_board(&pt, &momentum, width, height);
if (score >0){ left +=1; }
else{ right += 1; }
}else if ( right >= 5 || left >= 5){
//Game over, stop playing
}
// outFrame -= Scalar(50,50,50);
// cvtColor(foregroundMask, inputFrame, CV_LOAD_IMAGE_COLOR);
// outFrame.setTo(Scalar(0, 0, 0));
// outFrame.setTo(Scalar(255, 255, 255), foregroundMask);
//Set the color of the ball here.
cvtColor(foregroundMask,foregroundMask ,COLOR_GRAY2BGR);
addWeighted(outFrame, 0.75, foregroundMask, 0.25, 1, outFrame, -1);
drawCircle(outFrame, pt, RADIUS, Scalar( 0, 0, 255 ));
// imshow(win, outFrame);
imshow(win,outFrame);
// listening for key press
char c = waitKey(30);
if (c >= 0) {
if (c == 'r') {
pt.x = width / 2;
pt.y = height / 2;
continue;
}
else
break;
}
}
return 0;
}
<commit_msg>Working game<commit_after>#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"
using namespace cv;
using namespace std;
const char *win = "Flying Pancake";
static bool reverseMirror = true;
int main(int argc, char **argv)
{
if (argc > 2) {
fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
exit(1);
}
else if (argc == 2) {
if (!strcmp(argv[1], "-r"))
reverseMirror = false;
else {
fprintf(stderr, "Usage: videoBall [-r]\n");
exit(1);
}
}
int cam = 0; // default camera
VideoCapture cap(cam);
if (!cap.isOpened()) {
fprintf(stderr, "Error: Cannot open camera %d\n", cam);
exit(1);
}
namedWindow(win, CV_WINDOW_AUTOSIZE);
Mat fgMaskMOG;
BackgroundSubtractorMOG2 MOG;
Mat inputFrame, outFrame, scoreFrame;
cap >> inputFrame;
int height = inputFrame.rows;
int width = inputFrame.cols;
// initial position
Point pt;
pt.x = width / 2;
pt.y = height / 2;
// initial momentum
Point momentum;
momentum.x = 0;
momentum.y = 0;
Mat circ;
cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
cvtColor(inputFrame, scoreFrame, CV_LOAD_IMAGE_COLOR);
cvtColor(inputFrame, circ, CV_BGR2GRAY);
int count = 0;
int sum;
Mat reverseFrame;
Mat ballFrame, handFrame;
Mat foregroundMask, backgroundMask;
Point small;
int score=0, left=0, right=0;
int timer = 50; // 50 frames between points are scored
//Initialize the scoreFrame here
scoreFrame = scoreFrame > 256;
putText(scoreFrame, to_string(left), Point(50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 3, Scalar(255,255,255), 1, 8, false );
// Put right score on right
putText(scoreFrame, to_string(right), Point(width-50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 3, Scalar(255,255,255), 1, 8, false );
while(++count) {
cap >> inputFrame;
if (reverseMirror) {
inputFrame.copyTo(reverseFrame);
flip(reverseFrame, inputFrame, 1);
}
cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
MOG(inputFrame, fgMaskMOG);
foregroundMask = fgMaskMOG > THRESH;
backgroundMask = fgMaskMOG <= THRESH;
score = pongDir(&momentum, &pt, height, width);
if (!score) { // still moving
// blank canvas
circ.setTo(Scalar(0, 0, 0));
Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
ballFrame = circ(ballRegion);
fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); // clean up
fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
handFrame = fgMaskMOG(ballRegion);
int halfRad = RADIUS / 2;
// top left
small.x = halfRad; small.y = halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x < width / 2 ? sum : 0;
momentum.y += sum;
// top right
small.x = 3 * halfRad; small.y = halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x >= width / 2 ? -sum : 0;
momentum.y += sum;
// bottom left
small.x = halfRad; small.y = 3 * halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x < width / 2 ? sum : 0;
momentum.y -= sum;
// bottom right
small.x = 3 * halfRad; small.y = 3 * halfRad;
sum = getOverlap(&ballFrame, &handFrame, &small);
momentum.x += pt.x >= width / 2 ? -sum : 0;
momentum.y -= sum;
}else if (!timer--){
//someone scored, so decrement timer and reset when timer = 0
timer = 50;
reset_board(&pt, &momentum, width, height);
if (score >0){ left +=1; }
else{ right += 1; }
scoreFrame = scoreFrame > 256;
putText(scoreFrame, to_string(left), Point(50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false );
// Put right score on right
putText(scoreFrame, to_string(right), Point(width-50,height-50), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar(255,255,255), 1, 8, false );
if ( right >= 5 || left >= 5){
//Game over, stop playing
// game_over(right,left);
break;
}
}
// outFrame -= Scalar(50,50,50);
// cvtColor(foregroundMask, inputFrame, CV_LOAD_IMAGE_COLOR);
// outFrame.setTo(Scalar(0, 0, 0));
// outFrame.setTo(Scalar(255, 255, 255), foregroundMask);
//Set the color of the ball here.
cvtColor(foregroundMask,foregroundMask ,COLOR_GRAY2BGR);
addWeighted(outFrame, 0.75, foregroundMask, 0.25, 1, outFrame, -1);
drawCircle(outFrame, pt, RADIUS, Scalar( 0, 0, 255 ));
// Put score frame onto image
addWeighted(outFrame, 0.75, scoreFrame, 1.0, 1, outFrame, -1);
imshow(win,outFrame);
// listening for key press
char c = waitKey(30);
if (c >= 0) {
if (c == 'r') {
pt.x = width / 2;
pt.y = height / 2;
continue;
}
else
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#include <Python.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/proto_api.h>
#include <google/protobuf/message_lite.h>
namespace {
// C++ API. Clients get at this via proto_api.h
struct ApiImplementation : google::protobuf::python::PyProto_API {
const google::protobuf::Message*
GetMessagePointer(PyObject* msg) const override {
return google::protobuf::python::PyMessage_GetMessagePointer(msg);
}
google::protobuf::Message*
GetMutableMessagePointer(PyObject* msg) const override {
return google::protobuf::python::PyMessage_GetMutableMessagePointer(msg);
}
};
} // namespace
static PyObject* GetPythonProto3PreserveUnknownsDefault(
PyObject* /*m*/, PyObject* /*args*/) {
if (google::protobuf::internal::GetProto3PreserveUnknownsDefault()) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject* SetPythonProto3PreserveUnknownsDefault(
PyObject* /*m*/, PyObject* arg) {
if (!arg || !PyBool_Check(arg)) {
PyErr_SetString(
PyExc_TypeError,
"Argument to SetPythonProto3PreserveUnknownsDefault must be boolean");
return NULL;
}
google::protobuf::internal::SetProto3PreserveUnknownsDefault(PyObject_IsTrue(arg));
Py_RETURN_NONE;
}
static const char module_docstring[] =
"python-proto2 is a module that can be used to enhance proto2 Python API\n"
"performance.\n"
"\n"
"It provides access to the protocol buffers C++ reflection API that\n"
"implements the basic protocol buffer functions.";
static PyMethodDef ModuleMethods[] = {
{"SetAllowOversizeProtos",
(PyCFunction)google::protobuf::python::cmessage::SetAllowOversizeProtos,
METH_O, "Enable/disable oversize proto parsing."},
// DO NOT USE: For migration and testing only.
{"GetPythonProto3PreserveUnknownsDefault",
(PyCFunction)GetPythonProto3PreserveUnknownsDefault,
METH_NOARGS, "Get Proto3 preserve unknowns default."},
// DO NOT USE: For migration and testing only.
{"SetPythonProto3PreserveUnknownsDefault",
(PyCFunction)SetPythonProto3PreserveUnknownsDefault,
METH_O, "Enable/disable proto3 unknowns preservation."},
{ NULL, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"_message",
module_docstring,
-1,
ModuleMethods, /* m_methods */
NULL,
NULL,
NULL,
NULL
};
#define INITFUNC PyInit__message
#define INITFUNC_ERRORVAL NULL
#else // Python 2
#define INITFUNC init_message
#define INITFUNC_ERRORVAL
#endif
extern "C" {
PyMODINIT_FUNC INITFUNC(void) {
PyObject* m;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&_module);
#else
m = Py_InitModule3("_message", ModuleMethods,
module_docstring);
#endif
if (m == NULL) {
return INITFUNC_ERRORVAL;
}
if (!google::protobuf::python::InitProto2MessageModule(m)) {
Py_DECREF(m);
return INITFUNC_ERRORVAL;
}
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
}
<commit_msg>Update message_module.cc (#4835)<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#include <Python.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/proto_api.h>
#include <google/protobuf/message_lite.h>
namespace {
// C++ API. Clients get at this via proto_api.h
struct ApiImplementation : google::protobuf::python::PyProto_API {
const google::protobuf::Message*
GetMessagePointer(PyObject* msg) const override {
return google::protobuf::python::PyMessage_GetMessagePointer(msg);
}
google::protobuf::Message*
GetMutableMessagePointer(PyObject* msg) const override {
return google::protobuf::python::PyMessage_GetMutableMessagePointer(msg);
}
};
} // namespace
static PyObject* GetPythonProto3PreserveUnknownsDefault(
PyObject* /*m*/, PyObject* /*args*/) {
if (google::protobuf::internal::GetProto3PreserveUnknownsDefault()) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject* SetPythonProto3PreserveUnknownsDefault(
PyObject* /*m*/, PyObject* arg) {
if (!arg || !PyBool_Check(arg)) {
PyErr_SetString(
PyExc_TypeError,
"Argument to SetPythonProto3PreserveUnknownsDefault must be boolean");
return NULL;
}
google::protobuf::internal::SetProto3PreserveUnknownsDefault(PyObject_IsTrue(arg));
Py_RETURN_NONE;
}
static const char module_docstring[] =
"python-proto2 is a module that can be used to enhance proto2 Python API\n"
"performance.\n"
"\n"
"It provides access to the protocol buffers C++ reflection API that\n"
"implements the basic protocol buffer functions.";
static PyMethodDef ModuleMethods[] = {
{"SetAllowOversizeProtos",
(PyCFunction)google::protobuf::python::cmessage::SetAllowOversizeProtos,
METH_O, "Enable/disable oversize proto parsing."},
// DO NOT USE: For migration and testing only.
{"GetPythonProto3PreserveUnknownsDefault",
(PyCFunction)GetPythonProto3PreserveUnknownsDefault,
METH_NOARGS, "Get Proto3 preserve unknowns default."},
// DO NOT USE: For migration and testing only.
{"SetPythonProto3PreserveUnknownsDefault",
(PyCFunction)SetPythonProto3PreserveUnknownsDefault,
METH_O, "Enable/disable proto3 unknowns preservation."},
{ NULL, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"_message",
module_docstring,
-1,
ModuleMethods, /* m_methods */
NULL,
NULL,
NULL,
NULL
};
#define INITFUNC PyInit__message
#define INITFUNC_ERRORVAL NULL
#else // Python 2
#define INITFUNC init_message
#define INITFUNC_ERRORVAL
#endif
extern "C" {
PyMODINIT_FUNC INITFUNC(void) {
PyObject* m;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&_module);
#else
m = Py_InitModule3("_message", ModuleMethods,
module_docstring);
#endif
if (m == NULL) {
return INITFUNC_ERRORVAL;
}
if (!google::protobuf::python::InitProto2MessageModule(m)) {
Py_DECREF(m);
return INITFUNC_ERRORVAL;
}
// Adds the C++ API
if (PyObject* api =
PyCapsule_New(new ApiImplementation(),
google::protobuf::python::PyProtoAPICapsuleName(), NULL)) {
PyModule_AddObject(m, "proto_API", api);
} else {
return INITFUNC_ERRORVAL;
}
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
}
<|endoftext|> |
<commit_before>/**
* @file MelFilter.cpp
*
* Triangular filters in Mel frequency scale.
*
* This file is part of the Aquila DSP library.
* Aquila is free software, licensed under the MIT/X11 License. A copy of
* the license is provided with the library in the LICENSE file.
*
* @package Aquila
* @version 3.0.0-dev
* @author Zbigniew Siciarz
* @date 2007-2013
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @since 0.3.3
*/
#include "MelFilter.h"
#include <utility>
namespace Aquila
{
/**
* Creates the filter and sets sample frequency.
*
* @param sampleFrequency sample frequency in Hz
*/
MelFilter::MelFilter(FrequencyType sampleFrequency):
m_sampleFrequency(sampleFrequency)
{
}
/**
* Move constructor.
*
* @param other other filter to be moved from
*/
MelFilter::MelFilter(MelFilter&& other):
m_sampleFrequency(other.m_sampleFrequency),
m_spectrum(std::move(other.m_spectrum))
{
}
/**
* Designs the Mel filter and creates triangular spectrum.
*
* @param filterNum which filter in a sequence it is
* @param melFilterWidth filter width in Mel scale (eg. 200)
* @param N filter spectrum size (must be the same as filtered spectrum)
*/
void MelFilter::createFilter(unsigned short filterNum,
std::size_t melFilterWidth, std::size_t N)
{
// calculate frequencies in Mel scale
FrequencyType melMinFreq = filterNum * melFilterWidth / 2.0;
FrequencyType melCenterFreq = melMinFreq + melFilterWidth / 2.0;
FrequencyType melMaxFreq = melMinFreq + melFilterWidth;
// convert frequencies to linear scale
FrequencyType minFreq = melToLinear(melMinFreq);
FrequencyType centerFreq = melToLinear(melCenterFreq);
FrequencyType maxFreq = melToLinear(melMaxFreq);
// generate filter spectrum in linear scale
generateFilterSpectrum(minFreq, centerFreq, maxFreq, N);
}
/**
* Returns a single value computed by multiplying signal spectrum with
* Mel filter spectrum and summing all the products.
*
* @param dataSpectrum complex signal spectrum
* @return dot product of the spectra
*/
double MelFilter::apply(const SpectrumType& dataSpectrum) const
{
double value = 0.0;
const std::size_t N = dataSpectrum.size();
// iteration over first half of the spectrum
for (unsigned int i = 0; i < N / 2 - 1; ++i)
{
value += std::abs(dataSpectrum[i]) * m_spectrum[i];
}
return value;
}
void MelFilter::generateFilterSpectrum(FrequencyType minFreq,
FrequencyType centerFreq,
FrequencyType maxFreq, std::size_t N)
{
m_spectrum.clear();
m_spectrum.resize(N, 0.0);
// find spectral peak positions corresponding to frequencies
std::size_t minPos = static_cast<std::size_t>(N * minFreq / m_sampleFrequency);
std::size_t centerPos = static_cast<std::size_t>(N * centerFreq / m_sampleFrequency);
std::size_t maxPos = static_cast<std::size_t>(N * maxFreq / m_sampleFrequency);
const double max = 1.0;
// outside the triangle spectrum values are 0, guaranteed by
// earlier call to resize
for (unsigned int k = minPos; k <= maxPos; ++k)
{
if (k < centerPos)
{
// in the triangle on the ascending slope
m_spectrum[k] = (k - minPos) * max / (centerPos - minPos);
}
else
{
// in the triangle on the descending slope
m_spectrum[k] = (maxPos - k) * max / (maxPos - centerPos);
}
}
}
}
<commit_msg>Added a descriptive comment for generateFilterSpectrum.<commit_after>/**
* @file MelFilter.cpp
*
* Triangular filters in Mel frequency scale.
*
* This file is part of the Aquila DSP library.
* Aquila is free software, licensed under the MIT/X11 License. A copy of
* the license is provided with the library in the LICENSE file.
*
* @package Aquila
* @version 3.0.0-dev
* @author Zbigniew Siciarz
* @date 2007-2013
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @since 0.3.3
*/
#include "MelFilter.h"
#include <utility>
namespace Aquila
{
/**
* Creates the filter and sets sample frequency.
*
* @param sampleFrequency sample frequency in Hz
*/
MelFilter::MelFilter(FrequencyType sampleFrequency):
m_sampleFrequency(sampleFrequency)
{
}
/**
* Move constructor.
*
* @param other other filter to be moved from
*/
MelFilter::MelFilter(MelFilter&& other):
m_sampleFrequency(other.m_sampleFrequency),
m_spectrum(std::move(other.m_spectrum))
{
}
/**
* Designs the Mel filter and creates triangular spectrum.
*
* @param filterNum which filter in a sequence it is
* @param melFilterWidth filter width in Mel scale (eg. 200)
* @param N filter spectrum size (must be the same as filtered spectrum)
*/
void MelFilter::createFilter(unsigned short filterNum,
std::size_t melFilterWidth, std::size_t N)
{
// calculate frequencies in Mel scale
FrequencyType melMinFreq = filterNum * melFilterWidth / 2.0;
FrequencyType melCenterFreq = melMinFreq + melFilterWidth / 2.0;
FrequencyType melMaxFreq = melMinFreq + melFilterWidth;
// convert frequencies to linear scale
FrequencyType minFreq = melToLinear(melMinFreq);
FrequencyType centerFreq = melToLinear(melCenterFreq);
FrequencyType maxFreq = melToLinear(melMaxFreq);
// generate filter spectrum in linear scale
generateFilterSpectrum(minFreq, centerFreq, maxFreq, N);
}
/**
* Returns a single value computed by multiplying signal spectrum with
* Mel filter spectrum and summing all the products.
*
* @param dataSpectrum complex signal spectrum
* @return dot product of the spectra
*/
double MelFilter::apply(const SpectrumType& dataSpectrum) const
{
double value = 0.0;
const std::size_t N = dataSpectrum.size();
// iteration over first half of the spectrum
for (unsigned int i = 0; i < N / 2 - 1; ++i)
{
value += std::abs(dataSpectrum[i]) * m_spectrum[i];
}
return value;
}
/**
* Generates a vector of values shaped as a triangular filter.
*
* ^ [2]
* | /\
* | / \
* | / \
* |_____________________/ \__________________
* +--------------------[1]----[3]---------------------> f
*
* @param minFreq frequency at [1] in linear scale
* @param centerFreq frequency at [2] in linear scale
* @param maxFreq frequency at [3] in linear scale
* @param N length of the spectrum
*/
void MelFilter::generateFilterSpectrum(FrequencyType minFreq,
FrequencyType centerFreq,
FrequencyType maxFreq, std::size_t N)
{
m_spectrum.clear();
m_spectrum.resize(N, 0.0);
// find spectral peak positions corresponding to frequencies
std::size_t minPos = static_cast<std::size_t>(N * minFreq / m_sampleFrequency);
std::size_t centerPos = static_cast<std::size_t>(N * centerFreq / m_sampleFrequency);
std::size_t maxPos = static_cast<std::size_t>(N * maxFreq / m_sampleFrequency);
const double max = 1.0;
// outside the triangle spectrum values are 0, guaranteed by
// earlier call to resize
for (unsigned int k = minPos; k <= maxPos; ++k)
{
if (k < centerPos)
{
// in the triangle on the ascending slope
m_spectrum[k] = (k - minPos) * max / (centerPos - minPos);
}
else
{
// in the triangle on the descending slope
m_spectrum[k] = (maxPos - k) * max / (maxPos - centerPos);
}
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/experimental/sampling_dataset_op.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/lib/random/simple_philox.h"
namespace tensorflow {
namespace data {
namespace experimental {
// Constants declared in sampling_dataset_op.h and used both here and in test
// cases.
/* static */ constexpr const char* const SamplingDatasetOp::kDatasetType;
/* static */ constexpr const char* const SamplingDatasetOp::kInputDataset;
/* static */ constexpr const char* const SamplingDatasetOp::kRate;
/* static */ constexpr const char* const SamplingDatasetOp::kSeed;
/* static */ constexpr const char* const SamplingDatasetOp::kSeed2;
/* static */ constexpr const char* const SamplingDatasetOp::kOutputTypes;
/* static */ constexpr const char* const SamplingDatasetOp::kOutputShapes;
class SamplingDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, float rate, int64 seed, int64 seed2,
const DatasetBase* input)
: DatasetBase(DatasetContext(ctx)),
rate_(rate),
seed_(seed),
seed2_(seed2),
input_(input) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, name_utils::IteratorPrefix(kDatasetType, prefix)},
seed_, seed2_));
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return input_->output_shapes();
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
bool IsStateful() const override { return input_->IsStateful(); }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* rate = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(rate_, &rate));
TF_RETURN_IF_ERROR(b->AddScalar(seed_, &seed));
TF_RETURN_IF_ERROR(b->AddScalar(seed2_, &seed2));
TF_RETURN_IF_ERROR(
b->AddDataset(this, {input_graph_node, rate, seed, seed2}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params, int64 seed, int64 seed2)
: DatasetIterator<Dataset>(params),
seed_(seed),
seed2_(seed2),
parent_generator_(seed, seed2),
generator_(&parent_generator_) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
bool rand_val_hit;
do {
{
tf_shared_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, out_tensors, end_of_sequence));
}
if (*end_of_sequence) {
mutex_lock l(mu_);
input_impl_.reset();
return Status::OK();
}
// generate a number from random uniform [0, 1)
float rand_val = Random();
rand_val_hit = rand_val < dataset()->rate_;
if (!rand_val_hit) {
// Clear the output tensor list since it doesn't match.
out_tensors->clear();
}
} while (!rand_val_hit);
*end_of_sequence = false;
return Status::OK();
}
protected:
void ResetRngs() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
// Reset the generators based on the current iterator seeds.
parent_generator_ = random::PhiloxRandom(seed_, seed2_);
generator_ =
random::SingleSampleAdapter<random::PhiloxRandom>(&parent_generator_);
generator_.Skip(num_random_samples_);
}
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
// Save state needed to restore the random number generators.
TF_RETURN_IF_ERROR(writer->WriteScalar(
this->full_name("num_random_samples"), num_random_samples_));
TF_RETURN_IF_ERROR(writer->WriteScalar(this->full_name("seed"), seed_));
TF_RETURN_IF_ERROR(writer->WriteScalar(this->full_name("seed2"), seed2_));
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
// Restore the random number generators.
TF_RETURN_IF_ERROR(reader->ReadScalar(
this->full_name("num_random_samples"), &num_random_samples_));
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed"), &seed_));
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed2"), &seed2_));
ResetRngs();
if (!reader->Contains(full_name("input_impl_empty"))) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
return Status::OK();
}
mutex mu_;
int64 seed_ GUARDED_BY(mu_);
int64 seed2_ GUARDED_BY(mu_);
private:
std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_);
float Random() {
mutex_lock l(mu_);
num_random_samples_++;
uint32 random_uint = generator_();
// PhiloxRandom returns 32-bit unsigned ints. Convert to float in [0,1)
// using the same method that the RandomUniform op uses.
return random::Uint32ToFloat(random_uint);
}
// random util
random::PhiloxRandom parent_generator_ GUARDED_BY(mu_);
random::SingleSampleAdapter<random::PhiloxRandom> generator_
GUARDED_BY(mu_);
int64 num_random_samples_ GUARDED_BY(mu_) = 0;
};
const float rate_;
const int64 seed_, seed2_;
const DatasetBase* const input_;
}; // SamplingDatasetOp::Dataset
SamplingDatasetOp::SamplingDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
// Create a new SamplingDatasetOp::Dataset, and return it as the output.
void SamplingDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
float rate;
int64 seed;
int64 seed2;
OP_REQUIRES_OK(ctx, ParseScalarArgument<float>(ctx, kRate, &rate));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, kSeed, &seed));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, kSeed2, &seed2));
if (seed == 0 && seed2 == 0) {
seed = random::New64();
seed2 = random::New64();
}
*output = new Dataset(ctx, rate, seed, seed2, input);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("SamplingDataset").Device(DEVICE_CPU),
SamplingDatasetOp);
} // namespace
} // namespace experimental
} // namespace data
} // namespace tensorflow
<commit_msg>Clean-up after merge<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/experimental/sampling_dataset_op.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/lib/random/simple_philox.h"
namespace tensorflow {
namespace data {
namespace experimental {
// Constants declared in sampling_dataset_op.h and used both here and in test
// cases.
/* static */ constexpr const char* const SamplingDatasetOp::kDatasetType;
/* static */ constexpr const char* const SamplingDatasetOp::kInputDataset;
/* static */ constexpr const char* const SamplingDatasetOp::kRate;
/* static */ constexpr const char* const SamplingDatasetOp::kSeed;
/* static */ constexpr const char* const SamplingDatasetOp::kSeed2;
/* static */ constexpr const char* const SamplingDatasetOp::kOutputTypes;
/* static */ constexpr const char* const SamplingDatasetOp::kOutputShapes;
class SamplingDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, float rate, int64 seed, int64 seed2,
const DatasetBase* input)
: DatasetBase(DatasetContext(ctx)),
rate_(rate),
seed_(seed),
seed2_(seed2),
input_(input) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, name_utils::IteratorPrefix(kDatasetType, prefix)},
seed_, seed2_));
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return input_->output_shapes();
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* rate = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(rate_, &rate));
TF_RETURN_IF_ERROR(b->AddScalar(seed_, &seed));
TF_RETURN_IF_ERROR(b->AddScalar(seed2_, &seed2));
TF_RETURN_IF_ERROR(
b->AddDataset(this, {input_graph_node, rate, seed, seed2}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params, int64 seed, int64 seed2)
: DatasetIterator<Dataset>(params),
seed_(seed),
seed2_(seed2),
parent_generator_(seed, seed2),
generator_(&parent_generator_) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
bool rand_val_hit;
do {
{
tf_shared_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, out_tensors, end_of_sequence));
}
if (*end_of_sequence) {
mutex_lock l(mu_);
input_impl_.reset();
return Status::OK();
}
// generate a number from random uniform [0, 1)
float rand_val = Random();
rand_val_hit = rand_val < dataset()->rate_;
if (!rand_val_hit) {
// Clear the output tensor list since it doesn't match.
out_tensors->clear();
}
} while (!rand_val_hit);
*end_of_sequence = false;
return Status::OK();
}
protected:
void ResetRngs() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
// Reset the generators based on the current iterator seeds.
parent_generator_ = random::PhiloxRandom(seed_, seed2_);
generator_ =
random::SingleSampleAdapter<random::PhiloxRandom>(&parent_generator_);
generator_.Skip(num_random_samples_);
}
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
// Save state needed to restore the random number generators.
TF_RETURN_IF_ERROR(writer->WriteScalar(
this->full_name("num_random_samples"), num_random_samples_));
TF_RETURN_IF_ERROR(writer->WriteScalar(this->full_name("seed"), seed_));
TF_RETURN_IF_ERROR(writer->WriteScalar(this->full_name("seed2"), seed2_));
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
// Restore the random number generators.
TF_RETURN_IF_ERROR(reader->ReadScalar(
this->full_name("num_random_samples"), &num_random_samples_));
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed"), &seed_));
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed2"), &seed2_));
ResetRngs();
if (!reader->Contains(full_name("input_impl_empty"))) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
return Status::OK();
}
mutex mu_;
int64 seed_ GUARDED_BY(mu_);
int64 seed2_ GUARDED_BY(mu_);
private:
std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_);
float Random() {
mutex_lock l(mu_);
num_random_samples_++;
uint32 random_uint = generator_();
// PhiloxRandom returns 32-bit unsigned ints. Convert to float in [0,1)
// using the same method that the RandomUniform op uses.
return random::Uint32ToFloat(random_uint);
}
// random util
random::PhiloxRandom parent_generator_ GUARDED_BY(mu_);
random::SingleSampleAdapter<random::PhiloxRandom> generator_
GUARDED_BY(mu_);
int64 num_random_samples_ GUARDED_BY(mu_) = 0;
};
const float rate_;
const int64 seed_, seed2_;
const DatasetBase* const input_;
}; // SamplingDatasetOp::Dataset
SamplingDatasetOp::SamplingDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
// Create a new SamplingDatasetOp::Dataset, and return it as the output.
void SamplingDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
float rate;
int64 seed;
int64 seed2;
OP_REQUIRES_OK(ctx, ParseScalarArgument<float>(ctx, kRate, &rate));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, kSeed, &seed));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, kSeed2, &seed2));
if (seed == 0 && seed2 == 0) {
seed = random::New64();
seed2 = random::New64();
}
*output = new Dataset(ctx, rate, seed, seed2, input);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("SamplingDataset").Device(DEVICE_CPU),
SamplingDatasetOp);
} // namespace
} // namespace experimental
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>// @(#)root/graf:$Name: $:$Id: TASPluginGS.cxx,v 1.1 2005/07/05 12:36:05 brun Exp $
// Author: Valeriy Onuchin 23/06/05
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TASPluginGS - allows to read PS/EPS/PDF files via GhostScript //
// //
// //
//////////////////////////////////////////////////////////////////////////
#include "TASPluginGS.h"
#include "TSystem.h"
#ifndef WIN32
# include <X11/Xlib.h>
#else
# include "Windows4root.h"
#endif
extern "C" {
#ifndef WIN32
# include <afterbase.h>
#else
# include <win32/config.h>
# include <win32/afterbase.h>
# define X_DISPLAY_MISSING 1
#endif
# include <import.h>
}
ClassImp(TASPluginGS)
//______________________________________________________________________________
TASPluginGS::TASPluginGS(const char *ext) : TASImagePlugin(ext)
{
// ctor
fInterpreter = gSystem->Which(gSystem->Getenv("PATH"), "gs", kExecutePermission);
}
//______________________________________________________________________________
TASPluginGS::~TASPluginGS()
{
// dtor
delete fInterpreter;
fInterpreter = 0;
}
//______________________________________________________________________________
ASImage *TASPluginGS::File2ASImage(const char *filename)
{
// read PS/EPS/PDF file and convert it to ASImage
if (!fInterpreter) {
Warning("File2ASImage", "GhostScript is not available");
return 0;
}
if (gSystem->AccessPathName(filename)) {
Warning("File2ASImage", "input file %s is not accessible", filename);
return 0;
}
// command line to execute
TString cmd = fInterpreter;
cmd += " -dSAFER -dBATCH -dNOPAUSE -dQUIET -sDEVICE=png16m -dGraphicsAlphaBits=4 -sOutputFile=- ";
cmd += filename;
FILE *in = gSystem->OpenPipe(cmd.Data(), "r");
if (!in) {
return 0;
}
const UInt_t kBuffLength = 32768;
static char buf[kBuffLength];
TString raw;
do {
Long_t r = fread(&buf, 1, kBuffLength, in);
raw.Append((const char*)&buf, r);
} while (!feof(in));
gSystem->ClosePipe(in);
ASImageImportParams params;
params.flags = 0;
params.width = 0;
params.height = 0 ;
params.filter = SCL_DO_ALL;
params.gamma = 0;
params.gamma_table = 0;
params.compression = 0;
params.format = ASA_ASImage;
params.search_path = 0;
params.subimage = 0;
ASImage *ret = PNGBuff2ASimage((CARD8 *)raw.Data(), ¶ms);
return ret;
}
<commit_msg>From Valeriy Onuchin: When image is created from EPS file the size of image is taken from BoundingBox values.<commit_after>// @(#)root/graf:$Name: $:$Id: TASPluginGS.cxx,v 1.2 2005/07/05 18:09:22 brun Exp $
// Author: Valeriy Onuchin 23/06/05
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TASPluginGS - allows to read PS/EPS/PDF files via GhostScript //
// //
// //
//////////////////////////////////////////////////////////////////////////
#include "TASPluginGS.h"
#include "TSystem.h"
#ifndef WIN32
# include <X11/Xlib.h>
#else
# include "Windows4root.h"
#endif
extern "C" {
#ifndef WIN32
# include <afterbase.h>
#else
# include <win32/config.h>
# include <win32/afterbase.h>
# define X_DISPLAY_MISSING 1
#endif
# include <import.h>
}
ClassImp(TASPluginGS)
//______________________________________________________________________________
TASPluginGS::TASPluginGS(const char *ext) : TASImagePlugin(ext)
{
// ctor
fInterpreter = gSystem->Which(gSystem->Getenv("PATH"), "gs", kExecutePermission);
}
//______________________________________________________________________________
TASPluginGS::~TASPluginGS()
{
// dtor
delete fInterpreter;
fInterpreter = 0;
}
//______________________________________________________________________________
ASImage *TASPluginGS::File2ASImage(const char *filename)
{
// read PS/EPS/PDF file and convert it to ASImage
if (!fInterpreter) {
Warning("File2ASImage", "GhostScript is not available");
return 0;
}
if (gSystem->AccessPathName(filename)) {
Warning("File2ASImage", "input file %s is not accessible", filename);
return 0;
}
TString ext = (strrchr(filename, '.') + 1);
ext.Strip();
ext.ToLower();
UInt_t width = 0;
UInt_t height = 0;
Bool_t eps = kFALSE;
if (ext == "eps") {
eps = kTRUE;
FILE *fd = fopen(filename, "r");
if (!fd) {
Warning("File2ASImage", "input file %s is not readable", filename);
return 0;
}
do {
char buf[128];
TString line = fgets(buf, 128, fd);
if (line.IsNull() || !line.BeginsWith("%")) break;
if (line.BeginsWith("%%BoundingBox:")) {
int lx, ly, ux, uy;
line = line(14, line.Length());
sscanf(line.Data(), "%d %d %d %d", &lx, &ly, &ux, &uy);
width = TMath::Abs(ux - lx);
height = TMath::Abs(uy - ly);
break;
}
} while (!feof(fd));
fclose(fd);
}
// command line to execute
TString cmd = fInterpreter;
if (eps) {
cmd += Form(" -g%dx%d", width, height);
}
cmd += " -dSAFER -dBATCH -dNOPAUSE -dQUIET -sDEVICE=png16m -dGraphicsAlphaBits=4 -sOutputFile=- ";
cmd += filename;
FILE *in = gSystem->OpenPipe(cmd.Data(), "r");
if (!in) {
return 0;
}
const UInt_t kBuffLength = 32768;
static char buf[kBuffLength];
TString raw;
do {
Long_t r = fread(&buf, 1, kBuffLength, in);
raw.Append((const char*)&buf, r);
} while (!feof(in));
gSystem->ClosePipe(in);
ASImageImportParams params;
params.flags = width;
params.width = height;
params.height = 0 ;
params.filter = SCL_DO_ALL;
params.gamma = 0;
params.gamma_table = 0;
params.compression = 0;
params.format = ASA_ASImage;
params.search_path = 0;
params.subimage = 0;
ASImage *ret = PNGBuff2ASimage((CARD8 *)raw.Data(), ¶ms);
return ret;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.