text
stringlengths 54
60.6k
|
---|
<commit_before>
#include <cstdint>
#include <limits>
//
// http://www.csee.umbc.edu/~tsimo1/CMSC455/IEEE-754-2008.pdf
// https://en.wikipedia.org/wiki/IEEE_754-1985
//
namespace ieee754
{
enum class Float
{
PositiveZero,
NegativeZero,
DenormalizedNumber,
PositiveInfinity,
NegativeInfinity,
NotANumber,
NormalizedNumber,
};
Float floatType (const float number)
{
static_assert
(
(sizeof(float) == sizeof(uint32_t)) && std::numeric_limits<float>::is_iec559,
"Single precision IEEE 754 floating point number has to be 32-bit."
);
const auto bits = *reinterpret_cast<const uint32_t* const>(&number);
/* *\
| IEEE 754 float 32-bit |
| |
| 31 30 24 23 0 |
| +-+--------+------------------------+ |
| | |exponent| fraction | |
| +-+--------+------------------------+ |
| ^ |
| sign |
\* */
const auto sign = uint32_t { bits & 0x80000000 } >> 31;
const auto exponentBias = uint32_t { bits & 0x7F800000 } >> 23;
const auto fraction = uint32_t { bits & 0x007FFFFF } >> 0;
if (exponentBias == 0x0)
{
if (fraction == 0x0)
{
return (sign == 0x1) ? Float::NegativeZero : Float::PositiveZero;
}
else
{
return Float::DenormalizedNumber;
}
}
else if (exponentBias == 0xFF)
{
if (fraction == 0x0)
{
return (sign == 0x1) ? Float::NegativeInfinity : Float::PositiveInfinity;
}
else
{
return Float::NotANumber;
}
}
else
{
return Float::NormalizedNumber;
}
}
}
#include <cassert>
void test (const float value, const ieee754::Float type)
{
assert(ieee754::floatType(value) == type);
}
int main ()
{
static_assert(std::numeric_limits<float>::has_infinity , "IEEE 754 requires infinity");
static_assert(std::numeric_limits<float>::has_quiet_NaN , "IEEE 754 requires qNaN");
static_assert(std::numeric_limits<float>::has_signaling_NaN, "IEEE 754 requires sNaN");
test(+0.0f , ieee754::Float::PositiveZero);
test(-0.0f , ieee754::Float::NegativeZero);
test(std::numeric_limits<float>::min() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::max() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::lowest() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::quiet_NaN() , ieee754::Float::NotANumber);
test(std::numeric_limits<float>::signaling_NaN(), ieee754::Float::NotANumber);
test(+std::numeric_limits<float>::infinity() , ieee754::Float::PositiveInfinity);
test(-std::numeric_limits<float>::infinity() , ieee754::Float::NegativeInfinity);
test(std::numeric_limits<float>::denorm_min() , ieee754::Float::DenormalizedNumber);
return 0;
}
<commit_msg>IEEE 754 float 32-bit memory layout fix<commit_after>
#include <cstdint>
#include <limits>
//
// http://www.csee.umbc.edu/~tsimo1/CMSC455/IEEE-754-2008.pdf
// https://en.wikipedia.org/wiki/IEEE_754-1985
//
namespace ieee754
{
enum class Float
{
PositiveZero,
NegativeZero,
DenormalizedNumber,
PositiveInfinity,
NegativeInfinity,
NotANumber,
NormalizedNumber,
};
Float floatType (const float number)
{
static_assert
(
(sizeof(float) == sizeof(uint32_t)) && std::numeric_limits<float>::is_iec559,
"Single precision IEEE 754 floating point number has to be 32-bit."
);
const auto bits = *reinterpret_cast<const uint32_t* const>(&number);
/* *\
| IEEE 754 float 32-bit |
| |
| 31 30 23 22 0 |
| +-+--------+------------------------+ |
| | |exponent| fraction | |
| +-+--------+------------------------+ |
| ^ |
| sign |
\* */
const auto sign = uint32_t { bits & 0x80000000 } >> 31;
const auto exponentBias = uint32_t { bits & 0x7F800000 } >> 23;
const auto fraction = uint32_t { bits & 0x007FFFFF } >> 0;
if (exponentBias == 0x0)
{
if (fraction == 0x0)
{
return (sign == 0x1) ? Float::NegativeZero : Float::PositiveZero;
}
else
{
return Float::DenormalizedNumber;
}
}
else if (exponentBias == 0xFF)
{
if (fraction == 0x0)
{
return (sign == 0x1) ? Float::NegativeInfinity : Float::PositiveInfinity;
}
else
{
return Float::NotANumber;
}
}
else
{
return Float::NormalizedNumber;
}
}
}
#include <cassert>
void test (const float value, const ieee754::Float type)
{
assert(ieee754::floatType(value) == type);
}
int main ()
{
static_assert(std::numeric_limits<float>::has_infinity , "IEEE 754 requires infinity");
static_assert(std::numeric_limits<float>::has_quiet_NaN , "IEEE 754 requires qNaN");
static_assert(std::numeric_limits<float>::has_signaling_NaN, "IEEE 754 requires sNaN");
test(+0.0f , ieee754::Float::PositiveZero);
test(-0.0f , ieee754::Float::NegativeZero);
test(std::numeric_limits<float>::min() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::max() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::lowest() , ieee754::Float::NormalizedNumber);
test(std::numeric_limits<float>::quiet_NaN() , ieee754::Float::NotANumber);
test(std::numeric_limits<float>::signaling_NaN(), ieee754::Float::NotANumber);
test(+std::numeric_limits<float>::infinity() , ieee754::Float::PositiveInfinity);
test(-std::numeric_limits<float>::infinity() , ieee754::Float::NegativeInfinity);
test(std::numeric_limits<float>::denorm_min() , ieee754::Float::DenormalizedNumber);
return 0;
}
<|endoftext|> |
<commit_before>// This file may be redistributed and modified only under the terms of
// the GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2000 Stefanus Du Toit
#include "../Stream/Codec.h"
#include "Utility.h"
#include <stack>
using namespace std;
using namespace Atlas::Stream;
/*
[type][name]=[data][|endtype]
{} for message
() for lists
[] for maps
$ for string
@ for int
# for float
*/
class PackedAscii : public Codec
{
public:
PackedAscii(const Codec::Parameters&);
virtual void Poll();
virtual void MessageBegin();
virtual void MessageMapBegin();
virtual void MessageEnd();
virtual void MapItem(const std::string& name, const Map&);
virtual void MapItem(const std::string& name, const List&);
virtual void MapItem(const std::string& name, int);
virtual void MapItem(const std::string& name, double);
virtual void MapItem(const std::string& name, const std::string&);
virtual void MapEnd();
virtual void ListItem(const Map&);
virtual void ListItem(const List&);
virtual void ListItem(int);
virtual void ListItem(double);
virtual void ListItem(const std::string&);
virtual void ListEnd();
protected:
iostream& socket;
Filter* filter;
Bridge* bridge;
enum parsestate_t {
PARSE_MSG,
PARSE_MAP,
PARSE_LIST,
PARSE_INT,
PARSE_FLOAT,
PARSE_STRING,
PARSE_NAME,
PARSE_ASSIGN,
PARSE_VALUE
};
stack<parsestate_t> parseStack;
stack<string> fragments;
string currentFragment;
};
namespace
{
Codec::Factory<PackedAscii> factory("PackedAscii", Codec::Metrics(1, 2));
}
PackedAscii::PackedAscii(const Codec::Parameters& p) :
socket(p.stream), filter(p.filter), bridge(p.bridge)
{
}
void mapItem(Bridge* b, parsestate_t type, const string& name,
const string& value)
{
switch (type) {
case PARSE_STRING : b->MapItem(name, value);
break;
case PARSE_INT: b->MapItem(name, atoi(value.c_str()));
break;
case PARSE_FLOAT: b->MapItem(name, atof(value.c_str()));
break;
}
}
void listItem(Bridge* b, parsestate_t type, const string& value)
{
switch (type) {
case PARSE_STRING : b->ListItem(value);
break;
case PARSE_INT: b->ListItem(atoi(value.c_str()));
break;
case PARSE_FLOAT: b->ListItem(atof(value.c_str()));
break;
}
}
void popStack(stack<parsestate_t>& parseStack, stack<string>& fragments,
Bridge* b)
{
// FIXME
// check for right stack entries (VALUE, ASSIGN, NAME)
// depending on what comes before that, add to the bridge, pop off nicely
string name, value;
parsestate_t type;
if (parseStack.top() != PARSE_VALUE) return; // FIXME report error
parseStack.pop();
value = fragments.pop();
if (parseStack.top() != PARSE_ASSIGN) return; // FIXME report error
parseStack.pop();
if (parseStack.top() != PARSE_NAME) return; // FIXME report error
parseStack.pop();
name = fragments.pop();
type = parseStack.pop();
switch (parseStack.top()) {
case PARSE_MAP: mapItem(b, type, name, value);
break;
case PARSE_LIST: listItem(b, type, value);
break;
default: break; // FIXME report error
}
}
void PackedAscii::Poll() // muchas FIXME
{
if (!socket.rdbuf()->in_avail()) return; // no data waiting
// FIXME
// what about dehexifying?
// basically, we should look at everything in the stream
// if we find '+' plus 2 chars, dehexify and put back?
// maybe...
char next = socket.get(); // get character
switch (next) {
case '{':
if (parseStack.empty())
{
bridge->MessageBegin();
parseStack.push(PARSE_MSG);
}
break;
case '}':
// FIXME handle empty stack or incorrect nesting
if (parseStack.top() == PARSE_MSG)
{
bridge->MessageEnd();
parseStack.pop();
}
break;
case '[': parseStack.push(PARSE_MAP);
break; // FIXME
case ']': popStack(parseStack, fragments, bridge);
parseStack.pop(); // PARSE_MAP
break; // FIXME
case '(': parseStack.push(PARSE_LIST);
break; // FIXME
case ')': popStack(parseStack, fragments, bridge);
parseStack.pop(); // PARSE_LIST
break; // FIXME
case '$': break; // FIXME
case '@': break; // FIXME
case '#': break; // FIXME
}
// FIXME - finish this
// do whatever with it depending on the stack
// possibly pop off the stack
}
void PackedAscii::MessageBegin()
{
socket << "{";
}
void PackedAscii::MessageMapBegin()
{
socket << "[=";
}
void PackedAscii::MessageEnd()
{
socket << "}";
}
void PackedAscii::MapItem(const std::string& name, const Map&)
{
socket << "[" << hexEncode("+", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, const List&)
{
socket << "(" << hexEncode("+", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, int data)
{
socket << "@" << hexEncode("+", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, double data)
{
socket << "#" << hexEncode("+", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, const std::string& data)
{
socket << "$" << hexEncode("+", "+{}[]()@#$=", name) << "=" <<
hexEncode("+", "+{}[]()@#$=", data);
}
void PackedAscii::MapEnd()
{
socket << "]";
}
void PackedAscii::ListItem(const Map&)
{
socket << "[=";
}
void PackedAscii::ListItem(const List&)
{
socket << "(=";
}
void PackedAscii::ListItem(int data)
{
socket << "@=" << data;
}
void PackedAscii::ListItem(double data)
{
socket << "#=" << data;
}
void PackedAscii::ListItem(const std::string& data)
{
socket << "$=" << hexEncode("+", "+{}[]()@#$=", data);
}
void PackedAscii::ListEnd()
{
socket << ")";
}
<commit_msg>Added some speculative code for handling the beginning of maps<commit_after>// This file may be redistributed and modified only under the terms of
// the GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2000 Stefanus Du Toit
#include "../Stream/Codec.h"
#include "Utility.h"
#include <stack>
using namespace std;
using namespace Atlas::Stream;
/*
[type][name]=[data][|endtype]
{} for message
() for lists
[] for maps
$ for string
@ for int
# for float
*/
class PackedAscii : public Codec
{
public:
PackedAscii(const Codec::Parameters&);
virtual void Poll();
virtual void MessageBegin();
virtual void MessageMapBegin();
virtual void MessageEnd();
virtual void MapItem(const std::string& name, const Map&);
virtual void MapItem(const std::string& name, const List&);
virtual void MapItem(const std::string& name, int);
virtual void MapItem(const std::string& name, double);
virtual void MapItem(const std::string& name, const std::string&);
virtual void MapEnd();
virtual void ListItem(const Map&);
virtual void ListItem(const List&);
virtual void ListItem(int);
virtual void ListItem(double);
virtual void ListItem(const std::string&);
virtual void ListEnd();
protected:
iostream& socket;
Filter* filter;
Bridge* bridge;
enum parsestate_t {
PARSE_MSG,
PARSE_MAP,
PARSE_LIST,
PARSE_INT,
PARSE_FLOAT,
PARSE_STRING,
PARSE_NAME,
PARSE_ASSIGN,
PARSE_VALUE
};
stack<parsestate_t> parseStack;
stack<string> fragments;
string currentFragment;
};
namespace
{
Codec::Factory<PackedAscii> factory("PackedAscii", Codec::Metrics(1, 2));
}
PackedAscii::PackedAscii(const Codec::Parameters& p) :
socket(p.stream), filter(p.filter), bridge(p.bridge)
{
}
void mapItem(Bridge* b, parsestate_t type, const string& name,
const string& value)
{
switch (type) {
case PARSE_STRING : b->MapItem(name, value);
break;
case PARSE_INT: b->MapItem(name, atoi(value.c_str()));
break;
case PARSE_FLOAT: b->MapItem(name, atof(value.c_str()));
break;
}
}
void listItem(Bridge* b, parsestate_t type, const string& value)
{
switch (type) {
case PARSE_STRING : b->ListItem(value);
break;
case PARSE_INT: b->ListItem(atoi(value.c_str()));
break;
case PARSE_FLOAT: b->ListItem(atof(value.c_str()));
break;
}
}
void popStack(stack<parsestate_t>& parseStack, stack<string>& fragments,
Bridge* b)
{
// FIXME
// check for right stack entries (VALUE, ASSIGN, NAME)
// depending on what comes before that, add to the bridge, pop off nicely
string name, value;
parsestate_t type;
if (parseStack.top() != PARSE_VALUE) return; // FIXME report error
parseStack.pop();
value = fragments.pop();
if (parseStack.top() != PARSE_ASSIGN) return; // FIXME report error
parseStack.pop();
if (parseStack.top() != PARSE_NAME) return; // FIXME report error
parseStack.pop();
name = fragments.pop();
type = parseStack.pop();
switch (parseStack.top()) {
case PARSE_MAP: mapItem(b, type, name, value);
break;
case PARSE_LIST: listItem(b, type, value);
break;
default: break; // FIXME report error
}
}
void PackedAscii::Poll() // muchas FIXME
{
if (!socket.rdbuf()->in_avail()) return; // no data waiting
// FIXME
// what about dehexifying?
// basically, we should look at everything in the stream
// if we find '+' plus 2 chars, dehexify and put back?
// maybe...
char next = socket.get(); // get character
switch (next) {
case '{':
if (parseStack.empty())
{
bridge->MessageBegin();
parseStack.push(PARSE_MSG);
}
break;
case '}':
// FIXME handle empty stack or incorrect nesting
if (parseStack.top() == PARSE_MSG)
{
bridge->MessageEnd();
parseStack.pop();
}
break;
case '[':
// FIXME ensure that this map is in the right context
if (parseStack.top() == PARSE_MSG)
{
bridge->MessageBeginMap();
}
else if (parseStack.top() == PARSE_MAP)
{
// FIXME need the map name
// so this needs to be handled by fragments some how
bridge->MapItem("", MapBegin);
}
else if (parseStack.top() == PARSE_LIST)
{
bridge->ListItem(MapBegin);
}
parseStack.push(PARSE_MAP);
break;
case ']': popStack(parseStack, fragments, bridge);
parseStack.pop(); // PARSE_MAP
break; // FIXME
case '(': parseStack.push(PARSE_LIST);
break; // FIXME
case ')': popStack(parseStack, fragments, bridge);
parseStack.pop(); // PARSE_LIST
break; // FIXME
case '$': break; // FIXME
case '@': break; // FIXME
case '#': break; // FIXME
}
// FIXME - finish this
// do whatever with it depending on the stack
// possibly pop off the stack
}
void PackedAscii::MessageBegin()
{
socket << "{";
}
void PackedAscii::MessageMapBegin()
{
socket << "[=";
}
void PackedAscii::MessageEnd()
{
socket << "}";
}
void PackedAscii::MapItem(const std::string& name, const Map&)
{
socket << "[" << hexEncode("+", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, const List&)
{
socket << "(" << hexEncode("+", "+{}[]()@#$=", name) << "=";
}
void PackedAscii::MapItem(const std::string& name, int data)
{
socket << "@" << hexEncode("+", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, double data)
{
socket << "#" << hexEncode("+", "+{}[]()@#$=", name) << "=" << data;
}
void PackedAscii::MapItem(const std::string& name, const std::string& data)
{
socket << "$" << hexEncode("+", "+{}[]()@#$=", name) << "=" <<
hexEncode("+", "+{}[]()@#$=", data);
}
void PackedAscii::MapEnd()
{
socket << "]";
}
void PackedAscii::ListItem(const Map&)
{
socket << "[=";
}
void PackedAscii::ListItem(const List&)
{
socket << "(=";
}
void PackedAscii::ListItem(int data)
{
socket << "@=" << data;
}
void PackedAscii::ListItem(double data)
{
socket << "#=" << data;
}
void PackedAscii::ListItem(const std::string& data)
{
socket << "$=" << hexEncode("+", "+{}[]()@#$=", data);
}
void PackedAscii::ListEnd()
{
socket << ")";
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "AutowiringBenchmarkTest.h"
#include "TestFixtures/SimpleObject.h"
#include <boost/chrono/system_clocks.hpp>
TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) {
const size_t n = 10000;
// Insert the object:
AutoRequired<SimpleObject>();
// Time n hash map hits, in order to get a baseline:
std::unordered_map<int, int> ref;
ref[0] = 212;
ref[1] = 21;
boost::chrono::nanoseconds baseline;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
ref[i % 2];
baseline = boost::chrono::high_resolution_clock::now() - start;
}
// Time n autowirings:
boost::chrono::nanoseconds benchmark;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
Autowired<SimpleObject>();
benchmark = (boost::chrono::high_resolution_clock::now() - start) / n;
}
EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup";
}
template<int N>
struct dummy:
public virtual ContextMember
{};
void InjectDummy(void) {
Autowired<dummy<1>>();
Autowired<dummy<2>>();
Autowired<dummy<3>>();
Autowired<dummy<4>>();
Autowired<dummy<5>>();
Autowired<dummy<6>>();
Autowired<dummy<7>>();
Autowired<dummy<8>>();
Autowired<dummy<9>>();
Autowired<dummy<10>>();
Autowired<dummy<11>>();
Autowired<dummy<12>>();
Autowired<dummy<13>>();
Autowired<dummy<14>>();
Autowired<dummy<15>>();
Autowired<dummy<16>>();
Autowired<dummy<17>>();
Autowired<dummy<18>>();
Autowired<dummy<19>>();
Autowired<dummy<20>>();
Autowired<dummy<21>>();
Autowired<dummy<22>>();
Autowired<dummy<23>>();
Autowired<dummy<24>>();
Autowired<dummy<25>>();
};
TEST_F(AutowiringBenchmarkTest, VerifyAutowiringCache) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
for(int i = 0; i<100; ++i) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
auto startBase = boost::chrono::high_resolution_clock::now();
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
InjectDummy();
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings";
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) {
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<dummy<1>> foo;
AutowiredFast<dummy<1>> bar;
ASSERT_TRUE(foo) << "AutoRequred member not created";
EXPECT_TRUE(bar) << "AutowiredFast not satisfied";
}
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutowiredFast<dummy<1>> fast;
Autowired<dummy<1>> wired;
AutoRequired<dummy<1>> required;
ASSERT_TRUE(required) << "AutoRequired member not created";
EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied";
EXPECT_FALSE(fast) << "AutowiredFast member was deferred";
}
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
{
// All of these tests will operate in the same context:
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
// Prime all memos:
InjectDummy();
// Test simple autowiring first:
auto startBase = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i)
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i) {
AutowiredFast<dummy<1>>();
AutowiredFast<dummy<2>>();
AutowiredFast<dummy<3>>();
AutowiredFast<dummy<4>>();
AutowiredFast<dummy<5>>();
AutowiredFast<dummy<6>>();
AutowiredFast<dummy<7>>();
AutowiredFast<dummy<8>>();
AutowiredFast<dummy<9>>();
AutowiredFast<dummy<10>>();
AutowiredFast<dummy<11>>();
AutowiredFast<dummy<12>>();
AutowiredFast<dummy<13>>();
AutowiredFast<dummy<14>>();
AutowiredFast<dummy<15>>();
AutowiredFast<dummy<16>>();
AutowiredFast<dummy<17>>();
AutowiredFast<dummy<18>>();
AutowiredFast<dummy<19>>();
AutowiredFast<dummy<20>>();
}
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring";
}
<commit_msg>Disable AutowiringBenchMarkTest.VerifyAutowiringCache on Linux. redmine #9459<commit_after>#include "stdafx.h"
#include "AutowiringBenchmarkTest.h"
#include "TestFixtures/SimpleObject.h"
#include <boost/chrono/system_clocks.hpp>
TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) {
const size_t n = 10000;
// Insert the object:
AutoRequired<SimpleObject>();
// Time n hash map hits, in order to get a baseline:
std::unordered_map<int, int> ref;
ref[0] = 212;
ref[1] = 21;
boost::chrono::nanoseconds baseline;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
ref[i % 2];
baseline = boost::chrono::high_resolution_clock::now() - start;
}
// Time n autowirings:
boost::chrono::nanoseconds benchmark;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
Autowired<SimpleObject>();
benchmark = (boost::chrono::high_resolution_clock::now() - start) / n;
}
EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup";
}
template<int N>
struct dummy:
public virtual ContextMember
{};
void InjectDummy(void) {
Autowired<dummy<1>>();
Autowired<dummy<2>>();
Autowired<dummy<3>>();
Autowired<dummy<4>>();
Autowired<dummy<5>>();
Autowired<dummy<6>>();
Autowired<dummy<7>>();
Autowired<dummy<8>>();
Autowired<dummy<9>>();
Autowired<dummy<10>>();
Autowired<dummy<11>>();
Autowired<dummy<12>>();
Autowired<dummy<13>>();
Autowired<dummy<14>>();
Autowired<dummy<15>>();
Autowired<dummy<16>>();
Autowired<dummy<17>>();
Autowired<dummy<18>>();
Autowired<dummy<19>>();
Autowired<dummy<20>>();
Autowired<dummy<21>>();
Autowired<dummy<22>>();
Autowired<dummy<23>>();
Autowired<dummy<24>>();
Autowired<dummy<25>>();
};
#if defined(__GNUC__) && !defined(__clang__)
TEST_F(AutowiringBenchmarkTest, DISABLED_VerifyAutowiringCache)
#else
TEST_F(AutowiringBenchmarkTest, VerifyAutowiringCache)
#endif
{
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
for(int i = 0; i<100; ++i) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
auto startBase = boost::chrono::high_resolution_clock::now();
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
InjectDummy();
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings";
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) {
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<dummy<1>> foo;
AutowiredFast<dummy<1>> bar;
ASSERT_TRUE(foo) << "AutoRequred member not created";
EXPECT_TRUE(bar) << "AutowiredFast not satisfied";
}
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutowiredFast<dummy<1>> fast;
Autowired<dummy<1>> wired;
AutoRequired<dummy<1>> required;
ASSERT_TRUE(required) << "AutoRequired member not created";
EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied";
EXPECT_FALSE(fast) << "AutowiredFast member was deferred";
}
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
{
// All of these tests will operate in the same context:
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
// Prime all memos:
InjectDummy();
// Test simple autowiring first:
auto startBase = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i)
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i) {
AutowiredFast<dummy<1>>();
AutowiredFast<dummy<2>>();
AutowiredFast<dummy<3>>();
AutowiredFast<dummy<4>>();
AutowiredFast<dummy<5>>();
AutowiredFast<dummy<6>>();
AutowiredFast<dummy<7>>();
AutowiredFast<dummy<8>>();
AutowiredFast<dummy<9>>();
AutowiredFast<dummy<10>>();
AutowiredFast<dummy<11>>();
AutowiredFast<dummy<12>>();
AutowiredFast<dummy<13>>();
AutowiredFast<dummy<14>>();
AutowiredFast<dummy<15>>();
AutowiredFast<dummy<16>>();
AutowiredFast<dummy<17>>();
AutowiredFast<dummy<18>>();
AutowiredFast<dummy<19>>();
AutowiredFast<dummy<20>>();
}
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring";
}
<|endoftext|> |
<commit_before>#include "is_valid_char.hxx"
#include "../../Positive_Matrix_With_Prefactor_State.hxx"
#include <algorithm>
#include <iterator>
#include <string>
using namespace std::literals;
inline void check_iterator(const char character,
const std::vector<char>::const_iterator &begin,
const std::vector<char>::const_iterator &iterator,
const std::vector<char>::const_iterator &end)
{
if(iterator == end)
{
throw std::runtime_error("Invalid polynomial string after '"s + character + "': "
+ std::string(begin,end));
}
}
std::vector<char>::const_iterator
parse_polynomial(const std::vector<char>::const_iterator &begin,
const std::vector<char>::const_iterator &end,
Polynomial &polynomial)
{
const std::vector<char> delimiters({',', '}'});
const auto delimiter(
std::find_first_of(begin, end, delimiters.begin(), delimiters.end()));
if(delimiter == end)
{
throw std::runtime_error("Missing '}' at end of array of polynomials");
}
std::string mantissa;
for(auto c(begin); c < delimiter; ++c)
{
if(*c == '`')
{
do
{
++c;
}
while(c != delimiter
&& (std::isdigit(*c) || *c == '.' || !is_valid_char(*c)
|| *c == '`'));
}
if(*c == '*')
{
do
{
++c;
check_iterator('*',begin, c, delimiter);
}
while(!is_valid_char(*c));
std::string exponent;
if(*c == '^')
{
exponent = "E";
++c;
check_iterator('^', begin, c, delimiter);
while(c != delimiter
&& ((exponent.size() == 1 && (*c == '-' || *c == '+'))
|| std::isdigit(*c) || !is_valid_char(*c)))
{
if(is_valid_char(*c))
{
exponent.push_back(*c);
}
++c;
}
while(c != delimiter && (!is_valid_char(*c) || *c == '*'))
{
++c;
}
}
size_t degree(0);
// Hard code the polynomial to be in 'x' since that is what
// SDPB.m uses.
if(*c == 'x')
{
++c;
while(!is_valid_char(*c))
{
++c;
check_iterator('x', begin, c, delimiter);
}
if(*c != '^')
{
degree = 1;
}
else
{
++c;
std::string degree_string;
while((degree_string.empty() && (*c == '-' || *c == '+'))
|| std::isdigit(*c) || !is_valid_char(*c))
{
if(is_valid_char(*c) && *c != '+')
{
degree_string.push_back(*c);
}
++c;
}
degree = std::stoull(degree_string);
}
}
if(polynomial.coefficients.size() < degree + 1)
{
polynomial.coefficients.resize(degree + 1);
}
polynomial.coefficients.at(degree)
= El::BigFloat(mantissa + exponent);
mantissa.clear();
}
else if(!mantissa.empty() && (*c == '-' || *c == '+' || c == delimiter))
{
if(polynomial.coefficients.size() < 1)
{
polynomial.coefficients.resize(1);
}
polynomial.coefficients.at(0) = El::BigFloat(mantissa);
mantissa.clear();
}
if(is_valid_char(*c) && *c != '+')
{
mantissa.push_back(*c);
}
}
return delimiter;
}
<commit_msg>clang-format<commit_after>#include "is_valid_char.hxx"
#include "../../Positive_Matrix_With_Prefactor_State.hxx"
#include <algorithm>
#include <iterator>
#include <string>
using namespace std::literals;
inline void check_iterator(const char character,
const std::vector<char>::const_iterator &begin,
const std::vector<char>::const_iterator &iterator,
const std::vector<char>::const_iterator &end)
{
if(iterator == end)
{
throw std::runtime_error("Invalid polynomial string after '"s + character
+ "': " + std::string(begin, end));
}
}
std::vector<char>::const_iterator
parse_polynomial(const std::vector<char>::const_iterator &begin,
const std::vector<char>::const_iterator &end,
Polynomial &polynomial)
{
const std::vector<char> delimiters({',', '}'});
const auto delimiter(
std::find_first_of(begin, end, delimiters.begin(), delimiters.end()));
if(delimiter == end)
{
throw std::runtime_error("Missing '}' at end of array of polynomials");
}
std::string mantissa;
for(auto c(begin); c < delimiter; ++c)
{
if(*c == '`')
{
do
{
++c;
}
while(c != delimiter
&& (std::isdigit(*c) || *c == '.' || !is_valid_char(*c)
|| *c == '`'));
}
if(*c == '*')
{
do
{
++c;
check_iterator('*', begin, c, delimiter);
}
while(!is_valid_char(*c));
std::string exponent;
if(*c == '^')
{
exponent = "E";
++c;
check_iterator('^', begin, c, delimiter);
while(c != delimiter
&& ((exponent.size() == 1 && (*c == '-' || *c == '+'))
|| std::isdigit(*c) || !is_valid_char(*c)))
{
if(is_valid_char(*c))
{
exponent.push_back(*c);
}
++c;
}
while(c != delimiter && (!is_valid_char(*c) || *c == '*'))
{
++c;
}
}
size_t degree(0);
// Hard code the polynomial to be in 'x' since that is what
// SDPB.m uses.
if(*c == 'x')
{
++c;
while(!is_valid_char(*c))
{
++c;
check_iterator('x', begin, c, delimiter);
}
if(*c != '^')
{
degree = 1;
}
else
{
++c;
std::string degree_string;
while((degree_string.empty() && (*c == '-' || *c == '+'))
|| std::isdigit(*c) || !is_valid_char(*c))
{
if(is_valid_char(*c) && *c != '+')
{
degree_string.push_back(*c);
}
++c;
}
degree = std::stoull(degree_string);
}
}
if(polynomial.coefficients.size() < degree + 1)
{
polynomial.coefficients.resize(degree + 1);
}
polynomial.coefficients.at(degree)
= El::BigFloat(mantissa + exponent);
mantissa.clear();
}
else if(!mantissa.empty() && (*c == '-' || *c == '+' || c == delimiter))
{
if(polynomial.coefficients.size() < 1)
{
polynomial.coefficients.resize(1);
}
polynomial.coefficients.at(0) = El::BigFloat(mantissa);
mantissa.clear();
}
if(is_valid_char(*c) && *c != '+')
{
mantissa.push_back(*c);
}
}
return delimiter;
}
<|endoftext|> |
<commit_before>//
// function.cpp
// integral
//
// Copyright (C) 2017 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <lua.hpp>
#include <integral.hpp>
double getSum(double x, double y) {
return x + y;
}
double luaGetSum(lua_State *luaState) {
integral::pushCopy(luaState, integral::get<double>(luaState, 1) + integral::get<double>(luaState, 2));
return 1;
}
int main(int argc, char* argv[]) {
try {
integral::State luaState;
luaState.openLibs();
luaState["getSum"].setFunction(getSum);
luaState.doString("print('getSum(1, -.2) = ' .. getSum(1, -.2))");
luaState["luaGetSum"].setLuaFunction(luaGetSum);
luaState.doString("print('luaGetSum(1, -.2) = ' .. luaGetSum(1, -.2))");
luaState["printHello"].setFunction([]{
std::puts("hello!");
});
luaState.doString("printHello()");
luaState["getQuoted"].setFunction([](const std::string &string) {
return std::string("\"") + string + '"';
});
luaState.doString("print('getQuoted(\"quoted\") = ' .. getQuoted('quoted'))");
luaState["luaGetQuoted"].setLuaFunction([](lua_State *lambdaLuaState) {
integral::push<std::string>(lambdaLuaState, std::string("\"") + integral::get<const char *>(lambdaLuaState, 1) + '"');
return 1;
});
luaState.doString("print('luaGetQuoted(\"quoted\") = ' .. luaGetQuoted('quoted'))");
try {
luaState.doString("getSum(1, 2, 3)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("luaGetSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
return EXIT_SUCCESS;
} catch (const std::exception &exception) {
std::cerr << "[function] " << exception.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception thrown" << std::endl;
}
return EXIT_FAILURE;
}
<commit_msg>added throw exception error example<commit_after>//
// function.cpp
// integral
//
// Copyright (C) 2017 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <lua.hpp>
#include <integral.hpp>
double getSum(double x, double y) {
return x + y;
}
double luaGetSum(lua_State *luaState) {
integral::pushCopy(luaState, integral::get<double>(luaState, 1) + integral::get<double>(luaState, 2));
return 1;
}
int main(int argc, char* argv[]) {
try {
integral::State luaState;
luaState.openLibs();
luaState["getSum"].setFunction(getSum);
luaState.doString("print('getSum(1, -.2) = ' .. getSum(1, -.2))");
luaState["luaGetSum"].setLuaFunction(luaGetSum);
luaState.doString("print('luaGetSum(1, -.2) = ' .. luaGetSum(1, -.2))");
luaState["printHello"].setFunction([]{
std::puts("hello!");
});
luaState.doString("printHello()");
luaState["getQuoted"].setFunction([](const std::string &string) {
return std::string("\"") + string + '"';
});
luaState.doString("print('getQuoted(\"quoted\") = ' .. getQuoted('quoted'))");
luaState["luaGetQuoted"].setLuaFunction([](lua_State *lambdaLuaState) {
integral::push<std::string>(lambdaLuaState, std::string("\"") + integral::get<const char *>(lambdaLuaState, 1) + '"');
return 1;
});
luaState.doString("print('luaGetQuoted(\"quoted\") = ' .. luaGetQuoted('quoted'))");
try {
luaState.doString("getSum(1, 2, 3)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("luaGetSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState["throw"].setFunction([]{
throw std::runtime_error("throw exception");
});
luaState.doString("throw()");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState["luaThrow"].setLuaFunction([](lua_State *) {
throw std::runtime_error("luaThrow exception");
return 0;
});
luaState.doString("luaThrow()");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
return EXIT_SUCCESS;
} catch (const std::exception &exception) {
std::cerr << "[function] " << exception.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception thrown" << std::endl;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>// attribute unused on struct parameter
// originally found in package 'rbldnsd_0.994b'
// Assertion failed: e != NULL && "388cba6d-895c-4acb-ac25-c28fc1c4c2cb", file cc.gr line 1234
// ERR-MATCH: Assertion failed: 388cba6d-895c-4acb-ac25-c28fc1c4c2cb
struct S1 {};
int foo(struct S1 __attribute__((unused)) *x)
{
}
<commit_msg>Err-match fix<commit_after>// attribute unused on struct parameter
// originally found in package 'rbldnsd_0.994b'
// Assertion failed: e != NULL && "388cba6d-895c-4acb-ac25-c28fc1c4c2cb", file cc.gr line 1234
// ERR-MATCH: 388cba6d-895c-4acb-ac25-c28fc1c4c2cb
struct S1 {};
int foo(struct S1 __attribute__((unused)) *x)
{
}
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <ncurses.h>
#include <cstdint>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "game.h"
WINDOW* main_wnd;
WINDOW* game_wnd;
rect game_area;
rect screen_area;
vec2ui cur_size;
std::vector<enemy> enemies;
std::vector<star> stars;
struct {
vec2i pos;
vec2i dir;
rect bounds;
char disp_char;
char ship_type;
bool moving;
int energy;
} player;
int init() {
srand(time(0));
initscr();
cbreak();
noecho();
clear();
refresh();
curs_set(0);
start_color();
// read in window size
cur_size = { 0, 0 };
getmaxyx(main_wnd, cur_size.x, cur_size.y);
// define area for screen (default terminal size)
screen_area = { { 0, 0 }, { 80, 24 } };
// set screen size accordingly
wresize(main_wnd, screen_area.height(), screen_area.width());
// initialize window areas
int infopanel_height = 4;
game_wnd = newwin(screen_area.height() - infopanel_height - 2, screen_area.width() - 2, screen_area.top() + 1, screen_area.left() + 1);
main_wnd = newwin(screen_area.height(), screen_area.width(), 0, 0);
// define area for movement
game_area = { { 0, 0}, { screen_area.width() - 2, screen_area.height() - infopanel_height - 4 } };
applyColorscheme(COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_YELLOW, COLOR_BLACK);
init_pair(4, COLOR_RED, COLOR_BLACK);
init_pair(5, COLOR_BLUE, COLOR_BLACK);
// enable function keys
keypad(main_wnd, true);
keypad(game_wnd, true);
// disable input blocking
nodelay(main_wnd, true);
nodelay(game_wnd, true);
// enable color
if(!has_colors()) {
endwin();
printf("ERROR: Terminal does not support color.\n");
exit(1);
}
return 0;
}
void run() {
int tick = 0;
// initialize player
player.disp_char = 'o';
player.pos = {10, 10};
player.bounds = { { player.pos.x - 1, player.pos.y }, { 3, 2 } }; // player is 3 wide, 2 tall
player.moving = false;
player.energy = 100;
int in_char = 0;
bool exit_requested = false;
bool game_over = false;
// draw frame around whole screen
wattron(main_wnd, A_BOLD);
box(main_wnd, 0, 0);
wattroff(main_wnd, A_BOLD);
// draw dividing line between game and stats
wmove(main_wnd, game_area.bot() + 3, 1);
whline(main_wnd, '-', screen_area.width() - 2);
// initial draw
wrefresh(main_wnd);
wrefresh(game_wnd);
const std::vector<std::string> story_text = {
"Just another Monday, and you're on your way to work...",
"When suddenly...",
"You realize you left the oven on!",
"Take a shortcut through that asteroid field!",
"Get back to the house before your planet explodes!"
};
mvwprintw(main_wnd, 22, 57, "press SPACE to skip...");
// story mode demo
tick = 0;
size_t story_part = 0;
size_t story_position = 0;
while(1) {
werase(game_wnd);
in_char = wgetch(main_wnd);
if(tick % 50 == 0)
moveStars();
// draw starry background
for(auto s : stars)
mvwaddch(game_wnd, s.pos.y, s.pos.x, '.');
if(story_position < story_text[story_part].length()) {
wattron(main_wnd, A_BOLD);
mvwaddch(main_wnd, 20, 5 + story_position, story_text[story_part][story_position]);
wattroff(main_wnd, A_BOLD);
story_position++;
}
if(in_char == ' ') {
story_part++;
story_position = 0;
mvwhline(main_wnd, 20, 1, ' ', screen_area.width() - 2);
}
else if(in_char == 'q') {
exit_requested = true;
break;
}
if(story_part >= story_text.size()) break;
wrefresh(game_wnd);
tick++;
usleep(10000); // 1 ms
}
// white-out
mvwhline(main_wnd, 22, 57, ' ', 22);
tick = 0;
while(1) {
// clear game window
werase(game_wnd);
// TODO: Give warning message if screen is too small!
if(cur_size.x > screen_area.width() || cur_size.y > screen_area.height()) {}
//winResize(cur_width, cur_height);
// read in input key, if any (non-blocking as defined earlier)
in_char = wgetch(main_wnd);
in_char = tolower(in_char);
switch(in_char) {
case 'q':
exit_requested = true;
break;
case KEY_UP:
case 'w':
case 'i':
if(player.pos.y > game_area.top())
player.pos.y -= 1;
break;
case KEY_DOWN:
case 's':
case 'k':
if(player.pos.y < game_area.bot() + 1)
player.pos.y += 1;
break;
case KEY_LEFT:
case 'a':
case 'j':
if(player.pos.x > game_area.left() + 1)
player.pos.x -= 1;
break;
case KEY_RIGHT:
case 'd':
case 'l':
if(player.pos.x < game_area.right() - 2)
player.pos.x += 1;
break;
default:
break;
}
if(tick % 7 == 0)
moveStars();
if(tick > 1000 && tick % 30 == 0)
enemyAI();
player.bounds = { { player.pos.x - 1, player.pos.y }, { 3, 2 } };
// collision detection
for(size_t i = 0; i < enemies.size(); i++) {
if(player.bounds.contains(enemies.at(i).pos)) {
enemies.erase(enemies.begin() + i);
player.energy -= 10;
}
}
if(player.energy <= 0)
game_over = true;
// draw starry background
for(auto s : stars)
mvwaddch(game_wnd, s.pos.y, s.pos.x, '.');
// player ship main body
wattron(game_wnd, A_BOLD);
mvwaddch(game_wnd, player.pos.y, player.pos.x, player.disp_char); // (y, x)
wattroff(game_wnd, A_BOLD);
// player ship accessories
wattron(game_wnd, A_ALTCHARSET);
//mvaddch(player.pos.y - 1, player.pos.x, ACS_UARROW);
mvwaddch(game_wnd, player.pos.y, player.pos.x - 1, ACS_LARROW);
mvwaddch(game_wnd, player.pos.y, player.pos.x + 1, ACS_RARROW);
// animate engine flame :)
if(tick / 5 % 3) { // 5 ms cycle, 50% duty
wattron(game_wnd, COLOR_PAIR(tick % 2 ? 3 : 4));
mvwaddch(game_wnd, player.pos.y + 1, player.pos.x, ACS_UARROW);
wattroff(game_wnd, COLOR_PAIR(tick % 2 ? 3 : 4));
}
wattroff(game_wnd, A_ALTCHARSET);
// draw enemies
for(auto n : enemies) {
wattron(game_wnd, A_BOLD);
mvwaddch(game_wnd, n.pos.y, n.pos.x, '*');
wattroff(game_wnd, A_BOLD);
}
// draw UI elements
// energy bar
wmove(main_wnd, 20, 1);
whline(main_wnd, ' ', 25); // health bar is 25 chars long
wmove(main_wnd, 20, 1);
drawEnergyBar(player.energy);
// draw static string to hold percentage
mvwprintw(main_wnd, 21, 1, " - E N E R G Y - //");
// draw numeric percentage
wattron(main_wnd, A_BOLD);
if(player.energy <= 25) {
wattron(main_wnd, COLOR_PAIR(4));
if(tick % 100 < 50)
mvwprintw(main_wnd, 21, 18, "%i%%", player.energy);
wattroff(main_wnd, COLOR_PAIR(4));
} else
mvwprintw(main_wnd, 21, 18, "%i%%", player.energy);
wattroff(main_wnd, A_BOLD);
//usleep(100);
// refresh windows
wrefresh(main_wnd);
wrefresh(game_wnd);
if(exit_requested || game_over) break;
tick++;
//nanosleep({0, 1000000000}, NULL);
usleep(10000); // 1 ms
};
delwin(main_wnd);
delwin(game_wnd);
endwin();
if(game_over) printf("Game over!\n");
}
void applyColorscheme(short fg, short bg) {
init_pair(1, fg, bg);
wbkgd(main_wnd, COLOR_PAIR(1));
wbkgd(game_wnd, COLOR_PAIR(1));
}
void setFrame(){
// creates simple frame around window composed of vertical and horizontal lines
attron(A_BOLD);
box(main_wnd, 0, 0);
attroff(A_BOLD);
// border characters can be set manually using the border function
// border( wnd, leftside, rightside, topside, bottom side, tlcorner,
// trcorner, blcorner, brcorner);
}
void winResize(int &orig_width, int &orig_height){
int new_width, new_height;
getmaxyx(main_wnd, new_width, new_height);
// if window dimensions have changed, update border
if(new_width != orig_width || new_height != orig_height){
orig_width = new_width;
orig_height = new_height;
wresize(main_wnd, new_height, 0);
mvwin(main_wnd, new_height, 0);
wclear(main_wnd);
setFrame();
}
}
void enemyAI(){
for(size_t i = 0; i < enemies.size(); i++){ // move each enemy down
if(enemies.at(i).pos.y > game_area.bot()){ // delete from vector when enemy reaches bottom
// mvwaddch(game_wnd, n.at(i).pos.y , n.at(i).pos.x, ' ');
enemies.erase(enemies.begin() + i);
}
//mvwaddch(game_wnd, n.at(i).pos.y, n.at(i).pos.x, ' '); // remove enemy from prev pos
enemies.at(i).pos.y += 1; // move enemy down
//mvwaddch(game_wnd, n.at(i).pos.y, n.at(i).pos.x, '*');
}
int pos = rand() % game_area.width(); // randomize enemy x position spawn
enemy e;
e.pos.x = pos;
e.pos.y = 0;
enemies.push_back(e);
}
void moveStars() {
for(size_t i = 0; i < stars.size(); i++) {
if(stars.at(i).pos.y > game_area.bot())
stars.erase(stars.begin() + i);
stars.at(i).pos.y += 1;
}
int pos = rand() % game_area.width();
star s;
s.pos.x = pos;
s.pos.y = 0;
stars.push_back(s);
}
void drawEnergyBar(int a) {
int col_pair = 1;
for(int i = 0; i < a; i+=4) {
if(i > 100)
col_pair = 5; // blue
else if(i > 50)
col_pair = 2; // green
else if(i > 25)
col_pair = 3; // yellow
else
col_pair = 4; // red
wattron(main_wnd, COLOR_PAIR(col_pair));
wattron(main_wnd, A_BOLD);
waddch(main_wnd, '/');
wattroff(main_wnd, A_BOLD);
wattroff(main_wnd, COLOR_PAIR(col_pair));
}
}
<commit_msg>Made enemies spawn and move faster<commit_after>#include <unistd.h>
#include <ncurses.h>
#include <cstdint>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "game.h"
WINDOW* main_wnd;
WINDOW* game_wnd;
rect game_area;
rect screen_area;
vec2ui cur_size;
std::vector<enemy> enemies;
std::vector<star> stars;
struct {
vec2i pos;
vec2i dir;
rect bounds;
char disp_char;
char ship_type;
bool moving;
int energy;
} player;
int init() {
srand(time(0));
initscr();
cbreak();
noecho();
clear();
refresh();
curs_set(0);
start_color();
// read in window size
cur_size = { 0, 0 };
getmaxyx(main_wnd, cur_size.x, cur_size.y);
// define area for screen (default terminal size)
screen_area = { { 0, 0 }, { 80, 24 } };
// set screen size accordingly
wresize(main_wnd, screen_area.height(), screen_area.width());
// initialize window areas
int infopanel_height = 4;
game_wnd = newwin(screen_area.height() - infopanel_height - 2, screen_area.width() - 2, screen_area.top() + 1, screen_area.left() + 1);
main_wnd = newwin(screen_area.height(), screen_area.width(), 0, 0);
// define area for movement
game_area = { { 0, 0}, { screen_area.width() - 2, screen_area.height() - infopanel_height - 4 } };
applyColorscheme(COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_YELLOW, COLOR_BLACK);
init_pair(4, COLOR_RED, COLOR_BLACK);
init_pair(5, COLOR_BLUE, COLOR_BLACK);
// enable function keys
keypad(main_wnd, true);
keypad(game_wnd, true);
// disable input blocking
nodelay(main_wnd, true);
nodelay(game_wnd, true);
// enable color
if(!has_colors()) {
endwin();
printf("ERROR: Terminal does not support color.\n");
exit(1);
}
return 0;
}
void run() {
int tick = 0;
// initialize player
player.disp_char = 'o';
player.pos = {10, 10};
player.bounds = { { player.pos.x - 1, player.pos.y }, { 3, 2 } }; // player is 3 wide, 2 tall
player.moving = false;
player.energy = 100;
int in_char = 0;
bool exit_requested = false;
bool game_over = false;
// draw frame around whole screen
wattron(main_wnd, A_BOLD);
box(main_wnd, 0, 0);
wattroff(main_wnd, A_BOLD);
// draw dividing line between game and stats
wmove(main_wnd, game_area.bot() + 3, 1);
whline(main_wnd, '-', screen_area.width() - 2);
// initial draw
wrefresh(main_wnd);
wrefresh(game_wnd);
const std::vector<std::string> story_text = {
"Just another Monday, and you're on your way to work...",
"When suddenly...",
"You realize you left the oven on!",
"Take a shortcut through that asteroid field!",
"Get back to the house before your planet explodes!"
};
mvwprintw(main_wnd, 22, 57, "press SPACE to skip...");
// story mode demo
tick = 0;
size_t story_part = 0;
size_t story_position = 0;
while(1) {
werase(game_wnd);
in_char = wgetch(main_wnd);
if(tick % 50 == 0)
moveStars();
// draw starry background
for(auto s : stars)
mvwaddch(game_wnd, s.pos.y, s.pos.x, '.');
if(story_position < story_text[story_part].length()) {
wattron(main_wnd, A_BOLD);
mvwaddch(main_wnd, 20, 5 + story_position, story_text[story_part][story_position]);
wattroff(main_wnd, A_BOLD);
story_position++;
}
if(in_char == ' ') {
story_part++;
story_position = 0;
mvwhline(main_wnd, 20, 1, ' ', screen_area.width() - 2);
}
else if(in_char == 'q') {
exit_requested = true;
break;
}
if(story_part >= story_text.size()) break;
wrefresh(game_wnd);
tick++;
usleep(10000); // 1 ms
}
// white-out
mvwhline(main_wnd, 22, 57, ' ', 22);
tick = 0;
while(1) {
// clear game window
werase(game_wnd);
// TODO: Give warning message if screen is too small!
if(cur_size.x > screen_area.width() || cur_size.y > screen_area.height()) {}
//winResize(cur_width, cur_height);
// read in input key, if any (non-blocking as defined earlier)
in_char = wgetch(main_wnd);
in_char = tolower(in_char);
switch(in_char) {
case 'q':
exit_requested = true;
break;
case KEY_UP:
case 'w':
case 'i':
if(player.pos.y > game_area.top())
player.pos.y -= 1;
break;
case KEY_DOWN:
case 's':
case 'k':
if(player.pos.y < game_area.bot() + 1)
player.pos.y += 1;
break;
case KEY_LEFT:
case 'a':
case 'j':
if(player.pos.x > game_area.left() + 1)
player.pos.x -= 1;
break;
case KEY_RIGHT:
case 'd':
case 'l':
if(player.pos.x < game_area.right() - 2)
player.pos.x += 1;
break;
default:
break;
}
if(tick % 7 == 0)
moveStars();
if(tick > 100 && tick % 20 == 0)
enemyAI();
player.bounds = { { player.pos.x - 1, player.pos.y }, { 3, 2 } };
// collision detection
for(size_t i = 0; i < enemies.size(); i++) {
if(player.bounds.contains(enemies.at(i).pos)) {
enemies.erase(enemies.begin() + i);
player.energy -= 10;
}
}
if(player.energy <= 0)
game_over = true;
// draw starry background
for(auto s : stars)
mvwaddch(game_wnd, s.pos.y, s.pos.x, '.');
// player ship main body
wattron(game_wnd, A_BOLD);
mvwaddch(game_wnd, player.pos.y, player.pos.x, player.disp_char); // (y, x)
wattroff(game_wnd, A_BOLD);
// player ship accessories
wattron(game_wnd, A_ALTCHARSET);
//mvaddch(player.pos.y - 1, player.pos.x, ACS_UARROW);
mvwaddch(game_wnd, player.pos.y, player.pos.x - 1, ACS_LARROW);
mvwaddch(game_wnd, player.pos.y, player.pos.x + 1, ACS_RARROW);
// animate engine flame :)
if(tick / 5 % 3) { // 5 ms cycle, 50% duty
wattron(game_wnd, COLOR_PAIR(tick % 2 ? 3 : 4));
mvwaddch(game_wnd, player.pos.y + 1, player.pos.x, ACS_UARROW);
wattroff(game_wnd, COLOR_PAIR(tick % 2 ? 3 : 4));
}
wattroff(game_wnd, A_ALTCHARSET);
// draw enemies
for(auto n : enemies) {
wattron(game_wnd, A_BOLD);
mvwaddch(game_wnd, n.pos.y, n.pos.x, '*');
wattroff(game_wnd, A_BOLD);
}
// draw UI elements
// energy bar
wmove(main_wnd, 20, 1);
whline(main_wnd, ' ', 25); // health bar is 25 chars long
wmove(main_wnd, 20, 1);
drawEnergyBar(player.energy);
// draw static string to hold percentage
mvwprintw(main_wnd, 21, 1, " - E N E R G Y - //");
// draw numeric percentage
wattron(main_wnd, A_BOLD);
if(player.energy <= 25) {
wattron(main_wnd, COLOR_PAIR(4));
if(tick % 100 < 50)
mvwprintw(main_wnd, 21, 18, "%i%%", player.energy);
wattroff(main_wnd, COLOR_PAIR(4));
} else
mvwprintw(main_wnd, 21, 18, "%i%%", player.energy);
wattroff(main_wnd, A_BOLD);
//usleep(100);
// refresh windows
wrefresh(main_wnd);
wrefresh(game_wnd);
if(exit_requested || game_over) break;
tick++;
//nanosleep({0, 1000000000}, NULL);
usleep(10000); // 1 ms
};
delwin(main_wnd);
delwin(game_wnd);
endwin();
if(game_over) printf("Game over!\n");
}
void applyColorscheme(short fg, short bg) {
init_pair(1, fg, bg);
wbkgd(main_wnd, COLOR_PAIR(1));
wbkgd(game_wnd, COLOR_PAIR(1));
}
void setFrame(){
// creates simple frame around window composed of vertical and horizontal lines
attron(A_BOLD);
box(main_wnd, 0, 0);
attroff(A_BOLD);
// border characters can be set manually using the border function
// border( wnd, leftside, rightside, topside, bottom side, tlcorner,
// trcorner, blcorner, brcorner);
}
void winResize(int &orig_width, int &orig_height){
int new_width, new_height;
getmaxyx(main_wnd, new_width, new_height);
// if window dimensions have changed, update border
if(new_width != orig_width || new_height != orig_height){
orig_width = new_width;
orig_height = new_height;
wresize(main_wnd, new_height, 0);
mvwin(main_wnd, new_height, 0);
wclear(main_wnd);
setFrame();
}
}
void enemyAI(){
for(size_t i = 0; i < enemies.size(); i++){ // move each enemy down
if(enemies.at(i).pos.y > game_area.bot()){ // delete from vector when enemy reaches bottom
// mvwaddch(game_wnd, n.at(i).pos.y , n.at(i).pos.x, ' ');
enemies.erase(enemies.begin() + i);
}
//mvwaddch(game_wnd, n.at(i).pos.y, n.at(i).pos.x, ' '); // remove enemy from prev pos
enemies.at(i).pos.y += 1; // move enemy down
//mvwaddch(game_wnd, n.at(i).pos.y, n.at(i).pos.x, '*');
}
int pos = rand() % game_area.width(); // randomize enemy x position spawn
enemy e;
e.pos.x = pos;
e.pos.y = 0;
enemies.push_back(e);
}
void moveStars() {
for(size_t i = 0; i < stars.size(); i++) {
if(stars.at(i).pos.y > game_area.bot())
stars.erase(stars.begin() + i);
stars.at(i).pos.y += 1;
}
int pos = rand() % game_area.width();
star s;
s.pos.x = pos;
s.pos.y = 0;
stars.push_back(s);
}
void drawEnergyBar(int a) {
int col_pair = 1;
for(int i = 0; i < a; i+=4) {
if(i > 100)
col_pair = 5; // blue
else if(i > 50)
col_pair = 2; // green
else if(i > 25)
col_pair = 3; // yellow
else
col_pair = 4; // red
wattron(main_wnd, COLOR_PAIR(col_pair));
wattron(main_wnd, A_BOLD);
waddch(main_wnd, '/');
wattroff(main_wnd, A_BOLD);
wattroff(main_wnd, COLOR_PAIR(col_pair));
}
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QPixmap>
#include <nitroshare/application.h>
#include "conclusionpage.h"
#include "devicepage.h"
#include "discoverypage.h"
#include "intropage.h"
#include "wizard.h"
Wizard::Wizard(Application *application)
: mApplication(application)
{
setPixmap(QWizard::LogoPixmap, QPixmap(":/wizard/logo.png"));
setWizardStyle(QWizard::ModernStyle);
setWindowTitle(tr("Setup Wizard"));
// Adjust the wizard to a reasonable size
resize(540, 400);
addPage(new IntroPage);
addPage(new DevicePage(application->deviceName()));
addPage(new DiscoveryPage);
addPage(new ConclusionPage);
}
void Wizard::accept()
{
// TODO
QWizard::accept();
}
<commit_msg>Shrink wizard dialog.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QPixmap>
#include <nitroshare/application.h>
#include "conclusionpage.h"
#include "devicepage.h"
#include "discoverypage.h"
#include "intropage.h"
#include "wizard.h"
Wizard::Wizard(Application *application)
: mApplication(application)
{
setPixmap(QWizard::LogoPixmap, QPixmap(":/wizard/logo.png"));
setWizardStyle(QWizard::ModernStyle);
setWindowTitle(tr("Setup Wizard"));
// Adjust the wizard to a reasonable size
resize(400, 300);
addPage(new IntroPage);
addPage(new DevicePage(application->deviceName()));
addPage(new DiscoveryPage);
addPage(new ConclusionPage);
}
void Wizard::accept()
{
// TODO
QWizard::accept();
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2015-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_HMM_HPP
#define WORD_SPOTTER_HMM_HPP
#ifndef SPOTTER_NO_HMM
#include <mlpack/core.hpp>
#include <mlpack/methods/hmm/hmm.hpp>
#include <mlpack/methods/gmm/gmm.hpp>
using GMM = mlpack::gmm::GMM;
template<typename Distribution>
using HMM = mlpack::hmm::HMM<Distribution>;
using hmm_p = std::unique_ptr<HMM<GMM>>;
//Number of gaussians for the HMM
static constexpr const std::size_t n_hmm_gaussians = 8;
//Number of gaussians for the GMM
static constexpr const std::size_t n_gmm_gaussians = 64;
template <typename RefFunctor>
hmm_p train_global_hmm(names train_word_names, RefFunctor functor) {
dll::auto_timer("gmm_train");
auto ref_a = functor(train_word_names);
const auto n_states = 1;
const auto n_features = ref_a[0][0].size();
auto hmm = std::make_unique<HMM<GMM>>(n_states, GMM(n_gmm_gaussians, n_features));
std::vector<arma::mat> images;
std::size_t f = 0;
//TODO Configure how the subset if sleected
for(std::size_t image = 0; image < ref_a.size(); image += 10){
auto& ref_image = ref_a[image];
auto width = ref_image.size();
images.emplace_back(n_features, width);
f += width;
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < ref_image[i].size(); ++j){
images.back()(j, i) = ref_image[i][j];
}
}
}
try {
std::cout << "Start training the global HMM" << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_observations=" << f << std::endl;
std::cout << "\tn_total_features=" << f * 9 << std::endl;
hmm->Train(images);
std::cout << "HMM succesfully converged (with " << images.size() << " images)" << std::endl;
} catch (const std::logic_error& e){
std::cout << "frakking HMM failed: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
for(auto& image : images){
image.print("Image");
}
} catch (const std::runtime_error& e){
std::cout << "frakking HMM failed to converge: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
}
return hmm;
}
template <typename Dataset, typename Ref>
hmm_p train_ref_hmm(const Dataset& dataset, Ref& ref_a, names training_images) {
dll::auto_timer("hmm_train");
auto characters = dataset.word_labels.at(training_images[0]).size();
const auto n_states_per_char = 5;
const auto n_states = characters * n_states_per_char;
const auto n_features = ref_a[0][0].size();
auto hmm = std::make_unique<HMM<GMM>>(n_states, GMM(n_hmm_gaussians, n_features));
std::vector<arma::mat> images(ref_a.size());
std::vector<arma::Row<size_t>> labels(ref_a.size());
for(std::size_t image = 0; image < ref_a.size(); ++image){
auto& ref_image = ref_a[image];
auto width = ref_image.size();
images[image] = arma::mat(n_features, width);
labels[image] = arma::Row<size_t>(width);
std::size_t current_label = 0;
std::size_t label_distance = width / n_states;
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < ref_image[i].size(); ++j){
images[image](j, i) = ref_image[i][j];
}
labels[image](i) = std::min(current_label, n_states - 1);
if(i > 0 && i % label_distance == 0){
++current_label;
}
}
}
try {
hmm->Train(images, labels);
std::cout << "HMM succesfully converged (with " << images.size() << " images)" << std::endl;
} catch (const std::logic_error& e){
std::cout << "frakking HMM failed: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
for(std::size_t i = 0; i < images.size(); ++i){
auto& image = images[i];
auto& label = labels[i];
image.print("Image");
label.print("Label");
}
} catch (const std::runtime_error& e){
std::cout << "frakking HMM failed to converge: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
}
return hmm;
}
template <typename Dataset, typename V1>
double hmm_distance(const Dataset& dataset, const hmm_p& global_hmm, const hmm_p& hmm, std::size_t pixel_width, const V1& test_image, names training_images) {
double ref_width = 0;
for(auto& image : training_images){
ref_width += dataset.word_images.at(image + ".png").size().width;
}
ref_width /= training_images.size();
auto ratio = ref_width / pixel_width;
if (ratio > 2.0 || ratio < 0.5) {
return 1e100;
}
//const auto n_states = hmm->Initial().size();
const auto n_features = test_image[0].size();
const auto width = test_image.size();
arma::mat image(n_features, width);
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < test_image[i].size(); ++j){
image(j, i) = test_image[i][j];
}
}
return -(hmm->LogLikelihood(image) / global_hmm->LogLikelihood(image));
}
#else
using hmm_p = int;
template <typename RefFunctor>
hmm_p train_global_hmm(names /*train_word_names*/, RefFunctor /*functor*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
template <typename Dataset, typename Ref>
hmm_p train_ref_hmm(const Dataset& /*dataset*/, Ref& /*ref_a*/, names /*training_images*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
template <typename Dataset, typename V1>
double hmm_distance(const Dataset& /*dataset*/, const hmm_p& /*global_hmm*/, const hmm_p& /*hmm*/, std::size_t /*pixel_width*/, const V1& /*test_image*/, names /*training_images*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
#endif
#endif
<commit_msg>Fix the timers :(<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2015-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_HMM_HPP
#define WORD_SPOTTER_HMM_HPP
#ifndef SPOTTER_NO_HMM
#include <mlpack/core.hpp>
#include <mlpack/methods/hmm/hmm.hpp>
#include <mlpack/methods/gmm/gmm.hpp>
using GMM = mlpack::gmm::GMM;
template<typename Distribution>
using HMM = mlpack::hmm::HMM<Distribution>;
using hmm_p = std::unique_ptr<HMM<GMM>>;
//Number of gaussians for the HMM
static constexpr const std::size_t n_hmm_gaussians = 8;
//Number of gaussians for the GMM
static constexpr const std::size_t n_gmm_gaussians = 64;
template <typename RefFunctor>
hmm_p train_global_hmm(names train_word_names, RefFunctor functor) {
dll::auto_timer timer("gmm_train");
auto ref_a = functor(train_word_names);
const auto n_states = 1;
const auto n_features = ref_a[0][0].size();
auto hmm = std::make_unique<HMM<GMM>>(n_states, GMM(n_gmm_gaussians, n_features));
std::vector<arma::mat> images;
std::size_t f = 0;
//TODO Configure how the subset if sleected
for(std::size_t image = 0; image < ref_a.size(); image += 10){
auto& ref_image = ref_a[image];
auto width = ref_image.size();
images.emplace_back(n_features, width);
f += width;
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < ref_image[i].size(); ++j){
images.back()(j, i) = ref_image[i][j];
}
}
}
try {
std::cout << "Start training the global HMM" << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_observations=" << f << std::endl;
std::cout << "\tn_total_features=" << f * 9 << std::endl;
hmm->Train(images);
std::cout << "HMM succesfully converged (with " << images.size() << " images)" << std::endl;
} catch (const std::logic_error& e){
std::cout << "frakking HMM failed: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
for(auto& image : images){
image.print("Image");
}
} catch (const std::runtime_error& e){
std::cout << "frakking HMM failed to converge: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
}
return hmm;
}
template <typename Dataset, typename Ref>
hmm_p train_ref_hmm(const Dataset& dataset, Ref& ref_a, names training_images) {
dll::auto_timer timer("hmm_train");
auto characters = dataset.word_labels.at(training_images[0]).size();
const auto n_states_per_char = 5;
const auto n_states = characters * n_states_per_char;
const auto n_features = ref_a[0][0].size();
auto hmm = std::make_unique<HMM<GMM>>(n_states, GMM(n_hmm_gaussians, n_features));
std::vector<arma::mat> images(ref_a.size());
std::vector<arma::Row<size_t>> labels(ref_a.size());
for(std::size_t image = 0; image < ref_a.size(); ++image){
auto& ref_image = ref_a[image];
auto width = ref_image.size();
images[image] = arma::mat(n_features, width);
labels[image] = arma::Row<size_t>(width);
std::size_t current_label = 0;
std::size_t label_distance = width / n_states;
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < ref_image[i].size(); ++j){
images[image](j, i) = ref_image[i][j];
}
labels[image](i) = std::min(current_label, n_states - 1);
if(i > 0 && i % label_distance == 0){
++current_label;
}
}
}
try {
hmm->Train(images, labels);
std::cout << "HMM succesfully converged (with " << images.size() << " images)" << std::endl;
} catch (const std::logic_error& e){
std::cout << "frakking HMM failed: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
for(std::size_t i = 0; i < images.size(); ++i){
auto& image = images[i];
auto& label = labels[i];
image.print("Image");
label.print("Label");
}
} catch (const std::runtime_error& e){
std::cout << "frakking HMM failed to converge: " << e.what() << std::endl;
std::cout << "\tn_images: " << images.size() << std::endl;
std::cout << "\tn_features: " << n_features << std::endl;
std::cout << "\tn_states: " << n_states << std::endl;
}
return hmm;
}
template <typename Dataset, typename V1>
double hmm_distance(const Dataset& dataset, const hmm_p& global_hmm, const hmm_p& hmm, std::size_t pixel_width, const V1& test_image, names training_images) {
double ref_width = 0;
for(auto& image : training_images){
ref_width += dataset.word_images.at(image + ".png").size().width;
}
ref_width /= training_images.size();
auto ratio = ref_width / pixel_width;
if (ratio > 2.0 || ratio < 0.5) {
return 1e100;
}
//const auto n_states = hmm->Initial().size();
const auto n_features = test_image[0].size();
const auto width = test_image.size();
arma::mat image(n_features, width);
for(std::size_t i = 0; i < width; ++i){
for(std::size_t j = 0; j < test_image[i].size(); ++j){
image(j, i) = test_image[i][j];
}
}
return -(hmm->LogLikelihood(image) / global_hmm->LogLikelihood(image));
}
#else
using hmm_p = int;
template <typename RefFunctor>
hmm_p train_global_hmm(names /*train_word_names*/, RefFunctor /*functor*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
template <typename Dataset, typename Ref>
hmm_p train_ref_hmm(const Dataset& /*dataset*/, Ref& /*ref_a*/, names /*training_images*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
template <typename Dataset, typename V1>
double hmm_distance(const Dataset& /*dataset*/, const hmm_p& /*global_hmm*/, const hmm_p& /*hmm*/, std::size_t /*pixel_width*/, const V1& /*test_image*/, names /*training_images*/) {
//Disabled HMM
std::cerr << "HMM has been disabled, -hmm should not be used" << std::endl;
}
#endif
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK 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 rtkLUTbasedVariableI0RawToAttenuationImageFilter_hxx
#define rtkLUTbasedVariableI0RawToAttenuationImageFilter_hxx
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include "rtkI0EstimationProjectionFilter.h"
namespace rtk
{
template <class TInputImage, class TOutputImage>
LUTbasedVariableI0RawToAttenuationImageFilter<TInputImage, TOutputImage>
::LUTbasedVariableI0RawToAttenuationImageFilter()
{
// Create the lut
typename LookupTableType::Pointer lut = LookupTableType::New();
typename LookupTableType::SizeType size;
size[0] = itk::NumericTraits<InputImagePixelType>::max()-itk::NumericTraits<InputImagePixelType>::NonpositiveMin()+1;
lut->SetRegions( size );
lut->Allocate();
// Iterate and set lut
itk::ImageRegionIteratorWithIndex<LookupTableType> it( lut, lut->GetBufferedRegion() );
it.Set(0);
++it;
while( !it.IsAtEnd() )
{
it.Set( it.GetIndex()[0] );
++it;
}
// Default value for I0 is the numerical max
m_I0 = size[0]-1;
m_IDark = 0;
// Mini pipeline for creating the lut.
m_SubtractRampFilter = SubtractLUTFilterType::New();
m_SubtractLUTFilter = SubtractLUTFilterType::New();
m_ThresholdRampFilter = ThresholdLUTFilterType::New();
m_LogRampFilter = LogLUTFilterType::New();
m_SubtractRampFilter->SetInput1(lut);
m_SubtractRampFilter->SetConstant2(m_IDark);
m_SubtractRampFilter->InPlaceOff();
m_ThresholdRampFilter->SetInput(m_SubtractRampFilter->GetOutput());
m_ThresholdRampFilter->ThresholdBelow(1.);
m_ThresholdRampFilter->SetOutsideValue(1.);
m_LogRampFilter->SetInput(m_ThresholdRampFilter->GetOutput());
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max(m_I0-m_IDark, 1.) ) );
m_SubtractLUTFilter->SetInput2(m_LogRampFilter->GetOutput());
// Set the lut to member and functor
this->SetLookupTable( m_SubtractLUTFilter->GetOutput() );
}
template <class TInputImage, class TOutputImage>
void
LUTbasedVariableI0RawToAttenuationImageFilter<TInputImage, TOutputImage>
::BeforeThreadedGenerateData()
{
typedef rtk::I0EstimationProjectionFilter<TInputImage> I0EstimationType;
I0EstimationType * i0est = dynamic_cast<I0EstimationType*>( this->GetInput()->GetSource().GetPointer() );
if(i0est)
{
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max((double)i0est->GetI0()-m_IDark, 1.) ) );
}
else
{
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max(m_I0-m_IDark, 1.) ) );
}
m_SubtractRampFilter->SetInput2(m_IDark);
Superclass::BeforeThreadedGenerateData(); // Update the LUT
}
}
#endif
<commit_msg>Update rtkLUTbasedVariableI0RawToAttenuationImageFilter.hxx<commit_after>/*=========================================================================
*
* Copyright RTK 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 rtkLUTbasedVariableI0RawToAttenuationImageFilter_hxx
#define rtkLUTbasedVariableI0RawToAttenuationImageFilter_hxx
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include "rtkI0EstimationProjectionFilter.h"
namespace rtk
{
template <class TInputImage, class TOutputImage>
LUTbasedVariableI0RawToAttenuationImageFilter<TInputImage, TOutputImage>
::LUTbasedVariableI0RawToAttenuationImageFilter()
{
// Create the lut
typename LookupTableType::Pointer lut = LookupTableType::New();
typename LookupTableType::SizeType size;
size[0] = itk::NumericTraits<InputImagePixelType>::max()-itk::NumericTraits<InputImagePixelType>::NonpositiveMin()+1;
lut->SetRegions( size );
lut->Allocate();
// Iterate and set lut
itk::ImageRegionIteratorWithIndex<LookupTableType> it( lut, lut->GetBufferedRegion() );
it.Set(0);
++it;
while( !it.IsAtEnd() )
{
it.Set( it.GetIndex()[0] );
++it;
}
// Default value for I0 is the numerical max
m_I0 = size[0]-1;
m_IDark = 0;
// Mini pipeline for creating the lut.
m_SubtractRampFilter = SubtractLUTFilterType::New();
m_SubtractLUTFilter = SubtractLUTFilterType::New();
m_ThresholdRampFilter = ThresholdLUTFilterType::New();
m_LogRampFilter = LogLUTFilterType::New();
m_SubtractRampFilter->SetInput1(lut);
m_SubtractRampFilter->SetConstant2(m_IDark);
m_SubtractRampFilter->InPlaceOff();
m_ThresholdRampFilter->SetInput(m_SubtractRampFilter->GetOutput());
m_ThresholdRampFilter->ThresholdBelow(1.);
m_ThresholdRampFilter->SetOutsideValue(1.);
m_LogRampFilter->SetInput(m_ThresholdRampFilter->GetOutput());
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max(m_I0-m_IDark, 1.) ) );
m_SubtractLUTFilter->SetInput2(m_LogRampFilter->GetOutput());
// Set the lut to member and functor
this->SetLookupTable( m_SubtractLUTFilter->GetOutput() );
}
template <class TInputImage, class TOutputImage>
void
LUTbasedVariableI0RawToAttenuationImageFilter<TInputImage, TOutputImage>
::BeforeThreadedGenerateData()
{
typedef rtk::I0EstimationProjectionFilter<TInputImage, TOutputImage> I0EstimationType;
I0EstimationType * i0est = dynamic_cast<I0EstimationType*>( this->GetInput()->GetSource().GetPointer() );
if(i0est)
{
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max((double)i0est->GetI0()-m_IDark, 1.) ) );
}
else
{
m_SubtractLUTFilter->SetConstant1((OutputImagePixelType) log( std::max(m_I0-m_IDark, 1.) ) );
}
m_SubtractRampFilter->SetInput2(m_IDark);
Superclass::BeforeThreadedGenerateData(); // Update the LUT
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Richard Martin
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 Richard Martin 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 <COPYRIGHT HOLDER> 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.
*/
#ifndef EVENT_HEADER
#define EVENT_HEADER
template <class T>
class BaseEvent {
private:
const T time;
public:
BaseEvent(T _time = 0) : time(_time) {}
BaseEvent(BaseEvent<T> const & cpy): time(cpy.time) {}
BaseEvent(BaseEvent<T> && mv) : time(mv.time) {}
BaseEvent<T>& operator =(const BaseEvent<T>& cpy) { time = cpy.time; }
BaseEvent<T>& operator =(BaseEvent<T> && mv) { time = mv.time; }
virtual ~BaseEvent() {}
T get_time() const{ return time; }
virtual void dispatch() = 0;
bool operator< (BaseEvent<T> * evnt) {
if(time < evnt->time) {
return true;
}
return false;
}
bool operator> (BaseEvent<T> * evnt) {
if(time > evnt->time) {
return true;
}
return false;
}
bool operator== (BaseEvent<T> * evnt) {
if(time == evnt->time) {
return true;
}
return false;
}
bool operator< (BaseEvent<T> &evnt) {
if(time < evnt.time) {
return true;
}
return false;
}
bool operator> (BaseEvent<T> &evnt) {
if(time > evnt.time) {
return true;
}
return false;
}
bool operator==(BaseEvent<T> &evnt) {
if(time == evnt.time) {
return true;
}
return false;
}
};
#endif
<commit_msg>Moved the Event file to BaseEvent to better reflect the class it contains<commit_after><|endoftext|> |
<commit_before>/*
KSync - Client-Server synchronization system using rsync.
Copyright (C) 2014 Matthew Scott Krafczyk
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <iostream>
#include "ksync/logging.h"
#include "ksync/client.h"
#include "ksync/messages.h"
//#include "ksync/socket_ops.h"
#include "ksync/utilities.h"
#include "ksync/comm_system_interface.h"
#include "ksync/comm_system_factory.h"
#include "ArgParse/ArgParse.h"
int main(int argc, char** argv) {
std::string connect_socket_url = "";
bool connect_socket_url_defined = false;
ArgParse::ArgParser arg_parser("KSync Server - Client side of a Client-Server synchonization system using rsync.");
arg_parser.AddArgument("connect-socket", "Socket to use to negotiate new client connections. Default is : ipc:///ksync/<user>/ksync-connect.ipc", &connect_socket_url, ArgParse::Argument::Optional, &connect_socket_url_defined);
if(arg_parser.ParseArgs(argc, argv) < 0) {
Error("Problem parsing arguments\n");
arg_parser.PrintHelp();
return -1;
}
if(arg_parser.HelpPrinted()) {
return 0;
}
connect_socket_url = "tcp://localhost:5555";
//if(!connect_socket_url_defined){
// if(KSync::Utilities::get_default_connection_url(connect_socket_url) < 0) {
// Error("There was a problem getting the default connection url!\n");
// return -2;
// }
//}
printf("Using the following socket url: %s\n", connect_socket_url.c_str());
KSync::Comm::CommSystemInterface* comm_system = 0;
if (KSync::Comm::GetZeromqCommSystem(comm_system) < 0) {
Error("There was a problem initializing the ZeroMQ communication system!\n");
return -2;
}
KSync::Comm::CommSystemSocket* gateway_socket = 0;
if (comm_system->Create_Gateway_Req_Socket(gateway_socket) < 0) {
Error("There was a problem creating the gateway socket!\n");
return -3;
}
if (gateway_socket->Connect(connect_socket_url) < 0) {
Error("There was a problem connecting to the gateway socket!\n");
return -4;
}
while (true) {
printf("Print message to send to the server:\n");
std::string message_to_send;
std::cin >> message_to_send;
if (message_to_send == "quit") {
printf("Detected quit message. Quitting.");
break;
}
printf("Sending message: (%s)\n", message_to_send.c_str());
KSync::Comm::CommObject* send_obj = new KSync::Comm::CommObject(message_to_send);
if(gateway_socket->Send(send_obj) == 0) {
KSync::Comm::CommObject* recv_obj = 0;
if(gateway_socket->Recv(recv_obj) != 0) {
Warning("Problem receiving response\n");
} else {
std::string message;
if(recv_obj->GetString(message) < 0) {
printf("There was a problem decoding string message\n");
}
KPrint("Received (%s)\n", message.c_str());
if(message_to_send != message) {
printf("Message received wasn't the same as that sent!\n");
}
delete recv_obj;
}
}
delete send_obj;
}
delete gateway_socket;
delete comm_system;
//int connection_socket = 0;
//int connection_endpoint = 0;
//
//printf("create and connect\n");
//
//errno=0;
//if(KSync::SocketOps::Create_And_Connect_Req_Socket(connection_socket, connection_endpoint, connect_socket_url) < 0) {
// Error("Encountered an error trying to create and connect to the connection socket\n");
// return -1;
//}
//if(KSync::SocketOps::Set_Socket_Linger(connection_socket, -1) < 0) {
// Error("Couldn't set socket linger\n");
// return -1;
//}
//
//printf("send\n");
//std::string message = "test_message";
//if(KSync::SocketOps::Send_Message(message, connection_socket) < 0) {
// Warning("There was a problem sending a message to the server.\n");
//}
//usleep(1000000);
//printf("shutdown\n");
//if(KSync::SocketOps::Shutdown_Socket(connection_socket, connection_endpoint) < 0) {
// Warning("There was a problem shutting down the client side of the connection socket.\n");
//}
return 0;
}
<commit_msg>Now use getline with the client<commit_after>/*
KSync - Client-Server synchronization system using rsync.
Copyright (C) 2014 Matthew Scott Krafczyk
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <iostream>
#include "ksync/logging.h"
#include "ksync/client.h"
#include "ksync/messages.h"
//#include "ksync/socket_ops.h"
#include "ksync/utilities.h"
#include "ksync/comm_system_interface.h"
#include "ksync/comm_system_factory.h"
#include "ArgParse/ArgParse.h"
int main(int argc, char** argv) {
std::string connect_socket_url = "";
bool connect_socket_url_defined = false;
ArgParse::ArgParser arg_parser("KSync Server - Client side of a Client-Server synchonization system using rsync.");
arg_parser.AddArgument("connect-socket", "Socket to use to negotiate new client connections. Default is : ipc:///ksync/<user>/ksync-connect.ipc", &connect_socket_url, ArgParse::Argument::Optional, &connect_socket_url_defined);
if(arg_parser.ParseArgs(argc, argv) < 0) {
Error("Problem parsing arguments\n");
arg_parser.PrintHelp();
return -1;
}
if(arg_parser.HelpPrinted()) {
return 0;
}
connect_socket_url = "tcp://localhost:5555";
//if(!connect_socket_url_defined){
// if(KSync::Utilities::get_default_connection_url(connect_socket_url) < 0) {
// Error("There was a problem getting the default connection url!\n");
// return -2;
// }
//}
printf("Using the following socket url: %s\n", connect_socket_url.c_str());
KSync::Comm::CommSystemInterface* comm_system = 0;
if (KSync::Comm::GetZeromqCommSystem(comm_system) < 0) {
Error("There was a problem initializing the ZeroMQ communication system!\n");
return -2;
}
KSync::Comm::CommSystemSocket* gateway_socket = 0;
if (comm_system->Create_Gateway_Req_Socket(gateway_socket) < 0) {
Error("There was a problem creating the gateway socket!\n");
return -3;
}
if (gateway_socket->Connect(connect_socket_url) < 0) {
Error("There was a problem connecting to the gateway socket!\n");
return -4;
}
while (true) {
printf("Print message to send to the server:\n");
std::string message_to_send;
std::getline(std::cin, message_to_send);
if (message_to_send == "quit") {
printf("Detected quit message. Quitting.");
break;
}
printf("Sending message: (%s)\n", message_to_send.c_str());
KSync::Comm::CommObject* send_obj = new KSync::Comm::CommObject(message_to_send);
if(gateway_socket->Send(send_obj) == 0) {
KSync::Comm::CommObject* recv_obj = 0;
if(gateway_socket->Recv(recv_obj) != 0) {
Warning("Problem receiving response\n");
} else {
std::string message;
if(recv_obj->GetString(message) < 0) {
printf("There was a problem decoding string message\n");
}
KPrint("Received (%s)\n", message.c_str());
if(message_to_send != message) {
printf("Message received wasn't the same as that sent!\n");
}
delete recv_obj;
}
}
delete send_obj;
}
delete gateway_socket;
delete comm_system;
//int connection_socket = 0;
//int connection_endpoint = 0;
//
//printf("create and connect\n");
//
//errno=0;
//if(KSync::SocketOps::Create_And_Connect_Req_Socket(connection_socket, connection_endpoint, connect_socket_url) < 0) {
// Error("Encountered an error trying to create and connect to the connection socket\n");
// return -1;
//}
//if(KSync::SocketOps::Set_Socket_Linger(connection_socket, -1) < 0) {
// Error("Couldn't set socket linger\n");
// return -1;
//}
//
//printf("send\n");
//std::string message = "test_message";
//if(KSync::SocketOps::Send_Message(message, connection_socket) < 0) {
// Warning("There was a problem sending a message to the server.\n");
//}
//usleep(1000000);
//printf("shutdown\n");
//if(KSync::SocketOps::Shutdown_Socket(connection_socket, connection_endpoint) < 0) {
// Warning("There was a problem shutting down the client side of the connection socket.\n");
//}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Nagisa Sekiguchi
*
* 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 <fstream>
#include <sstream>
#include <functional>
#include "directive.h"
#include "../platform/platform.h"
#include <misc/fatal.h>
#include <parser.h>
#include <type_checker.h>
#include <core.h>
namespace ydsh {
namespace directive {
#define TRY(expr) \
({ auto v = expr; if(this->hasError()) { return nullptr; } std::forward<decltype(v)>(v); })
struct DirectiveParser : public Parser {
explicit DirectiveParser(Lexer &lexer) : Parser(lexer) {}
~DirectiveParser() = default;
std::unique_ptr<ApplyNode> operator()() {
auto exprNode = TRY(this->parse_appliedName(false));
auto args = TRY(this->parse_arguments());
TRY(this->expect(EOS));
return std::make_unique<ApplyNode>(exprNode.release(), ArgsWrapper::extract(std::move(args)));
}
};
static bool isDirective(const std::string &line) {
auto *ptr = line.c_str();
return strstr(ptr, "#$test") == ptr;
}
static std::pair<std::string, unsigned int> extractDirective(std::istream &input) {
unsigned int lineNum = 0;
for(std::string line; std::getline(input, line); ) {
lineNum++;
if(isDirective(line)) {
line.erase(line.begin());
return {line, lineNum};
}
}
return {std::string(), 0};
}
using AttributeHandler = std::function<void(Node &, Directive &)>;
class DirectiveInitializer : public TypeChecker {
private:
std::string sourceName;
using Handler = std::pair<DSType *, AttributeHandler>;
std::unordered_map<std::string, Handler> handlerMap;
public:
DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable);
~DirectiveInitializer() override = default;
void operator()(ApplyNode &node, Directive &d);
private:
void addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler);
void addHandler(const char *attributeName, TYPE type, AttributeHandler &&handler) {
this->addHandler(attributeName, this->symbolTable.get(type), std::move(handler));
}
void addAlias(const char *alias, const char *attr);
unsigned int resolveStatus(const StringNode &node);
/**
* if not found corresponding handler, return null.
*/
const std::pair<DSType *, AttributeHandler> *lookupHandler(const std::string &name) const;
void checkNode(NodeKind kind, const Node &node);
void setVarName(const char *name, DSType &type);
template <typename T>
T &checkedCast(Node &node) {
this->checkNode(type2info<T>::value, node);
return static_cast<T &>(node);
}
/**
* return always [String : String] type
* @return
*/
DSType &getMapType() {
return *this->symbolTable.createReifiedType(this->symbolTable.getMapTemplate(), {
&this->symbolTable.get(TYPE::String), &this->symbolTable.get(TYPE::String)
}).take();
}
};
// ##################################
// ## DirectiveInitializer ##
// ##################################
static bool checkDirectiveName(ApplyNode &node) {
assert(node.getExprNode()->is(NodeKind::Var));
auto *exprNode = static_cast<VarNode *>(node.getExprNode()); //NOLINT
return exprNode->getVarName() == "test";
}
DirectiveInitializer::DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable) :
TypeChecker(symbolTable, false), sourceName(sourceName) {
this->setVarName("0", this->symbolTable.get(TYPE::String));
}
TypeCheckError createError(const Node &node, const std::string &str) {
return TypeCheckError(node.getToken(), "", str.c_str());
}
void DirectiveInitializer::operator()(ApplyNode &node, Directive &d) {
if(!checkDirectiveName(node)) {
std::string str("unsupported directive: ");
str += static_cast<VarNode *>(node.getExprNode())->getVarName(); //NOLINT
throw createError(node, str);
}
this->addHandler("status", TYPE::Int32, [&](Node &node, Directive &d) {
d.setStatus(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("result", TYPE::String, [&](Node &node, Directive &d) {
d.setResult(this->resolveStatus(this->checkedCast<StringNode>(node)));
});
this->addHandler("params", TYPE::StringArray, [&](Node &node, Directive &d) {
auto &value = this->checkedCast<ArrayNode>(node);
for(auto &e : value.getExprNodes()) {
d.appendParam(this->checkedCast<StringNode>(*e).getValue());
}
});
this->addHandler("lineNum", TYPE::Int32, [&](Node &node, Directive &d) {
d.setLineNum(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("errorKind", TYPE::String, [&](Node &node, Directive &d) {
d.setErrorKind(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("in", TYPE::String, [&](Node &node, Directive &d) {
d.setIn(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("out", TYPE::String, [&](Node &node, Directive &d) {
d.setOut(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("err", TYPE::String, [&](Node &node, Directive &d) {
d.setErr(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("fileName", TYPE::String, [&](Node &node, Directive &d) {
if(node.is(NodeKind::Var) &&
this->checkedCast<VarNode>(node).getVarName() == "0") {
d.setFileName(this->sourceName.c_str());
return;
}
std::string str = this->checkedCast<StringNode>(node).getValue();
expandTilde(str);
char *buf = realpath(str.c_str(), nullptr);
if(buf == nullptr) {
std::string message = "invalid file name: ";
message += str;
throw createError(node, message);
}
d.setFileName(buf);
free(buf);
});
this->addHandler("envs", this->getMapType(), [&](Node &node, Directive &d) {
auto &mapNode = this->checkedCast<MapNode>(node);
const unsigned int size = mapNode.getKeyNodes().size();
for(unsigned int i = 0; i < size; i++) {
auto &keyNode = this->checkedCast<StringNode>(*mapNode.getKeyNodes()[i]);
auto &valueNode = this->checkedCast<StringNode>(*mapNode.getValueNodes()[i]);
d.addEnv(keyNode.getValue(), valueNode.getValue());
}
});
this->addAlias("env", "envs");
this->addHandler("ignored", TYPE::String, [&](Node &node, Directive &d) {
auto &str = this->checkedCast<StringNode>(node).getValue();
d.setIgnoredPlatform(platform::contain(str));
});
std::unordered_set<std::string> foundAttrSet;
for(auto &attrNode : node.getArgNodes()) {
auto &assignNode = this->checkedCast<AssignNode>(*attrNode);
auto &attrName = this->checkedCast<VarNode>(*assignNode.getLeftNode()).getVarName();
auto *pair = this->lookupHandler(attrName);
if(pair == nullptr) {
std::string str("unsupported attribute: ");
str += attrName;
throw createError(*assignNode.getLeftNode(), str);
}
// check duplication
auto iter = foundAttrSet.find(attrName);
if(iter != foundAttrSet.end()) {
std::string str("duplicated attribute: ");
str += attrName;
throw createError(*assignNode.getLeftNode(), str);
}
// check type attribute
this->checkType(*pair->first, assignNode.getRightNode());
// invoke handler
(pair->second)(*assignNode.getRightNode(), d);
foundAttrSet.insert(attrName);
}
}
void DirectiveInitializer::addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler) {
auto pair = this->handlerMap.insert(std::make_pair(attributeName, std::make_pair(&type, std::move(handler))));
if(!pair.second) {
fatal("found duplicated handler: %s\n", attributeName);
}
}
void DirectiveInitializer::addAlias(const char *alias, const char *attr) {
auto *handler = this->lookupHandler(attr);
if(handler != nullptr) {
this->addHandler(alias, *handler->first, AttributeHandler(handler->second));
}
}
unsigned int DirectiveInitializer::resolveStatus(const StringNode &node) {
const struct {
const char *name;
unsigned int status;
} statusTable[] = {
#define _E(K) DS_ERROR_KIND_##K
{"success", _E(SUCCESS)},
{"parse_error", _E(PARSE_ERROR)},
{"parse", _E(PARSE_ERROR)},
{"type_error", _E(TYPE_ERROR)},
{"type", _E(TYPE_ERROR)},
{"runtime_error", _E(RUNTIME_ERROR)},
{"runtime", _E(RUNTIME_ERROR)},
{"throw", _E(RUNTIME_ERROR)},
{"assertion_error", _E(ASSERTION_ERROR)},
{"assert", _E(ASSERTION_ERROR)},
{"exit", _E(EXIT)},
#undef _E
};
for(auto &e : statusTable) {
if(strcasecmp(node.getValue().c_str(), e.name) == 0) {
return e.status;
}
}
std::vector<std::string> alters;
for(auto &e : statusTable) {
alters.emplace_back(e.name);
}
std::string message("illegal status, expect for ");
unsigned int count = 0;
for(auto &e : alters) {
if(count++ > 0) {
message += ", ";
}
message += e;
}
throw createError(node, message);
// return 0;
}
const std::pair<DSType *, AttributeHandler> *DirectiveInitializer::lookupHandler(const std::string &name) const {
auto iter = this->handlerMap.find(name);
if(iter == this->handlerMap.end()) {
return nullptr;
}
return &iter->second;
}
void DirectiveInitializer::checkNode(NodeKind kind, const Node &node) {
const char *table[] = {
#define GEN_STR(K) #K,
EACH_NODE_KIND(GEN_STR)
#undef GEN_STR
};
if(!node.is(kind)) {
std::string str = "require: ";
str += table[static_cast<unsigned int>(kind)];
str += "Node, but is: ";
str += table[static_cast<unsigned int>(node.getNodeKind())];
str += "Node";
throw TypeCheckError(node.getToken(), "", str.c_str());
}
}
void DirectiveInitializer::setVarName(const char *name, DSType &type) {
this->symbolTable.newHandle(name, type, FieldAttribute());
}
// #######################
// ## Directive ##
// #######################
Directive::~Directive() {
free(this->out);
free(this->err);
}
static void showError(const char *sourceName, Lexer &lexer, const std::string &line,
Token errorToken, const std::string &message, const char *errorName) {
Token lineToken = {0, static_cast<unsigned int>(line.size())};
std::cerr << sourceName << ":" << lexer.getLineNum() << ": [" << errorName << " error] ";
std::cerr << message << std::endl;
std::cerr << line << std::endl;
std::cerr << lexer.formatLineMarker(lineToken, errorToken) << std::endl;
}
static bool initDirective(const char *fileName, std::istream &input, Directive &directive) {
auto ret = extractDirective(input);
if(ret.first.empty()) {
return true;
}
Lexer lexer(fileName, ret.first.c_str());
lexer.setLineNum(ret.second);
DirectiveParser parser(lexer);
auto node = parser();
if(parser.hasError()) {
auto &e = parser.getError();
showError(fileName, lexer, ret.first, e.getErrorToken(), e.getMessage(), "syntax");
return false;
}
try {
SymbolTable symbolTable;
DirectiveInitializer initializer(fileName, symbolTable);
initializer(*node, directive);
} catch(const TypeCheckError &e) {
showError(fileName, lexer, ret.first, e.getToken(), e.getMessage(), "semantic");
return false;
}
return true;
}
bool Directive::init(const char *fileName, Directive &d) {
std::ifstream input(fileName);
if(!input) {
fatal("cannot open file: %s\n", fileName);
}
return initDirective(fileName, input, d);
}
bool Directive::init(const char *sourceName, const char *src, Directive &d) {
std::istringstream input(src);
return initDirective(sourceName, input, d);
}
} // namespace directive
} // namespace ydsh<commit_msg>fix error reporting of directive<commit_after>/*
* Copyright (C) 2017 Nagisa Sekiguchi
*
* 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 <fstream>
#include <sstream>
#include <functional>
#include "directive.h"
#include "../platform/platform.h"
#include <misc/fatal.h>
#include <parser.h>
#include <type_checker.h>
#include <core.h>
namespace ydsh {
namespace directive {
#define TRY(expr) \
({ auto v = expr; if(this->hasError()) { return nullptr; } std::forward<decltype(v)>(v); })
struct DirectiveParser : public Parser {
explicit DirectiveParser(Lexer &lexer) : Parser(lexer) {}
~DirectiveParser() = default;
std::unique_ptr<ApplyNode> operator()() {
auto exprNode = TRY(this->parse_appliedName(false));
auto args = TRY(this->parse_arguments());
TRY(this->expect(EOS));
return std::make_unique<ApplyNode>(exprNode.release(), ArgsWrapper::extract(std::move(args)));
}
};
static bool isDirective(const std::string &line) {
auto *ptr = line.c_str();
return strstr(ptr, "#$test") == ptr;
}
static std::pair<std::string, unsigned int> extractDirective(std::istream &input) {
unsigned int lineNum = 0;
for(std::string line; std::getline(input, line); ) {
lineNum++;
if(isDirective(line)) {
line.erase(line.begin());
return {line, lineNum};
}
}
return {std::string(), 0};
}
class DirectiveInitializer : public TypeChecker {
private:
std::string sourceName;
using AttributeHandler = std::function<void(Node &, Directive &)>;
using Handler = std::pair<DSType *, AttributeHandler>;
std::unordered_map<std::string, Handler> handlerMap;
std::unique_ptr<TypeCheckError> error;
public:
DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable);
~DirectiveInitializer() override = default;
void operator()(ApplyNode &node, Directive &d);
bool hasError() const {
return static_cast<bool>(this->error);
}
const TypeCheckError &getError() const {
return *this->error;
}
private:
void addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler);
void addHandler(const char *attributeName, TYPE type, AttributeHandler &&handler) {
this->addHandler(attributeName, this->symbolTable.get(type), std::move(handler));
}
void addAlias(const char *alias, const char *attr);
unsigned int resolveStatus(const StringNode &node);
/**
* if not found corresponding handler, return null.
*/
const std::pair<DSType *, AttributeHandler> *lookupHandler(const std::string &name) const;
bool checkNode(NodeKind kind, const Node &node);
void setVarName(const char *name, DSType &type);
template <typename T>
T *checkedCast(Node &node) {
if(!this->checkNode(type2info<T>::value, node)) {
return nullptr;
}
return static_cast<T *>(&node);
}
/**
* return always [String : String] type
* @return
*/
DSType &getMapType() {
return *this->symbolTable.createReifiedType(this->symbolTable.getMapTemplate(), {
&this->symbolTable.get(TYPE::String), &this->symbolTable.get(TYPE::String)
}).take();
}
void createError(const Node &node, const std::string &str) {
this->error = std::make_unique<TypeCheckError>(node.getToken(), "", str.c_str());
}
};
#undef TRY
#define TRY(E) ({ auto v = E; if(this->hasError()) { return; } std::forward<decltype(v)>(v); })
// ##################################
// ## DirectiveInitializer ##
// ##################################
static bool checkDirectiveName(ApplyNode &node) {
assert(node.getExprNode()->is(NodeKind::Var));
auto *exprNode = static_cast<VarNode *>(node.getExprNode()); //NOLINT
return exprNode->getVarName() == "test";
}
DirectiveInitializer::DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable) :
TypeChecker(symbolTable, false), sourceName(sourceName) {
this->setVarName("0", this->symbolTable.get(TYPE::String));
}
void DirectiveInitializer::operator()(ApplyNode &node, Directive &d) {
if(!checkDirectiveName(node)) {
std::string str("unsupported directive: ");
str += static_cast<VarNode *>(node.getExprNode())->getVarName(); //NOLINT
return this->createError(node, str);
}
this->addHandler("status", TYPE::Int32, [&](Node &node, Directive &d) {
d.setStatus(TRY(this->checkedCast<NumberNode>(node))->getIntValue());
});
this->addHandler("result", TYPE::String, [&](Node &node, Directive &d) {
auto *strNode = TRY(this->checkedCast<StringNode>(node));
d.setResult(TRY(this->resolveStatus(*strNode)));
});
this->addHandler("params", TYPE::StringArray, [&](Node &node, Directive &d) {
auto *value = TRY(this->checkedCast<ArrayNode>(node));
for(auto &e : value->getExprNodes()) {
d.appendParam(TRY(this->checkedCast<StringNode>(*e))->getValue());
}
});
this->addHandler("lineNum", TYPE::Int32, [&](Node &node, Directive &d) {
d.setLineNum(TRY(this->checkedCast<NumberNode>(node))->getIntValue());
});
this->addHandler("errorKind", TYPE::String, [&](Node &node, Directive &d) {
d.setErrorKind(TRY(this->checkedCast<StringNode>(node))->getValue());
});
this->addHandler("in", TYPE::String, [&](Node &node, Directive &d) {
d.setIn(TRY(this->checkedCast<StringNode>(node))->getValue());
});
this->addHandler("out", TYPE::String, [&](Node &node, Directive &d) {
d.setOut(TRY(this->checkedCast<StringNode>(node))->getValue());
});
this->addHandler("err", TYPE::String, [&](Node &node, Directive &d) {
d.setErr(TRY(this->checkedCast<StringNode>(node))->getValue());
});
this->addHandler("fileName", TYPE::String, [&](Node &node, Directive &d) {
if(node.is(NodeKind::Var) &&
TRY(this->checkedCast<VarNode>(node))->getVarName() == "0") {
d.setFileName(this->sourceName.c_str());
return;
}
std::string str = TRY(this->checkedCast<StringNode>(node))->getValue();
expandTilde(str);
char *buf = realpath(str.c_str(), nullptr);
if(buf == nullptr) {
std::string message = "invalid file name: ";
message += str;
return this->createError(node, message);
}
d.setFileName(buf);
free(buf);
});
this->addHandler("envs", this->getMapType(), [&](Node &node, Directive &d) {
auto *mapNode = TRY(this->checkedCast<MapNode>(node));
const unsigned int size = mapNode->getKeyNodes().size();
for(unsigned int i = 0; i < size; i++) {
auto *keyNode = TRY(this->checkedCast<StringNode>(*mapNode->getKeyNodes()[i]));
auto *valueNode = TRY(this->checkedCast<StringNode>(*mapNode->getValueNodes()[i]));
d.addEnv(keyNode->getValue(), valueNode->getValue());
}
});
this->addAlias("env", "envs");
this->addHandler("ignored", TYPE::String, [&](Node &node, Directive &d) {
auto &str = TRY(this->checkedCast<StringNode>(node))->getValue();
d.setIgnoredPlatform(platform::contain(str));
});
std::unordered_set<std::string> foundAttrSet;
for(auto &attrNode : node.getArgNodes()) {
auto *assignNode = TRY(this->checkedCast<AssignNode>(*attrNode));
auto &attrName = TRY(this->checkedCast<VarNode>(*assignNode->getLeftNode()))->getVarName();
auto *pair = this->lookupHandler(attrName);
if(pair == nullptr) {
std::string str("unsupported attribute: ");
str += attrName;
return this->createError(*assignNode->getLeftNode(), str);
}
// check duplication
auto iter = foundAttrSet.find(attrName);
if(iter != foundAttrSet.end()) {
std::string str("duplicated attribute: ");
str += attrName;
return this->createError(*assignNode->getLeftNode(), str);
}
// check type attribute
try {
this->checkType(*pair->first, assignNode->getRightNode());
} catch(const TypeCheckError &e) {
this->error = std::make_unique<TypeCheckError>(e);
return;
}
// invoke handler
(pair->second)(*assignNode->getRightNode(), d);
if(this->hasError()) {
return;
}
foundAttrSet.insert(attrName);
}
}
void DirectiveInitializer::addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler) {
auto pair = this->handlerMap.insert(std::make_pair(attributeName, std::make_pair(&type, std::move(handler))));
if(!pair.second) {
fatal("found duplicated handler: %s\n", attributeName);
}
}
void DirectiveInitializer::addAlias(const char *alias, const char *attr) {
auto *handler = this->lookupHandler(attr);
if(handler != nullptr) {
this->addHandler(alias, *handler->first, AttributeHandler(handler->second));
}
}
unsigned int DirectiveInitializer::resolveStatus(const StringNode &node) {
const struct {
const char *name;
unsigned int status;
} statusTable[] = {
#define _E(K) DS_ERROR_KIND_##K
{"success", _E(SUCCESS)},
{"parse_error", _E(PARSE_ERROR)},
{"parse", _E(PARSE_ERROR)},
{"type_error", _E(TYPE_ERROR)},
{"type", _E(TYPE_ERROR)},
{"runtime_error", _E(RUNTIME_ERROR)},
{"runtime", _E(RUNTIME_ERROR)},
{"throw", _E(RUNTIME_ERROR)},
{"assertion_error", _E(ASSERTION_ERROR)},
{"assert", _E(ASSERTION_ERROR)},
{"exit", _E(EXIT)},
#undef _E
};
for(auto &e : statusTable) {
if(strcasecmp(node.getValue().c_str(), e.name) == 0) {
return e.status;
}
}
std::vector<std::string> alters;
for(auto &e : statusTable) {
alters.emplace_back(e.name);
}
std::string message("illegal status, expect for ");
unsigned int count = 0;
for(auto &e : alters) {
if(count++ > 0) {
message += ", ";
}
message += e;
}
createError(node, message);
return 0;
}
const std::pair<DSType *, DirectiveInitializer::AttributeHandler>
*DirectiveInitializer::lookupHandler(const std::string &name) const {
auto iter = this->handlerMap.find(name);
if(iter == this->handlerMap.end()) {
return nullptr;
}
return &iter->second;
}
bool DirectiveInitializer::checkNode(NodeKind kind, const Node &node) {
const char *table[] = {
#define GEN_STR(K) #K,
EACH_NODE_KIND(GEN_STR)
#undef GEN_STR
};
if(!node.is(kind)) {
std::string str = "require: ";
str += table[static_cast<unsigned int>(kind)];
str += "Node, but is: ";
str += table[static_cast<unsigned int>(node.getNodeKind())];
str += "Node";
this->createError(node, str);
return false;
}
return true;
}
void DirectiveInitializer::setVarName(const char *name, DSType &type) {
this->symbolTable.newHandle(name, type, FieldAttribute());
}
// #######################
// ## Directive ##
// #######################
Directive::~Directive() {
free(this->out);
free(this->err);
}
static void showError(const char *sourceName, Lexer &lexer, const std::string &line,
Token errorToken, const std::string &message, const char *errorName) {
Token lineToken = {0, static_cast<unsigned int>(line.size())};
std::cerr << sourceName << ":" << lexer.getLineNum() << ": [" << errorName << " error] ";
std::cerr << message << std::endl;
std::cerr << line << std::endl;
std::cerr << lexer.formatLineMarker(lineToken, errorToken) << std::endl;
}
static bool initDirective(const char *fileName, std::istream &input, Directive &directive) {
auto ret = extractDirective(input);
if(ret.first.empty()) {
return true;
}
Lexer lexer(fileName, ret.first.c_str());
lexer.setLineNum(ret.second);
DirectiveParser parser(lexer);
auto node = parser();
if(parser.hasError()) {
auto &e = parser.getError();
showError(fileName, lexer, ret.first, e.getErrorToken(), e.getMessage(), "syntax");
return false;
}
SymbolTable symbolTable;
DirectiveInitializer initializer(fileName, symbolTable);
initializer(*node, directive);
if(initializer.hasError()) {
auto &e = initializer.getError();
showError(fileName, lexer, ret.first, e.getToken(), e.getMessage(), "semantic");
return false;
}
return true;
}
bool Directive::init(const char *fileName, Directive &d) {
std::ifstream input(fileName);
if(!input) {
fatal("cannot open file: %s\n", fileName);
}
return initDirective(fileName, input, d);
}
bool Directive::init(const char *sourceName, const char *src, Directive &d) {
std::istringstream input(src);
return initDirective(sourceName, input, d);
}
} // namespace directive
} // namespace ydsh<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Nagisa Sekiguchi
*
* 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 <fstream>
#include <sstream>
#include <functional>
#include "directive.h"
#include <misc/fatal.h>
#include <parser.h>
#include <type_checker.h>
#include <core.h>
namespace ydsh {
namespace directive {
#define TRY(expr) \
({ auto v = expr; if(this->hasError()) { return nullptr; } std::forward<decltype(v)>(v); })
struct DirectiveParser : public Parser {
explicit DirectiveParser(Lexer &lexer) : Parser(lexer) {}
~DirectiveParser() = default;
std::unique_ptr<ApplyNode> operator()() {
auto exprNode = TRY(this->parse_appliedName(false));
auto args = TRY(this->parse_arguments());
TRY(this->expect(EOS));
return make_unique<ApplyNode>(exprNode.release(), ArgsWrapper::extract(std::move(args)));
}
};
static bool isDirective(const std::string &line) {
auto *ptr = line.c_str();
return strstr(ptr, "#$test") == ptr;
}
static std::pair<std::string, unsigned int> extractDirective(std::istream &input) {
unsigned int lineNum = 0;
for(std::string line; std::getline(input, line); ) {
lineNum++;
if(isDirective(line)) {
line.erase(line.begin());
return {line, lineNum};
}
}
return {std::string(), 0};
}
using AttributeHandler = std::function<void(Node &, Directive &)>;
class DirectiveInitializer : public TypeChecker {
private:
std::string sourceName;
using Handler = std::pair<DSType *, AttributeHandler>;
std::unordered_map<std::string, Handler> handlerMap;
public:
DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable);
~DirectiveInitializer() override = default;
void operator()(ApplyNode &node, Directive &d);
private:
void addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler);
unsigned int resolveStatus(const StringNode &node);
/**
* if not found corresponding handler, return null.
*/
const std::pair<DSType *, AttributeHandler> *lookupHandler(const std::string &name) const;
void checkNode(NodeKind kind, const Node &node);
void setVarName(const char *name, DSType &type);
template <typename T>
T &checkedCast(Node &node) {
this->checkNode(type2info<T>::value, node);
return static_cast<T &>(node);
}
};
// ##################################
// ## DirectiveInitializer ##
// ##################################
static bool checkDirectiveName(ApplyNode &node) {
assert(node.getExprNode()->is(NodeKind::Var));
auto *exprNode = static_cast<VarNode *>(node.getExprNode());
return exprNode->getVarName() == "test";
}
static bool toBool(const std::string &str) {
return strcasecmp(str.c_str(), "true") == 0;
}
DirectiveInitializer::DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable) :
TypeChecker(symbolTable, false), sourceName(sourceName) {
auto &boolType = this->symbolTable.get(TYPE::Boolean);
const char *names[] = {
"TRUE", "True", "true", "FALSE", "False", "false",
};
for(auto &name : names) {
this->setVarName(name, boolType);
}
this->setVarName("0", this->symbolTable.get(TYPE::String));
}
void DirectiveInitializer::operator()(ApplyNode &node, Directive &d) {
if(!checkDirectiveName(node)) {
std::string str("unsupported directive: ");
str += static_cast<VarNode *>(node.getExprNode())->getVarName();
throw TypeCheckError(node.getToken(), "", str.c_str());
}
this->addHandler("status", this->symbolTable.get(TYPE::Int32), [&](Node &node, Directive &d) {
d.setStatus(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("result", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setResult(this->resolveStatus(this->checkedCast<StringNode>(node)));
});
this->addHandler("params", this->symbolTable.get(TYPE::StringArray), [&](Node &node, Directive &d) {
auto &value = this->checkedCast<ArrayNode>(node);
for(auto &e : value.getExprNodes()) {
d.appendParam(this->checkedCast<StringNode>(*e).getValue());
}
});
this->addHandler("lineNum", this->symbolTable.get(TYPE::Int32), [&](Node &node, Directive &d) {
d.setLineNum(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("ifHaveDBus", this->symbolTable.get(TYPE::Boolean), [&](Node &node, Directive &d) {
bool v = toBool(this->checkedCast<VarNode>(node).getVarName());
d.setIfHaveDBus(v);
});
this->addHandler("errorKind", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setErrorKind(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("out", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setOut(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("err", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setErr(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("fileName", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
if(node.getNodeKind() == NodeKind::Var &&
this->checkedCast<VarNode>(node).getVarName() == "0") {
d.setFileName(this->sourceName.c_str());
return;
}
std::string str = this->checkedCast<StringNode>(node).getValue();
expandTilde(str);
char *buf = realpath(str.c_str(), nullptr);
if(buf == nullptr) {
std::string message = "invalid file name: ";
message += str;
throw TypeCheckError(node.getToken(), "", message.c_str());
}
d.setFileName(buf);
free(buf);
});
std::unordered_set<std::string> foundAttrSet;
for(auto &attrNode : node.getArgNodes()) {
auto &assignNode = this->checkedCast<AssignNode>(*attrNode);
auto &attrName = this->checkedCast<VarNode>(*assignNode.getLeftNode()).getVarName();
auto *pair = this->lookupHandler(attrName);
if(pair == nullptr) {
std::string str("unsupported attribute: ");
str += attrName;
throw TypeCheckError(assignNode.getLeftNode()->getToken(), "", str.c_str());
}
// check duplication
auto iter = foundAttrSet.find(attrName);
if(iter != foundAttrSet.end()) {
std::string str("duplicated attribute: ");
str += attrName;
throw TypeCheckError(assignNode.getLeftNode()->getToken(), "", str.c_str());
}
// check type attribute
this->checkType(*pair->first, assignNode.getRightNode());
// invoke handler
(pair->second)(*assignNode.getRightNode(), d);
foundAttrSet.insert(attrName);
}
}
void DirectiveInitializer::addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler) {
auto pair = this->handlerMap.insert(std::make_pair(attributeName, std::make_pair(&type, std::move(handler))));
if(!pair.second) {
fatal("found duplicated handler: %s\n", attributeName);
}
}
unsigned int DirectiveInitializer::resolveStatus(const StringNode &node) {
const struct {
const char *name;
unsigned int status;
} statusTable[] = {
#define _E(K) DS_ERROR_KIND_##K
{"success", _E(SUCCESS)},
{"parse_error", _E(PARSE_ERROR)},
{"parse", _E(PARSE_ERROR)},
{"type_error", _E(TYPE_ERROR)},
{"type", _E(TYPE_ERROR)},
{"runtime_error", _E(RUNTIME_ERROR)},
{"runtime", _E(RUNTIME_ERROR)},
{"throw", _E(RUNTIME_ERROR)},
{"assertion_error", _E(ASSERTION_ERROR)},
{"assert", _E(ASSERTION_ERROR)},
{"exit", _E(EXIT)},
#undef _E
};
for(auto &e : statusTable) {
if(strcasecmp(node.getValue().c_str(), e.name) == 0) {
return e.status;
}
}
std::vector<std::string> alters;
for(auto &e : statusTable) {
alters.emplace_back(e.name);
}
std::string message("illegal status, expect for ");
unsigned int count = 0;
for(auto &e : alters) {
if(count++ > 0) {
message += ", ";
}
message += e;
}
throw TypeCheckError(node.getToken(), "", message.c_str());
// return 0;
}
const std::pair<DSType *, AttributeHandler> *DirectiveInitializer::lookupHandler(const std::string &name) const {
auto iter = this->handlerMap.find(name);
if(iter == this->handlerMap.end()) {
return nullptr;
}
return &iter->second;
}
void DirectiveInitializer::checkNode(NodeKind kind, const Node &node) {
const char *table[] = {
#define GEN_STR(K) #K,
EACH_NODE_KIND(GEN_STR)
#undef GEN_STR
};
if(!node.is(kind)) {
std::string str = "require: ";
str += table[static_cast<unsigned int>(kind)];
str += "Node, but is: ";
str += table[static_cast<unsigned int>(node.getNodeKind())];
str += "Node";
throw TypeCheckError(node.getToken(), "", str.c_str());
}
}
void DirectiveInitializer::setVarName(const char *name, DSType &type) {
this->symbolTable.newHandle(name, type, FieldAttributes());
}
// #######################
// ## Directive ##
// #######################
Directive::~Directive() {
free(this->out);
free(this->err);
}
static void showError(const char *sourceName, Lexer &lexer, const std::string &line,
Token errorToken, const std::string &message, const char *errorName) {
Token lineToken = {0, static_cast<unsigned int>(line.size())};
std::cerr << sourceName << ":" << lexer.getLineNum() << ": [" << errorName << " error] ";
std::cerr << message << std::endl;
std::cerr << line << std::endl;
std::cerr << lexer.formatLineMarker(lineToken, errorToken) << std::endl;
}
static bool initDirective(const char *fileName, std::istream &input, Directive &directive) {
auto ret = extractDirective(input);
if(ret.first.empty()) {
return true;
}
Lexer lexer(fileName, ret.first.c_str());
lexer.setLineNum(ret.second);
DirectiveParser parser(lexer);
auto node = parser();
if(parser.hasError()) {
auto &e = parser.getError();
showError(fileName, lexer, ret.first, e.getErrorToken(), e.getMessage(), "syntax");
return false;
}
try {
SymbolTable symbolTable;
DirectiveInitializer initializer(fileName, symbolTable);
initializer(*node, directive);
} catch(const TypeCheckError &e) {
showError(fileName, lexer, ret.first, e.getToken(), e.getMessage(), "semantic");
return false;
}
return true;
}
bool Directive::init(const char *fileName, Directive &d) {
std::ifstream input(fileName);
if(!input) {
fatal("cannot open file: %s\n", fileName);
}
return initDirective(fileName, input, d);
}
bool Directive::init(const char *sourceName, const char *src, Directive &d) {
std::istringstream input(src);
return initDirective(sourceName, input, d);
}
} // namespace directive
} // namespace ydsh<commit_msg>refactor<commit_after>/*
* Copyright (C) 2017 Nagisa Sekiguchi
*
* 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 <fstream>
#include <sstream>
#include <functional>
#include "directive.h"
#include <misc/fatal.h>
#include <parser.h>
#include <type_checker.h>
#include <core.h>
namespace ydsh {
namespace directive {
#define TRY(expr) \
({ auto v = expr; if(this->hasError()) { return nullptr; } std::forward<decltype(v)>(v); })
struct DirectiveParser : public Parser {
explicit DirectiveParser(Lexer &lexer) : Parser(lexer) {}
~DirectiveParser() = default;
std::unique_ptr<ApplyNode> operator()() {
auto exprNode = TRY(this->parse_appliedName(false));
auto args = TRY(this->parse_arguments());
TRY(this->expect(EOS));
return make_unique<ApplyNode>(exprNode.release(), ArgsWrapper::extract(std::move(args)));
}
};
static bool isDirective(const std::string &line) {
auto *ptr = line.c_str();
return strstr(ptr, "#$test") == ptr;
}
static std::pair<std::string, unsigned int> extractDirective(std::istream &input) {
unsigned int lineNum = 0;
for(std::string line; std::getline(input, line); ) {
lineNum++;
if(isDirective(line)) {
line.erase(line.begin());
return {line, lineNum};
}
}
return {std::string(), 0};
}
using AttributeHandler = std::function<void(Node &, Directive &)>;
class DirectiveInitializer : public TypeChecker {
private:
std::string sourceName;
using Handler = std::pair<DSType *, AttributeHandler>;
std::unordered_map<std::string, Handler> handlerMap;
public:
DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable);
~DirectiveInitializer() override = default;
void operator()(ApplyNode &node, Directive &d);
private:
void addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler);
unsigned int resolveStatus(const StringNode &node);
/**
* if not found corresponding handler, return null.
*/
const std::pair<DSType *, AttributeHandler> *lookupHandler(const std::string &name) const;
void checkNode(NodeKind kind, const Node &node);
void setVarName(const char *name, DSType &type);
template <typename T>
T &checkedCast(Node &node) {
this->checkNode(type2info<T>::value, node);
return static_cast<T &>(node);
}
};
// ##################################
// ## DirectiveInitializer ##
// ##################################
static bool checkDirectiveName(ApplyNode &node) {
assert(node.getExprNode()->is(NodeKind::Var));
auto *exprNode = static_cast<VarNode *>(node.getExprNode());
return exprNode->getVarName() == "test";
}
static bool toBool(const std::string &str) {
return strcasecmp(str.c_str(), "true") == 0;
}
DirectiveInitializer::DirectiveInitializer(const char *sourceName, SymbolTable &symbolTable) :
TypeChecker(symbolTable, false), sourceName(sourceName) {
auto &boolType = this->symbolTable.get(TYPE::Boolean);
const char *names[] = {
"TRUE", "True", "true", "FALSE", "False", "false",
};
for(auto &name : names) {
this->setVarName(name, boolType);
}
this->setVarName("0", this->symbolTable.get(TYPE::String));
}
TypeCheckError createError(const Node &node, const std::string &str) {
return TypeCheckError(node.getToken(), "", str.c_str());
}
void DirectiveInitializer::operator()(ApplyNode &node, Directive &d) {
if(!checkDirectiveName(node)) {
std::string str("unsupported directive: ");
str += static_cast<VarNode *>(node.getExprNode())->getVarName();
throw createError(node, str);
}
this->addHandler("status", this->symbolTable.get(TYPE::Int32), [&](Node &node, Directive &d) {
d.setStatus(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("result", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setResult(this->resolveStatus(this->checkedCast<StringNode>(node)));
});
this->addHandler("params", this->symbolTable.get(TYPE::StringArray), [&](Node &node, Directive &d) {
auto &value = this->checkedCast<ArrayNode>(node);
for(auto &e : value.getExprNodes()) {
d.appendParam(this->checkedCast<StringNode>(*e).getValue());
}
});
this->addHandler("lineNum", this->symbolTable.get(TYPE::Int32), [&](Node &node, Directive &d) {
d.setLineNum(this->checkedCast<NumberNode>(node).getIntValue());
});
this->addHandler("ifHaveDBus", this->symbolTable.get(TYPE::Boolean), [&](Node &node, Directive &d) {
bool v = toBool(this->checkedCast<VarNode>(node).getVarName());
d.setIfHaveDBus(v);
});
this->addHandler("errorKind", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setErrorKind(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("out", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setOut(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("err", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
d.setErr(this->checkedCast<StringNode>(node).getValue());
});
this->addHandler("fileName", this->symbolTable.get(TYPE::String), [&](Node &node, Directive &d) {
if(node.getNodeKind() == NodeKind::Var &&
this->checkedCast<VarNode>(node).getVarName() == "0") {
d.setFileName(this->sourceName.c_str());
return;
}
std::string str = this->checkedCast<StringNode>(node).getValue();
expandTilde(str);
char *buf = realpath(str.c_str(), nullptr);
if(buf == nullptr) {
std::string message = "invalid file name: ";
message += str;
throw createError(node, message);
}
d.setFileName(buf);
free(buf);
});
std::unordered_set<std::string> foundAttrSet;
for(auto &attrNode : node.getArgNodes()) {
auto &assignNode = this->checkedCast<AssignNode>(*attrNode);
auto &attrName = this->checkedCast<VarNode>(*assignNode.getLeftNode()).getVarName();
auto *pair = this->lookupHandler(attrName);
if(pair == nullptr) {
std::string str("unsupported attribute: ");
str += attrName;
throw createError(*assignNode.getLeftNode(), str);
}
// check duplication
auto iter = foundAttrSet.find(attrName);
if(iter != foundAttrSet.end()) {
std::string str("duplicated attribute: ");
str += attrName;
throw createError(*assignNode.getLeftNode(), str);
}
// check type attribute
this->checkType(*pair->first, assignNode.getRightNode());
// invoke handler
(pair->second)(*assignNode.getRightNode(), d);
foundAttrSet.insert(attrName);
}
}
void DirectiveInitializer::addHandler(const char *attributeName, DSType &type, AttributeHandler &&handler) {
auto pair = this->handlerMap.insert(std::make_pair(attributeName, std::make_pair(&type, std::move(handler))));
if(!pair.second) {
fatal("found duplicated handler: %s\n", attributeName);
}
}
unsigned int DirectiveInitializer::resolveStatus(const StringNode &node) {
const struct {
const char *name;
unsigned int status;
} statusTable[] = {
#define _E(K) DS_ERROR_KIND_##K
{"success", _E(SUCCESS)},
{"parse_error", _E(PARSE_ERROR)},
{"parse", _E(PARSE_ERROR)},
{"type_error", _E(TYPE_ERROR)},
{"type", _E(TYPE_ERROR)},
{"runtime_error", _E(RUNTIME_ERROR)},
{"runtime", _E(RUNTIME_ERROR)},
{"throw", _E(RUNTIME_ERROR)},
{"assertion_error", _E(ASSERTION_ERROR)},
{"assert", _E(ASSERTION_ERROR)},
{"exit", _E(EXIT)},
#undef _E
};
for(auto &e : statusTable) {
if(strcasecmp(node.getValue().c_str(), e.name) == 0) {
return e.status;
}
}
std::vector<std::string> alters;
for(auto &e : statusTable) {
alters.emplace_back(e.name);
}
std::string message("illegal status, expect for ");
unsigned int count = 0;
for(auto &e : alters) {
if(count++ > 0) {
message += ", ";
}
message += e;
}
throw createError(node, message);
// return 0;
}
const std::pair<DSType *, AttributeHandler> *DirectiveInitializer::lookupHandler(const std::string &name) const {
auto iter = this->handlerMap.find(name);
if(iter == this->handlerMap.end()) {
return nullptr;
}
return &iter->second;
}
void DirectiveInitializer::checkNode(NodeKind kind, const Node &node) {
const char *table[] = {
#define GEN_STR(K) #K,
EACH_NODE_KIND(GEN_STR)
#undef GEN_STR
};
if(!node.is(kind)) {
std::string str = "require: ";
str += table[static_cast<unsigned int>(kind)];
str += "Node, but is: ";
str += table[static_cast<unsigned int>(node.getNodeKind())];
str += "Node";
throw TypeCheckError(node.getToken(), "", str.c_str());
}
}
void DirectiveInitializer::setVarName(const char *name, DSType &type) {
this->symbolTable.newHandle(name, type, FieldAttributes());
}
// #######################
// ## Directive ##
// #######################
Directive::~Directive() {
free(this->out);
free(this->err);
}
static void showError(const char *sourceName, Lexer &lexer, const std::string &line,
Token errorToken, const std::string &message, const char *errorName) {
Token lineToken = {0, static_cast<unsigned int>(line.size())};
std::cerr << sourceName << ":" << lexer.getLineNum() << ": [" << errorName << " error] ";
std::cerr << message << std::endl;
std::cerr << line << std::endl;
std::cerr << lexer.formatLineMarker(lineToken, errorToken) << std::endl;
}
static bool initDirective(const char *fileName, std::istream &input, Directive &directive) {
auto ret = extractDirective(input);
if(ret.first.empty()) {
return true;
}
Lexer lexer(fileName, ret.first.c_str());
lexer.setLineNum(ret.second);
DirectiveParser parser(lexer);
auto node = parser();
if(parser.hasError()) {
auto &e = parser.getError();
showError(fileName, lexer, ret.first, e.getErrorToken(), e.getMessage(), "syntax");
return false;
}
try {
SymbolTable symbolTable;
DirectiveInitializer initializer(fileName, symbolTable);
initializer(*node, directive);
} catch(const TypeCheckError &e) {
showError(fileName, lexer, ret.first, e.getToken(), e.getMessage(), "semantic");
return false;
}
return true;
}
bool Directive::init(const char *fileName, Directive &d) {
std::ifstream input(fileName);
if(!input) {
fatal("cannot open file: %s\n", fileName);
}
return initDirective(fileName, input, d);
}
bool Directive::init(const char *sourceName, const char *src, Directive &d) {
std::istringstream input(src);
return initDirective(sourceName, input, d);
}
} // namespace directive
} // namespace ydsh<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "s60audioplayersession.h"
#include <QtCore/qdebug.h>
#include <QtCore/qvariant.h>
S60AudioPlayerSession::S60AudioPlayerSession(QObject *parent)
: S60MediaPlayerSession(parent)
, m_player(0)
, m_audioEndpoint("Default")
{
#ifdef HAS_AUDIOROUTING
m_audioOutput = 0;
#endif //HAS_AUDIOROUTING
QT_TRAP_THROWING(m_player = CAudioPlayer::NewL(*this, 0, EMdaPriorityPreferenceNone));
m_player->RegisterForAudioLoadingNotification(*this);
}
S60AudioPlayerSession::~S60AudioPlayerSession()
{
#ifdef HAS_AUDIOROUTING
if (m_audioOutput)
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
#endif
m_player->Close();
delete m_player;
}
void S60AudioPlayerSession::doLoadL(const TDesC &path)
{
#ifdef HAS_AUDIOROUTING
// m_audioOutput needs to be reinitialized after MapcInitComplete
if (m_audioOutput)
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
m_audioOutput = NULL;
#endif //HAS_AUDIOROUTING
m_player->OpenFileL(path);
}
qint64 S60AudioPlayerSession::doGetDurationL() const
{
return m_player->Duration().Int64() / qint64(1000);
}
qint64 S60AudioPlayerSession::doGetPositionL() const
{
TTimeIntervalMicroSeconds ms = 0;
m_player->GetPosition(ms);
return ms.Int64() / qint64(1000);
}
bool S60AudioPlayerSession::isVideoAvailable()
{
return false;
}
bool S60AudioPlayerSession::isAudioAvailable()
{
return true; // this is a bit happy scenario, but we do emit error that we can't play
}
void S60AudioPlayerSession::MaloLoadingStarted()
{
buffering();
}
void S60AudioPlayerSession::MaloLoadingComplete()
{
buffered();
}
void S60AudioPlayerSession::doPlay()
{
// For some reason loading progress callback are not called on emulator
// Same is the case with hardware. Will be fixed as part of QTMOBILITY-782.
//#ifdef __WINSCW__
buffering();
//#endif
m_player->Play();
//#ifdef __WINSCW__
buffered();
//#endif
}
void S60AudioPlayerSession::doPauseL()
{
m_player->Pause();
}
void S60AudioPlayerSession::doStop()
{
m_player->Stop();
}
void S60AudioPlayerSession::doClose()
{
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
m_audioOutput = NULL;
}
#endif
m_player->Close();
}
void S60AudioPlayerSession::doSetVolumeL(int volume)
{
m_player->SetVolume(volume * m_player->MaxVolume() / 100);
}
void S60AudioPlayerSession::doSetPositionL(qint64 microSeconds)
{
m_player->SetPosition(TTimeIntervalMicroSeconds(microSeconds));
}
void S60AudioPlayerSession::updateMetaDataEntriesL()
{
metaDataEntries().clear();
int numberOfMetaDataEntries = 0;
//User::LeaveIfError(m_player->GetNumberOfMetaDataEntries(numberOfMetaDataEntries));
m_player->GetNumberOfMetaDataEntries(numberOfMetaDataEntries);
for (int i = 0; i < numberOfMetaDataEntries; i++) {
CMMFMetaDataEntry *entry = NULL;
entry = m_player->GetMetaDataEntryL(i);
metaDataEntries().insert(QString::fromUtf16(entry->Name().Ptr(), entry->Name().Length()), QString::fromUtf16(entry->Value().Ptr(), entry->Value().Length()));
delete entry;
}
emit metaDataChanged();
}
void S60AudioPlayerSession::setPlaybackRate(qreal rate)
{
/*set playback rate is not supported so returning
not supported error.*/
Q_UNUSED(rate);
int err = KErrNotSupported;
setError(err);
}
int S60AudioPlayerSession::doGetBufferStatusL() const
{
int progress = 0;
m_player->GetAudioLoadingProgressL(progress);
return progress;
}
#ifdef S60_DRM_SUPPORTED
void S60AudioPlayerSession::MdapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration)
#else
void S60AudioPlayerSession::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration)
#endif
{
Q_UNUSED(aDuration);
setError(aError);
#ifdef HAS_AUDIOROUTING
TRAPD(err,
m_audioOutput = CAudioOutput::NewL(*m_player);
m_audioOutput->RegisterObserverL(*this);
);
setActiveEndpoint(m_audioEndpoint);
setError(err);
#endif //HAS_AUDIOROUTING
if (KErrNone == aError)
loaded();
}
#ifdef S60_DRM_SUPPORTED
void S60AudioPlayerSession::MdapcPlayComplete(TInt aError)
#else
void S60AudioPlayerSession::MapcPlayComplete(TInt aError)
#endif
{
if (KErrNone == aError)
endOfMedia();
else
setError(aError);
}
void S60AudioPlayerSession::doSetAudioEndpoint(const QString& audioEndpoint)
{
m_audioEndpoint = audioEndpoint;
}
QString S60AudioPlayerSession::activeEndpoint() const
{
QString outputName = QString("Default");
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
CAudioOutput::TAudioOutputPreference output = m_audioOutput->AudioOutput();
outputName = qStringFromTAudioOutputPreference(output);
}
#endif
return outputName;
}
QString S60AudioPlayerSession::defaultEndpoint() const
{
QString outputName = QString("Default");
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
CAudioOutput::TAudioOutputPreference output = m_audioOutput->DefaultAudioOutput();
outputName = qStringFromTAudioOutputPreference(output);
}
#endif
return outputName;
}
void S60AudioPlayerSession::setActiveEndpoint(const QString& name)
{
#ifdef HAS_AUDIOROUTING
CAudioOutput::TAudioOutputPreference output = CAudioOutput::ENoPreference;
if (name == QString("Default"))
output = CAudioOutput::ENoPreference;
else if (name == QString("All"))
output = CAudioOutput::EAll;
else if (name == QString("None"))
output = CAudioOutput::ENoOutput;
else if (name == QString("Earphone"))
output = CAudioOutput::EPrivate;
else if (name == QString("Speaker"))
output = CAudioOutput::EPublic;
if (m_audioOutput) {
TRAPD(err, m_audioOutput->SetAudioOutputL(output));
setError(err);
}
#endif
}
#ifdef HAS_AUDIOROUTING
void S60AudioPlayerSession::DefaultAudioOutputChanged(CAudioOutput& aAudioOutput,
CAudioOutput::TAudioOutputPreference aNewDefault)
{
// Emit already implemented in setActiveEndpoint function
Q_UNUSED(aAudioOutput)
Q_UNUSED(aNewDefault)
}
QString S60AudioPlayerSession::qStringFromTAudioOutputPreference(CAudioOutput::TAudioOutputPreference output) const
{
if (output == CAudioOutput::ENoPreference)
return QString("Default");
else if (output == CAudioOutput::EAll)
return QString("All");
else if (output == CAudioOutput::ENoOutput)
return QString("None");
else if (output == CAudioOutput::EPrivate)
return QString("Earphone");
else if (output == CAudioOutput::EPublic)
return QString("Speaker");
return QString("Default");
}
#endif
bool S60AudioPlayerSession::getIsSeekable() const
{
return ETrue;
}
<commit_msg>Return correct symbian error code for corrupted .amr file<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "s60audioplayersession.h"
#include <QtCore/qdebug.h>
#include <QtCore/qvariant.h>
S60AudioPlayerSession::S60AudioPlayerSession(QObject *parent)
: S60MediaPlayerSession(parent)
, m_player(0)
, m_audioEndpoint("Default")
{
#ifdef HAS_AUDIOROUTING
m_audioOutput = 0;
#endif //HAS_AUDIOROUTING
QT_TRAP_THROWING(m_player = CAudioPlayer::NewL(*this, 0, EMdaPriorityPreferenceNone));
m_player->RegisterForAudioLoadingNotification(*this);
}
S60AudioPlayerSession::~S60AudioPlayerSession()
{
#ifdef HAS_AUDIOROUTING
if (m_audioOutput)
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
#endif
m_player->Close();
delete m_player;
}
void S60AudioPlayerSession::doLoadL(const TDesC &path)
{
#ifdef HAS_AUDIOROUTING
// m_audioOutput needs to be reinitialized after MapcInitComplete
if (m_audioOutput)
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
m_audioOutput = NULL;
#endif //HAS_AUDIOROUTING
m_player->OpenFileL(path);
}
qint64 S60AudioPlayerSession::doGetDurationL() const
{
return m_player->Duration().Int64() / qint64(1000);
}
qint64 S60AudioPlayerSession::doGetPositionL() const
{
TTimeIntervalMicroSeconds ms = 0;
m_player->GetPosition(ms);
return ms.Int64() / qint64(1000);
}
bool S60AudioPlayerSession::isVideoAvailable()
{
return false;
}
bool S60AudioPlayerSession::isAudioAvailable()
{
return true; // this is a bit happy scenario, but we do emit error that we can't play
}
void S60AudioPlayerSession::MaloLoadingStarted()
{
buffering();
}
void S60AudioPlayerSession::MaloLoadingComplete()
{
buffered();
}
void S60AudioPlayerSession::doPlay()
{
// For some reason loading progress callback are not called on emulator
// Same is the case with hardware. Will be fixed as part of QTMOBILITY-782.
//#ifdef __WINSCW__
buffering();
//#endif
m_player->Play();
//#ifdef __WINSCW__
buffered();
//#endif
}
void S60AudioPlayerSession::doPauseL()
{
m_player->Pause();
}
void S60AudioPlayerSession::doStop()
{
m_player->Stop();
}
void S60AudioPlayerSession::doClose()
{
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
m_audioOutput->UnregisterObserver(*this);
delete m_audioOutput;
m_audioOutput = NULL;
}
#endif
m_player->Close();
}
void S60AudioPlayerSession::doSetVolumeL(int volume)
{
m_player->SetVolume(volume * m_player->MaxVolume() / 100);
}
void S60AudioPlayerSession::doSetPositionL(qint64 microSeconds)
{
m_player->SetPosition(TTimeIntervalMicroSeconds(microSeconds));
}
void S60AudioPlayerSession::updateMetaDataEntriesL()
{
metaDataEntries().clear();
int numberOfMetaDataEntries = 0;
//User::LeaveIfError(m_player->GetNumberOfMetaDataEntries(numberOfMetaDataEntries));
m_player->GetNumberOfMetaDataEntries(numberOfMetaDataEntries);
for (int i = 0; i < numberOfMetaDataEntries; i++) {
CMMFMetaDataEntry *entry = NULL;
entry = m_player->GetMetaDataEntryL(i);
metaDataEntries().insert(QString::fromUtf16(entry->Name().Ptr(), entry->Name().Length()), QString::fromUtf16(entry->Value().Ptr(), entry->Value().Length()));
delete entry;
}
emit metaDataChanged();
}
void S60AudioPlayerSession::setPlaybackRate(qreal rate)
{
/*set playback rate is not supported so returning
not supported error.*/
Q_UNUSED(rate);
int err = KErrNotSupported;
setError(err);
}
int S60AudioPlayerSession::doGetBufferStatusL() const
{
int progress = 0;
m_player->GetAudioLoadingProgressL(progress);
return progress;
}
#ifdef S60_DRM_SUPPORTED
void S60AudioPlayerSession::MdapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration)
#else
void S60AudioPlayerSession::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration)
#endif
{
Q_UNUSED(aDuration);
setError(aError);
if (KErrNone != aError)
return;
#ifdef HAS_AUDIOROUTING
TRAPD(err,
m_audioOutput = CAudioOutput::NewL(*m_player);
m_audioOutput->RegisterObserverL(*this);
);
setActiveEndpoint(m_audioEndpoint);
setError(err);
#endif //HAS_AUDIOROUTING
if (KErrNone == aError)
loaded();
}
#ifdef S60_DRM_SUPPORTED
void S60AudioPlayerSession::MdapcPlayComplete(TInt aError)
#else
void S60AudioPlayerSession::MapcPlayComplete(TInt aError)
#endif
{
if (KErrNone == aError)
endOfMedia();
else
setError(aError);
}
void S60AudioPlayerSession::doSetAudioEndpoint(const QString& audioEndpoint)
{
m_audioEndpoint = audioEndpoint;
}
QString S60AudioPlayerSession::activeEndpoint() const
{
QString outputName = QString("Default");
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
CAudioOutput::TAudioOutputPreference output = m_audioOutput->AudioOutput();
outputName = qStringFromTAudioOutputPreference(output);
}
#endif
return outputName;
}
QString S60AudioPlayerSession::defaultEndpoint() const
{
QString outputName = QString("Default");
#ifdef HAS_AUDIOROUTING
if (m_audioOutput) {
CAudioOutput::TAudioOutputPreference output = m_audioOutput->DefaultAudioOutput();
outputName = qStringFromTAudioOutputPreference(output);
}
#endif
return outputName;
}
void S60AudioPlayerSession::setActiveEndpoint(const QString& name)
{
#ifdef HAS_AUDIOROUTING
CAudioOutput::TAudioOutputPreference output = CAudioOutput::ENoPreference;
if (name == QString("Default"))
output = CAudioOutput::ENoPreference;
else if (name == QString("All"))
output = CAudioOutput::EAll;
else if (name == QString("None"))
output = CAudioOutput::ENoOutput;
else if (name == QString("Earphone"))
output = CAudioOutput::EPrivate;
else if (name == QString("Speaker"))
output = CAudioOutput::EPublic;
if (m_audioOutput) {
TRAPD(err, m_audioOutput->SetAudioOutputL(output));
setError(err);
}
#endif
}
#ifdef HAS_AUDIOROUTING
void S60AudioPlayerSession::DefaultAudioOutputChanged(CAudioOutput& aAudioOutput,
CAudioOutput::TAudioOutputPreference aNewDefault)
{
// Emit already implemented in setActiveEndpoint function
Q_UNUSED(aAudioOutput)
Q_UNUSED(aNewDefault)
}
QString S60AudioPlayerSession::qStringFromTAudioOutputPreference(CAudioOutput::TAudioOutputPreference output) const
{
if (output == CAudioOutput::ENoPreference)
return QString("Default");
else if (output == CAudioOutput::EAll)
return QString("All");
else if (output == CAudioOutput::ENoOutput)
return QString("None");
else if (output == CAudioOutput::EPrivate)
return QString("Earphone");
else if (output == CAudioOutput::EPublic)
return QString("Speaker");
return QString("Default");
}
#endif
bool S60AudioPlayerSession::getIsSeekable() const
{
return ETrue;
}
<|endoftext|> |
<commit_before>#include <Document.h>
#include <Selection.h>
#include <Node.h>
void test_parser() {
std::string page("<h1><a>wrong link</a><a class=\"special\"\\>some link</a></h1>");
CDocument doc;
doc.parse(page.c_str());
CSelection c = doc.find("h1 a.special");
CNode node = c.nodeAt(0);
printf("Node: %s\n", node.text().c_str());
std::string content = page.substr(node.startPos(), node.endPos()-node.startPos());
printf("Node: %s\n", content.c_str());
}
void test_html() {
std::string page = "<html><div><span>1\n</span>2\n</div></html>";
CDocument doc;
doc.parse(page.c_str());
CNode pNode = doc.find("div").nodeAt(0);
std::string content = page.substr(pNode.startPos(), pNode.endPos() - pNode.startPos());
printf("Node: #%s#\n", content.c_str());
}
int main() {
test_parser();
test_html();
}
<commit_msg>escape test<commit_after>#include <Document.h>
#include <Selection.h>
#include <Node.h>
void test_parser() {
std::string page("<h1><a>wrong link</a><a class=\"special\"\\>some link</a></h1>");
CDocument doc;
doc.parse(page.c_str());
CSelection c = doc.find("h1 a.special");
CNode node = c.nodeAt(0);
printf("Node: %s\n", node.text().c_str());
std::string content = page.substr(node.startPos(), node.endPos()-node.startPos());
printf("Node: %s\n", content.c_str());
}
void test_html() {
std::string page = "<html><div><span>1\n</span>2\n</div></html>";
CDocument doc;
doc.parse(page.c_str());
CNode pNode = doc.find("div").nodeAt(0);
std::string content = page.substr(pNode.startPos(), pNode.endPos() - pNode.startPos());
printf("Node: #%s#\n", content.c_str());
}
void test_escape() {
std::string page = "<html><div><span id=\"that's\">1\n</span>2\n</div></html>";
CDocument doc;
doc.parse(page.c_str());
CNode pNode = doc.find("span[id=\"that's\"]").nodeAt(0);
std::string content = page.substr(pNode.startPos(), pNode.endPos() - pNode.startPos());
printf("Node: #%s#\n", content.c_str());
}
int main() {
test_parser();
test_html();
test_escape();
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2011 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
extern "C" {
#include "main/macros.h"
#include "program/register_allocate.h"
} /* extern "C" */
#include "brw_vec4.h"
#include "brw_vs.h"
using namespace brw;
namespace brw {
static void
assign(unsigned int *reg_hw_locations, reg *reg)
{
if (reg->file == GRF) {
reg->reg = reg_hw_locations[reg->reg];
}
}
bool
vec4_visitor::reg_allocate_trivial()
{
unsigned int hw_reg_mapping[this->virtual_grf_count];
bool virtual_grf_used[this->virtual_grf_count];
int i;
int next;
/* Calculate which virtual GRFs are actually in use after whatever
* optimization passes have occurred.
*/
for (int i = 0; i < this->virtual_grf_count; i++) {
virtual_grf_used[i] = false;
}
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
if (inst->dst.file == GRF)
virtual_grf_used[inst->dst.reg] = true;
for (int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF)
virtual_grf_used[inst->src[i].reg] = true;
}
}
hw_reg_mapping[0] = this->first_non_payload_grf;
next = hw_reg_mapping[0] + this->virtual_grf_sizes[0];
for (i = 1; i < this->virtual_grf_count; i++) {
if (virtual_grf_used[i]) {
hw_reg_mapping[i] = next;
next += this->virtual_grf_sizes[i];
}
}
prog_data->total_grf = next;
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
assign(hw_reg_mapping, &inst->dst);
assign(hw_reg_mapping, &inst->src[0]);
assign(hw_reg_mapping, &inst->src[1]);
assign(hw_reg_mapping, &inst->src[2]);
}
if (prog_data->total_grf > max_grf) {
fail("Ran out of regs on trivial allocator (%d/%d)\n",
prog_data->total_grf, max_grf);
return false;
}
return true;
}
extern "C" void
brw_vec4_alloc_reg_set(struct brw_context *brw)
{
int base_reg_count = brw->gen >= 7 ? GEN7_MRF_HACK_START : BRW_MAX_GRF;
/* After running split_virtual_grfs(), almost all VGRFs will be of size 1.
* SEND-from-GRF sources cannot be split, so we also need classes for each
* potential message length.
*/
const int class_count = 2;
const int class_sizes[class_count] = {1, 2};
/* Compute the total number of registers across all classes. */
int ra_reg_count = 0;
for (int i = 0; i < class_count; i++) {
ra_reg_count += base_reg_count - (class_sizes[i] - 1);
}
ralloc_free(brw->vec4.ra_reg_to_grf);
brw->vec4.ra_reg_to_grf = ralloc_array(brw, uint8_t, ra_reg_count);
ralloc_free(brw->vec4.regs);
brw->vec4.regs = ra_alloc_reg_set(brw, ra_reg_count);
if (brw->gen >= 6)
ra_set_allocate_round_robin(brw->vec4.regs);
ralloc_free(brw->vec4.classes);
brw->vec4.classes = ralloc_array(brw, int, class_count + 1);
/* Now, add the registers to their classes, and add the conflicts
* between them and the base GRF registers (and also each other).
*/
int reg = 0;
for (int i = 0; i < class_count; i++) {
int class_reg_count = base_reg_count - (class_sizes[i] - 1);
brw->vec4.classes[i] = ra_alloc_reg_class(brw->vec4.regs);
for (int j = 0; j < class_reg_count; j++) {
ra_class_add_reg(brw->vec4.regs, brw->vec4.classes[i], reg);
brw->vec4.ra_reg_to_grf[reg] = j;
for (int base_reg = j;
base_reg < j + class_sizes[i];
base_reg++) {
ra_add_transitive_reg_conflict(brw->vec4.regs, base_reg, reg);
}
reg++;
}
}
assert(reg == ra_reg_count);
ra_set_finalize(brw->vec4.regs, NULL);
}
void
vec4_visitor::setup_payload_interference(struct ra_graph *g,
int first_payload_node,
int reg_node_count)
{
int payload_node_count = this->first_non_payload_grf;
for (int i = 0; i < payload_node_count; i++) {
/* Mark each payload reg node as being allocated to its physical register.
*
* The alternative would be to have per-physical register classes, which
* would just be silly.
*/
ra_set_node_reg(g, first_payload_node + i, i);
/* For now, just mark each payload node as interfering with every other
* node to be allocated.
*/
for (int j = 0; j < reg_node_count; j++) {
ra_add_node_interference(g, first_payload_node + i, j);
}
}
}
bool
vec4_visitor::reg_allocate()
{
unsigned int hw_reg_mapping[virtual_grf_count];
int payload_reg_count = this->first_non_payload_grf;
/* Using the trivial allocator can be useful in debugging undefined
* register access as a result of broken optimization passes.
*/
if (0)
return reg_allocate_trivial();
calculate_live_intervals();
int node_count = virtual_grf_count;
int first_payload_node = node_count;
node_count += payload_reg_count;
struct ra_graph *g =
ra_alloc_interference_graph(brw->vec4.regs, node_count);
for (int i = 0; i < virtual_grf_count; i++) {
int size = this->virtual_grf_sizes[i];
assert(size >= 1 && size <= 2 &&
"Register allocation relies on split_virtual_grfs().");
ra_set_node_class(g, i, brw->vec4.classes[size - 1]);
for (int j = 0; j < i; j++) {
if (virtual_grf_interferes(i, j)) {
ra_add_node_interference(g, i, j);
}
}
}
setup_payload_interference(g, first_payload_node, node_count);
if (!ra_allocate_no_spills(g)) {
/* Failed to allocate registers. Spill a reg, and the caller will
* loop back into here to try again.
*/
int reg = choose_spill_reg(g);
if (this->no_spills) {
fail("Failure to register allocate. Reduce number of live "
"values to avoid this.");
} else if (reg == -1) {
fail("no register to spill\n");
} else {
spill_reg(reg);
}
ralloc_free(g);
return false;
}
/* Get the chosen virtual registers for each node, and map virtual
* regs in the register classes back down to real hardware reg
* numbers.
*/
prog_data->total_grf = payload_reg_count;
for (int i = 0; i < virtual_grf_count; i++) {
int reg = ra_get_node_reg(g, i);
hw_reg_mapping[i] = brw->vec4.ra_reg_to_grf[reg];
prog_data->total_grf = MAX2(prog_data->total_grf,
hw_reg_mapping[i] + virtual_grf_sizes[i]);
}
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *)node;
assign(hw_reg_mapping, &inst->dst);
assign(hw_reg_mapping, &inst->src[0]);
assign(hw_reg_mapping, &inst->src[1]);
assign(hw_reg_mapping, &inst->src[2]);
}
ralloc_free(g);
return true;
}
void
vec4_visitor::evaluate_spill_costs(float *spill_costs, bool *no_spill)
{
float loop_scale = 1.0;
for (int i = 0; i < this->virtual_grf_count; i++) {
spill_costs[i] = 0.0;
no_spill[i] = virtual_grf_sizes[i] != 1;
}
/* Calculate costs for spilling nodes. Call it a cost of 1 per
* spill/unspill we'll have to do, and guess that the insides of
* loops run 10 times.
*/
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
for (unsigned int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF) {
spill_costs[inst->src[i].reg] += loop_scale;
if (inst->src[i].reladdr)
no_spill[inst->src[i].reg] = true;
}
}
if (inst->dst.file == GRF) {
spill_costs[inst->dst.reg] += loop_scale;
if (inst->dst.reladdr)
no_spill[inst->dst.reg] = true;
}
switch (inst->opcode) {
case BRW_OPCODE_DO:
loop_scale *= 10;
break;
case BRW_OPCODE_WHILE:
loop_scale /= 10;
break;
case SHADER_OPCODE_GEN4_SCRATCH_READ:
case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
for (int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF)
no_spill[inst->src[i].reg] = true;
}
if (inst->dst.file == GRF)
no_spill[inst->dst.reg] = true;
break;
default:
break;
}
}
}
int
vec4_visitor::choose_spill_reg(struct ra_graph *g)
{
float spill_costs[this->virtual_grf_count];
bool no_spill[this->virtual_grf_count];
evaluate_spill_costs(spill_costs, no_spill);
for (int i = 0; i < this->virtual_grf_count; i++) {
if (!no_spill[i])
ra_set_node_spill_cost(g, i, spill_costs[i]);
}
return ra_get_best_spill_node(g);
}
void
vec4_visitor::spill_reg(int spill_reg_nr)
{
assert(virtual_grf_sizes[spill_reg_nr] == 1);
unsigned int spill_offset = c->last_scratch++;
/* Generate spill/unspill instructions for the objects being spilled. */
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
for (unsigned int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF && inst->src[i].reg == spill_reg_nr) {
src_reg spill_reg = inst->src[i];
inst->src[i].reg = virtual_grf_alloc(1);
dst_reg temp = dst_reg(inst->src[i]);
/* Only read the necessary channels, to avoid overwriting the rest
* with data that may not have been written to scratch.
*/
temp.writemask = 0;
for (int c = 0; c < 4; c++)
temp.writemask |= (1 << BRW_GET_SWZ(inst->src[i].swizzle, c));
assert(temp.writemask != 0);
emit_scratch_read(inst, temp, spill_reg, spill_offset);
}
}
if (inst->dst.file == GRF && inst->dst.reg == spill_reg_nr) {
emit_scratch_write(inst, spill_offset);
}
}
invalidate_live_intervals();
}
} /* namespace brw */
<commit_msg>i965/vec4: Fix off-by-one register class overallocation.<commit_after>/*
* Copyright © 2011 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
extern "C" {
#include "main/macros.h"
#include "program/register_allocate.h"
} /* extern "C" */
#include "brw_vec4.h"
#include "brw_vs.h"
using namespace brw;
namespace brw {
static void
assign(unsigned int *reg_hw_locations, reg *reg)
{
if (reg->file == GRF) {
reg->reg = reg_hw_locations[reg->reg];
}
}
bool
vec4_visitor::reg_allocate_trivial()
{
unsigned int hw_reg_mapping[this->virtual_grf_count];
bool virtual_grf_used[this->virtual_grf_count];
int i;
int next;
/* Calculate which virtual GRFs are actually in use after whatever
* optimization passes have occurred.
*/
for (int i = 0; i < this->virtual_grf_count; i++) {
virtual_grf_used[i] = false;
}
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
if (inst->dst.file == GRF)
virtual_grf_used[inst->dst.reg] = true;
for (int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF)
virtual_grf_used[inst->src[i].reg] = true;
}
}
hw_reg_mapping[0] = this->first_non_payload_grf;
next = hw_reg_mapping[0] + this->virtual_grf_sizes[0];
for (i = 1; i < this->virtual_grf_count; i++) {
if (virtual_grf_used[i]) {
hw_reg_mapping[i] = next;
next += this->virtual_grf_sizes[i];
}
}
prog_data->total_grf = next;
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
assign(hw_reg_mapping, &inst->dst);
assign(hw_reg_mapping, &inst->src[0]);
assign(hw_reg_mapping, &inst->src[1]);
assign(hw_reg_mapping, &inst->src[2]);
}
if (prog_data->total_grf > max_grf) {
fail("Ran out of regs on trivial allocator (%d/%d)\n",
prog_data->total_grf, max_grf);
return false;
}
return true;
}
extern "C" void
brw_vec4_alloc_reg_set(struct brw_context *brw)
{
int base_reg_count = brw->gen >= 7 ? GEN7_MRF_HACK_START : BRW_MAX_GRF;
/* After running split_virtual_grfs(), almost all VGRFs will be of size 1.
* SEND-from-GRF sources cannot be split, so we also need classes for each
* potential message length.
*/
const int class_count = 2;
const int class_sizes[class_count] = {1, 2};
/* Compute the total number of registers across all classes. */
int ra_reg_count = 0;
for (int i = 0; i < class_count; i++) {
ra_reg_count += base_reg_count - (class_sizes[i] - 1);
}
ralloc_free(brw->vec4.ra_reg_to_grf);
brw->vec4.ra_reg_to_grf = ralloc_array(brw, uint8_t, ra_reg_count);
ralloc_free(brw->vec4.regs);
brw->vec4.regs = ra_alloc_reg_set(brw, ra_reg_count);
if (brw->gen >= 6)
ra_set_allocate_round_robin(brw->vec4.regs);
ralloc_free(brw->vec4.classes);
brw->vec4.classes = ralloc_array(brw, int, class_count);
/* Now, add the registers to their classes, and add the conflicts
* between them and the base GRF registers (and also each other).
*/
int reg = 0;
for (int i = 0; i < class_count; i++) {
int class_reg_count = base_reg_count - (class_sizes[i] - 1);
brw->vec4.classes[i] = ra_alloc_reg_class(brw->vec4.regs);
for (int j = 0; j < class_reg_count; j++) {
ra_class_add_reg(brw->vec4.regs, brw->vec4.classes[i], reg);
brw->vec4.ra_reg_to_grf[reg] = j;
for (int base_reg = j;
base_reg < j + class_sizes[i];
base_reg++) {
ra_add_transitive_reg_conflict(brw->vec4.regs, base_reg, reg);
}
reg++;
}
}
assert(reg == ra_reg_count);
ra_set_finalize(brw->vec4.regs, NULL);
}
void
vec4_visitor::setup_payload_interference(struct ra_graph *g,
int first_payload_node,
int reg_node_count)
{
int payload_node_count = this->first_non_payload_grf;
for (int i = 0; i < payload_node_count; i++) {
/* Mark each payload reg node as being allocated to its physical register.
*
* The alternative would be to have per-physical register classes, which
* would just be silly.
*/
ra_set_node_reg(g, first_payload_node + i, i);
/* For now, just mark each payload node as interfering with every other
* node to be allocated.
*/
for (int j = 0; j < reg_node_count; j++) {
ra_add_node_interference(g, first_payload_node + i, j);
}
}
}
bool
vec4_visitor::reg_allocate()
{
unsigned int hw_reg_mapping[virtual_grf_count];
int payload_reg_count = this->first_non_payload_grf;
/* Using the trivial allocator can be useful in debugging undefined
* register access as a result of broken optimization passes.
*/
if (0)
return reg_allocate_trivial();
calculate_live_intervals();
int node_count = virtual_grf_count;
int first_payload_node = node_count;
node_count += payload_reg_count;
struct ra_graph *g =
ra_alloc_interference_graph(brw->vec4.regs, node_count);
for (int i = 0; i < virtual_grf_count; i++) {
int size = this->virtual_grf_sizes[i];
assert(size >= 1 && size <= 2 &&
"Register allocation relies on split_virtual_grfs().");
ra_set_node_class(g, i, brw->vec4.classes[size - 1]);
for (int j = 0; j < i; j++) {
if (virtual_grf_interferes(i, j)) {
ra_add_node_interference(g, i, j);
}
}
}
setup_payload_interference(g, first_payload_node, node_count);
if (!ra_allocate_no_spills(g)) {
/* Failed to allocate registers. Spill a reg, and the caller will
* loop back into here to try again.
*/
int reg = choose_spill_reg(g);
if (this->no_spills) {
fail("Failure to register allocate. Reduce number of live "
"values to avoid this.");
} else if (reg == -1) {
fail("no register to spill\n");
} else {
spill_reg(reg);
}
ralloc_free(g);
return false;
}
/* Get the chosen virtual registers for each node, and map virtual
* regs in the register classes back down to real hardware reg
* numbers.
*/
prog_data->total_grf = payload_reg_count;
for (int i = 0; i < virtual_grf_count; i++) {
int reg = ra_get_node_reg(g, i);
hw_reg_mapping[i] = brw->vec4.ra_reg_to_grf[reg];
prog_data->total_grf = MAX2(prog_data->total_grf,
hw_reg_mapping[i] + virtual_grf_sizes[i]);
}
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *)node;
assign(hw_reg_mapping, &inst->dst);
assign(hw_reg_mapping, &inst->src[0]);
assign(hw_reg_mapping, &inst->src[1]);
assign(hw_reg_mapping, &inst->src[2]);
}
ralloc_free(g);
return true;
}
void
vec4_visitor::evaluate_spill_costs(float *spill_costs, bool *no_spill)
{
float loop_scale = 1.0;
for (int i = 0; i < this->virtual_grf_count; i++) {
spill_costs[i] = 0.0;
no_spill[i] = virtual_grf_sizes[i] != 1;
}
/* Calculate costs for spilling nodes. Call it a cost of 1 per
* spill/unspill we'll have to do, and guess that the insides of
* loops run 10 times.
*/
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
for (unsigned int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF) {
spill_costs[inst->src[i].reg] += loop_scale;
if (inst->src[i].reladdr)
no_spill[inst->src[i].reg] = true;
}
}
if (inst->dst.file == GRF) {
spill_costs[inst->dst.reg] += loop_scale;
if (inst->dst.reladdr)
no_spill[inst->dst.reg] = true;
}
switch (inst->opcode) {
case BRW_OPCODE_DO:
loop_scale *= 10;
break;
case BRW_OPCODE_WHILE:
loop_scale /= 10;
break;
case SHADER_OPCODE_GEN4_SCRATCH_READ:
case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
for (int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF)
no_spill[inst->src[i].reg] = true;
}
if (inst->dst.file == GRF)
no_spill[inst->dst.reg] = true;
break;
default:
break;
}
}
}
int
vec4_visitor::choose_spill_reg(struct ra_graph *g)
{
float spill_costs[this->virtual_grf_count];
bool no_spill[this->virtual_grf_count];
evaluate_spill_costs(spill_costs, no_spill);
for (int i = 0; i < this->virtual_grf_count; i++) {
if (!no_spill[i])
ra_set_node_spill_cost(g, i, spill_costs[i]);
}
return ra_get_best_spill_node(g);
}
void
vec4_visitor::spill_reg(int spill_reg_nr)
{
assert(virtual_grf_sizes[spill_reg_nr] == 1);
unsigned int spill_offset = c->last_scratch++;
/* Generate spill/unspill instructions for the objects being spilled. */
foreach_list(node, &this->instructions) {
vec4_instruction *inst = (vec4_instruction *) node;
for (unsigned int i = 0; i < 3; i++) {
if (inst->src[i].file == GRF && inst->src[i].reg == spill_reg_nr) {
src_reg spill_reg = inst->src[i];
inst->src[i].reg = virtual_grf_alloc(1);
dst_reg temp = dst_reg(inst->src[i]);
/* Only read the necessary channels, to avoid overwriting the rest
* with data that may not have been written to scratch.
*/
temp.writemask = 0;
for (int c = 0; c < 4; c++)
temp.writemask |= (1 << BRW_GET_SWZ(inst->src[i].swizzle, c));
assert(temp.writemask != 0);
emit_scratch_read(inst, temp, spill_reg, spill_offset);
}
}
if (inst->dst.file == GRF && inst->dst.reg == spill_reg_nr) {
emit_scratch_write(inst, spill_offset);
}
}
invalidate_live_intervals();
}
} /* namespace brw */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaExportComponent.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: obo $ $Date: 2008-02-26 13:37:31 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_METAEXPORTCOMPONENT_HXX
#include "MetaExportComponent.hxx"
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif
#ifndef _COMPHELPER_GENERICPROPERTYSET_HXX_
#include <comphelper/genericpropertyset.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLMETAE_HXX
#include <xmloff/xmlmetae.hxx>
#endif
#ifndef _XMLOFF_PROPERTYSETMERGER_HXX_
#include "PropertySetMerger.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <unotools/docinfohelper.hxx>
using namespace ::com::sun::star;
using namespace ::xmloff::token;
// #110680#
XMLMetaExportComponent::XMLMetaExportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
sal_uInt16 nFlags )
: SvXMLExport( xServiceFactory, MAP_INCH, XML_TEXT, nFlags )
{
}
XMLMetaExportComponent::~XMLMetaExportComponent()
{
}
void SAL_CALL XMLMetaExportComponent::setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
try
{
SvXMLExport::setSourceDocument( xDoc );
}
catch( lang::IllegalArgumentException& )
{
// allow to use document properties service without model access
// this is required for document properties exporter
mxDocProps =
uno::Reference< document::XDocumentProperties >::query( xDoc );
if( !mxDocProps.is() )
throw lang::IllegalArgumentException();
}
}
sal_uInt32 XMLMetaExportComponent::exportDoc( enum XMLTokenEnum )
{
uno::Reference< xml::sax::XDocumentHandler > xDocHandler = GetDocHandler();
if( (getExportFlags() & EXPORT_OASIS) == 0 )
{
uno::Reference< lang::XMultiServiceFactory > xFactory = getServiceFactory();
if( xFactory.is() )
{
try
{
::comphelper::PropertyMapEntry aInfoMap[] =
{
{ "Class", sizeof("Class")-1, 0,
&::getCppuType((::rtl::OUString*)0),
beans::PropertyAttribute::MAYBEVOID, 0},
{ NULL, 0, 0, NULL, 0, 0 }
};
uno::Reference< beans::XPropertySet > xConvPropSet(
::comphelper::GenericPropertySet_CreateInstance(
new ::comphelper::PropertySetInfo( aInfoMap ) ) );
uno::Any aAny;
aAny <<= GetXMLToken( XML_TEXT );
xConvPropSet->setPropertyValue(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Class")), aAny );
uno::Reference< beans::XPropertySet > xPropSet =
getExportInfo().is()
? PropertySetMerger_CreateInstance( getExportInfo(),
xConvPropSet )
: getExportInfo();
uno::Sequence< uno::Any > aArgs( 3 );
aArgs[0] <<= xDocHandler;
aArgs[1] <<= xPropSet;
aArgs[2] <<= GetModel();
// get filter component
xDocHandler = uno::Reference< xml::sax::XDocumentHandler >(
xFactory->createInstanceWithArguments(
::rtl::OUString::createFromAscii("com.sun.star.comp.Oasis2OOoTransformer"),
aArgs),
uno::UNO_QUERY_THROW );
SetDocHandler( xDocHandler );
}
catch( com::sun::star::uno::Exception& )
{
OSL_ENSURE( sal_False, "Cannot instantiate com.sun.star.comp.Oasis2OOoTransformer!\n");
}
}
}
xDocHandler->startDocument();
{
#if 0
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_DC ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_DC ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_META ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_META ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_OFFICE ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_OFFICE ) );
#else
sal_uInt16 nPos = GetNamespaceMap().GetFirstKey();
while( USHRT_MAX != nPos )
{
GetAttrList().AddAttribute( GetNamespaceMap().GetAttrNameByKey( nPos ), GetNamespaceMap().GetNameByKey( nPos ) );
nPos = GetNamespaceMap().GetNextKey( nPos );
}
#endif
AddAttribute( XML_NAMESPACE_OFFICE, XML_VERSION, ::rtl::OUString::createFromAscii( "1.1" ) );
SvXMLElementExport aDocElem( *this, XML_NAMESPACE_OFFICE, XML_DOCUMENT_META,
sal_True, sal_True );
// NB: office:meta is now written by _ExportMeta
_ExportMeta();
}
xDocHandler->endDocument();
return 0;
}
void XMLMetaExportComponent::_ExportMeta()
{
if (mxDocProps.is()) {
::rtl::OUString generator( ::utl::DocInfoHelper::GetGeneratorString() );
// update generator here
mxDocProps->setGenerator(generator);
SvXMLMetaExport * pMeta = new SvXMLMetaExport(*this, mxDocProps);
uno::Reference<xml::sax::XDocumentHandler> xMeta(pMeta);
pMeta->Export();
} else {
SvXMLExport::_ExportMeta();
}
}
// methods without content:
void XMLMetaExportComponent::_ExportAutoStyles() {}
void XMLMetaExportComponent::_ExportMasterStyles() {}
void XMLMetaExportComponent::_ExportContent() {}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLOasisMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META|EXPORT_OASIS);
}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportOOO_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportOOO_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportOOo" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportOOO_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.18.28); FILE MERGED 2008/04/01 16:09:48 thb 1.18.28.3: #i85898# Stripping all external header guards 2008/04/01 13:04:54 thb 1.18.28.2: #i85898# Stripping all external header guards 2008/03/31 16:28:14 rt 1.18.28.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaExportComponent.cxx,v $
* $Revision: 1.19 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "MetaExportComponent.hxx"
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP
#include <com/sun/star/uno/Exception.hpp>
#endif
#include <com/sun/star/beans/PropertyAttribute.hpp>
// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif
#include <comphelper/genericpropertyset.hxx>
#include <rtl/ustrbuf.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlmetae.hxx>
#include "PropertySetMerger.hxx"
#include <tools/debug.hxx>
#include <unotools/docinfohelper.hxx>
using namespace ::com::sun::star;
using namespace ::xmloff::token;
// #110680#
XMLMetaExportComponent::XMLMetaExportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
sal_uInt16 nFlags )
: SvXMLExport( xServiceFactory, MAP_INCH, XML_TEXT, nFlags )
{
}
XMLMetaExportComponent::~XMLMetaExportComponent()
{
}
void SAL_CALL XMLMetaExportComponent::setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
try
{
SvXMLExport::setSourceDocument( xDoc );
}
catch( lang::IllegalArgumentException& )
{
// allow to use document properties service without model access
// this is required for document properties exporter
mxDocProps =
uno::Reference< document::XDocumentProperties >::query( xDoc );
if( !mxDocProps.is() )
throw lang::IllegalArgumentException();
}
}
sal_uInt32 XMLMetaExportComponent::exportDoc( enum XMLTokenEnum )
{
uno::Reference< xml::sax::XDocumentHandler > xDocHandler = GetDocHandler();
if( (getExportFlags() & EXPORT_OASIS) == 0 )
{
uno::Reference< lang::XMultiServiceFactory > xFactory = getServiceFactory();
if( xFactory.is() )
{
try
{
::comphelper::PropertyMapEntry aInfoMap[] =
{
{ "Class", sizeof("Class")-1, 0,
&::getCppuType((::rtl::OUString*)0),
beans::PropertyAttribute::MAYBEVOID, 0},
{ NULL, 0, 0, NULL, 0, 0 }
};
uno::Reference< beans::XPropertySet > xConvPropSet(
::comphelper::GenericPropertySet_CreateInstance(
new ::comphelper::PropertySetInfo( aInfoMap ) ) );
uno::Any aAny;
aAny <<= GetXMLToken( XML_TEXT );
xConvPropSet->setPropertyValue(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Class")), aAny );
uno::Reference< beans::XPropertySet > xPropSet =
getExportInfo().is()
? PropertySetMerger_CreateInstance( getExportInfo(),
xConvPropSet )
: getExportInfo();
uno::Sequence< uno::Any > aArgs( 3 );
aArgs[0] <<= xDocHandler;
aArgs[1] <<= xPropSet;
aArgs[2] <<= GetModel();
// get filter component
xDocHandler = uno::Reference< xml::sax::XDocumentHandler >(
xFactory->createInstanceWithArguments(
::rtl::OUString::createFromAscii("com.sun.star.comp.Oasis2OOoTransformer"),
aArgs),
uno::UNO_QUERY_THROW );
SetDocHandler( xDocHandler );
}
catch( com::sun::star::uno::Exception& )
{
OSL_ENSURE( sal_False, "Cannot instantiate com.sun.star.comp.Oasis2OOoTransformer!\n");
}
}
}
xDocHandler->startDocument();
{
#if 0
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_DC ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_DC ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_META ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_META ) );
GetAttrList().AddAttribute(
GetNamespaceMap().GetAttrNameByKey( XML_NAMESPACE_OFFICE ),
GetNamespaceMap().GetNameByKey( XML_NAMESPACE_OFFICE ) );
#else
sal_uInt16 nPos = GetNamespaceMap().GetFirstKey();
while( USHRT_MAX != nPos )
{
GetAttrList().AddAttribute( GetNamespaceMap().GetAttrNameByKey( nPos ), GetNamespaceMap().GetNameByKey( nPos ) );
nPos = GetNamespaceMap().GetNextKey( nPos );
}
#endif
AddAttribute( XML_NAMESPACE_OFFICE, XML_VERSION, ::rtl::OUString::createFromAscii( "1.1" ) );
SvXMLElementExport aDocElem( *this, XML_NAMESPACE_OFFICE, XML_DOCUMENT_META,
sal_True, sal_True );
// NB: office:meta is now written by _ExportMeta
_ExportMeta();
}
xDocHandler->endDocument();
return 0;
}
void XMLMetaExportComponent::_ExportMeta()
{
if (mxDocProps.is()) {
::rtl::OUString generator( ::utl::DocInfoHelper::GetGeneratorString() );
// update generator here
mxDocProps->setGenerator(generator);
SvXMLMetaExport * pMeta = new SvXMLMetaExport(*this, mxDocProps);
uno::Reference<xml::sax::XDocumentHandler> xMeta(pMeta);
pMeta->Export();
} else {
SvXMLExport::_ExportMeta();
}
}
// methods without content:
void XMLMetaExportComponent::_ExportAutoStyles() {}
void XMLMetaExportComponent::_ExportMasterStyles() {}
void XMLMetaExportComponent::_ExportContent() {}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLOasisMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META|EXPORT_OASIS);
}
uno::Sequence< rtl::OUString > SAL_CALL XMLMetaExportOOO_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.XMLMetaExporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaExportOOO_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaExportOOo" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaExportOOO_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaExportComponent;
return (cppu::OWeakObject*)new XMLMetaExportComponent(rSMgr, EXPORT_META);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xsec_nss.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: mt $ $Date: 2004-07-12 13:15:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <sal/config.h>
#include <stdio.h>
#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <cppuhelper/factory.hxx>
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#include "seinitializer_nssimpl.hxx"
#include "xmlsignature_nssimpl.hxx"
#include "xmlencryption_nssimpl.hxx"
#include "xmlsecuritycontext_nssimpl.hxx"
#include "securityenvironment_nssimpl.hxx"
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
extern "C"
{
sal_Bool SAL_CALL nss_component_writeInfo( void* pServiceManager , void* pRegistryKey )
{
sal_Bool result = sal_False;
sal_Int32 i ;
OUString sKeyName ;
Reference< XRegistryKey > xNewKey ;
Sequence< OUString > seqServices ;
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;
if( xKey.is() ) {
// try {
// XMLSignature_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLSignature_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLSignature_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// XMLEncryption_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLEncryption_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLEncryption_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// XMLSecurityContext_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLSecurityContext_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLSecurityContext_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// SecurityEnvironment_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += SecurityEnvironment_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = SecurityEnvironment_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// SEInitializer_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += SEInitializer_NssImpl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = SEInitializer_NssImpl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
return sal_True;
//} catch( InvalidRegistryException & ) {
// //we should not ignore exceptions
// return sal_False ;
//}
}
return result;
}
void* SAL_CALL nss_component_getFactory( const sal_Char* pImplName , void* pServiceManager , void* pRegistryKey )
{
void* pRet = 0;
Reference< XSingleServiceFactory > xFactory ;
if( pImplName != NULL && pServiceManager != NULL ) {
if( XMLSignature_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLSignature_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( XMLSecurityContext_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLSecurityContext_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( SecurityEnvironment_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = SecurityEnvironment_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( XMLEncryption_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLEncryption_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( SEInitializer_NssImpl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = Reference< XSingleServiceFactory >( createSingleFactory(
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
OUString::createFromAscii( pImplName ),
SEInitializer_NssImpl_createInstance, SEInitializer_NssImpl_getSupportedServiceNames() ) );
}
}
if( xFactory.is() ) {
xFactory->acquire() ;
pRet = xFactory.get() ;
}
return pRet ;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.86); FILE MERGED 2005/09/05 17:02:05 rt 1.1.1.1.86.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xsec_nss.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 17:36:50 $
*
* 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 <sal/config.h>
#include <stdio.h>
#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <cppuhelper/factory.hxx>
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#include "seinitializer_nssimpl.hxx"
#include "xmlsignature_nssimpl.hxx"
#include "xmlencryption_nssimpl.hxx"
#include "xmlsecuritycontext_nssimpl.hxx"
#include "securityenvironment_nssimpl.hxx"
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
extern "C"
{
sal_Bool SAL_CALL nss_component_writeInfo( void* pServiceManager , void* pRegistryKey )
{
sal_Bool result = sal_False;
sal_Int32 i ;
OUString sKeyName ;
Reference< XRegistryKey > xNewKey ;
Sequence< OUString > seqServices ;
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;
if( xKey.is() ) {
// try {
// XMLSignature_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLSignature_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLSignature_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// XMLEncryption_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLEncryption_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLEncryption_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// XMLSecurityContext_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += XMLSecurityContext_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = XMLSecurityContext_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// SecurityEnvironment_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += SecurityEnvironment_NssImpl::impl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = SecurityEnvironment_NssImpl::impl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
// SEInitializer_NssImpl
sKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ;
sKeyName += SEInitializer_NssImpl_getImplementationName() ;
sKeyName += OUString::createFromAscii( "/UNO/SERVICES" ) ;
xNewKey = xKey->createKey( sKeyName ) ;
if( xNewKey.is() ) {
seqServices = SEInitializer_NssImpl_getSupportedServiceNames() ;
for( i = seqServices.getLength() ; i -- ; )
xNewKey->createKey( seqServices.getConstArray()[i] ) ;
}
return sal_True;
//} catch( InvalidRegistryException & ) {
// //we should not ignore exceptions
// return sal_False ;
//}
}
return result;
}
void* SAL_CALL nss_component_getFactory( const sal_Char* pImplName , void* pServiceManager , void* pRegistryKey )
{
void* pRet = 0;
Reference< XSingleServiceFactory > xFactory ;
if( pImplName != NULL && pServiceManager != NULL ) {
if( XMLSignature_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLSignature_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( XMLSecurityContext_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLSecurityContext_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( SecurityEnvironment_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = SecurityEnvironment_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( XMLEncryption_NssImpl::impl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = XMLEncryption_NssImpl::impl_createFactory( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
} else if( SEInitializer_NssImpl_getImplementationName().equals( OUString::createFromAscii( pImplName ) ) ) {
xFactory = Reference< XSingleServiceFactory >( createSingleFactory(
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
OUString::createFromAscii( pImplName ),
SEInitializer_NssImpl_createInstance, SEInitializer_NssImpl_getSupportedServiceNames() ) );
}
}
if( xFactory.is() ) {
xFactory->acquire() ;
pRet = xFactory.get() ;
}
return pRet ;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <vector>
#include "hash.hpp"
#include "slice.hpp"
namespace {
auto readVI (Slice& data) {
const auto i = data.read<uint8_t>();
if (i < 253) return static_cast<uint64_t>(i);
if (i < 254) return static_cast<uint64_t>(data.read<uint16_t>());
if (i < 255) return static_cast<uint64_t>(data.read<uint32_t>());
return data.read<uint64_t>();
}
}
struct Transaction {
struct Input {
Slice data;
Slice hash;
uint32_t vout;
Slice script;
uint32_t sequence;
Input () {}
Input (
Slice data,
Slice hash,
uint32_t vout,
Slice script,
uint32_t sequence
) :
data(data),
hash(hash),
vout(vout),
script(script),
sequence(sequence) {}
};
struct Output {
Slice data;
Slice script;
uint64_t value;
Output () {}
Output (
Slice data,
Slice script,
uint64_t value
) :
data(data),
script(script),
value(value) {}
};
Slice data;
int32_t version;
std::vector<Input> inputs;
std::vector<Output> outputs;
uint32_t locktime;
Transaction () {}
Transaction (
Slice data,
int32_t version,
std::vector<Input> inputs,
std::vector<Output> outputs,
uint32_t locktime
) :
data(data),
version(version),
inputs(inputs),
outputs(outputs),
locktime(locktime) {}
};
struct TransactionRange {
private:
uint64_t n;
Slice data;
Transaction current;
bool lazy = true;
auto readTransaction () {
const auto source = this->data;
const auto version = this->data.read<int32_t>();
const auto nInputs = readVI(this->data);
std::vector<Transaction::Input> inputs;
for (size_t i = 0; i < nInputs; ++i) {
const auto idataSource = this->data;
const auto hash = this->data.readN(32);
const auto vout = this->data.read<uint32_t>();
const auto scriptLen = readVI(this->data);
const auto script = this->data.readN(scriptLen);
const auto sequence = this->data.read<uint32_t>();
const auto idata = Slice(idataSource.begin(), this->data.begin());
inputs.emplace_back(
Transaction::Input(idata, hash, vout, script, sequence)
);
}
const auto nOutputs = readVI(this->data);
std::vector<Transaction::Output> outputs;
for (size_t i = 0; i < nOutputs; ++i) {
const auto odataSource = this->data;
const auto value = this->data.read<uint64_t>();
const auto scriptLen = readVI(this->data);
const auto script = this->data.readN(scriptLen);
const auto odata = Slice(odataSource.begin(), this->data.begin());
outputs.emplace_back(Transaction::Output(odata, script, value));
}
const auto locktime = this->data.read<uint32_t>();
const auto _data = source.take(source.length() - this->data.length());
this->current = Transaction(_data, version, std::move(inputs), std::move(outputs), locktime);
this->lazy = false;
}
public:
TransactionRange(size_t n, Slice data) : n(n), data(data) {}
auto empty () const { return this->n == 0; }
auto length () const { return this->n; }
auto front () {
if (this->lazy) {
this->readTransaction();
}
return this->current;
}
// TODO: verify
// void popFront () {
// this->lazy = true;
// this->n--;
// }
void popFront () {
this->n--;
if (this->n > 0) {
this->readTransaction();
}
}
};
struct Block {
Slice header, data;
Block(Slice header) : header(header) {
assert(header.length() == 80);
}
Block(Slice header, Slice data) : header(header), data(data) {
assert(header.length() == 80);
}
static void calculateTarget (uint8_t* dest, uint32_t bits) {
const auto exponent = ((bits & 0xff000000) >> 24) - 3;
const auto mantissa = bits & 0x007fffff;
const auto i = static_cast<size_t>(31 - exponent);
if (i > 31) return;
dest[i] = static_cast<uint8_t>(mantissa & 0xff);
dest[i - 1] = static_cast<uint8_t>(mantissa >> 8);
dest[i - 2] = static_cast<uint8_t>(mantissa >> 16);
dest[i - 3] = static_cast<uint8_t>(mantissa >> 24);
}
auto bits () const {
return this->header.peek<uint32_t>(72);
}
auto previousBlockHash () const {
return this->header.drop(4).take(32);
}
auto transactions () const {
auto _data = this->data;
const auto n = readVI(_data);
return TransactionRange(n, _data);
}
auto utc () const {
return this->header.peek<uint32_t>(68);
}
auto verify () const {
uint8_t hash[32];
uint8_t target[32] = {};
hash256(hash, this->header);
std::reverse(hash, hash + 32);
const auto bits = this->header.peek<uint32_t>(72);
Block::calculateTarget(target, bits);
return memcmp(hash, target, 32) <= 0;
}
};
<commit_msg>block: less random indentation<commit_after>#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <vector>
#include "hash.hpp"
#include "slice.hpp"
namespace {
auto readVI (Slice& data) {
const auto i = data.read<uint8_t>();
if (i < 253) return static_cast<uint64_t>(i);
if (i < 254) return static_cast<uint64_t>(data.read<uint16_t>());
if (i < 255) return static_cast<uint64_t>(data.read<uint32_t>());
return data.read<uint64_t>();
}
}
struct Transaction {
struct Input {
Slice data;
Slice hash;
uint32_t vout;
Slice script;
uint32_t sequence;
Input () {}
Input (
Slice data,
Slice hash,
uint32_t vout,
Slice script,
uint32_t sequence
) :
data(data),
hash(hash),
vout(vout),
script(script),
sequence(sequence) {}
};
struct Output {
Slice data;
Slice script;
uint64_t value;
Output () {}
Output (
Slice data,
Slice script,
uint64_t value
) :
data(data),
script(script),
value(value) {}
};
Slice data;
int32_t version;
std::vector<Input> inputs;
std::vector<Output> outputs;
uint32_t locktime;
Transaction () {}
Transaction (
Slice data,
int32_t version,
std::vector<Input> inputs,
std::vector<Output> outputs,
uint32_t locktime
) :
data(data),
version(version),
inputs(inputs),
outputs(outputs),
locktime(locktime) {}
};
struct TransactionRange {
private:
uint64_t n;
Slice data;
Transaction current;
bool lazy = true;
auto readTransaction () {
const auto source = this->data;
const auto version = this->data.read<int32_t>();
const auto nInputs = readVI(this->data);
std::vector<Transaction::Input> inputs;
for (size_t i = 0; i < nInputs; ++i) {
const auto idataSource = this->data;
const auto hash = this->data.readN(32);
const auto vout = this->data.read<uint32_t>();
const auto scriptLen = readVI(this->data);
const auto script = this->data.readN(scriptLen);
const auto sequence = this->data.read<uint32_t>();
const auto idata = Slice(idataSource.begin(), this->data.begin());
inputs.emplace_back(
Transaction::Input(idata, hash, vout, script, sequence)
);
}
const auto nOutputs = readVI(this->data);
std::vector<Transaction::Output> outputs;
for (size_t i = 0; i < nOutputs; ++i) {
const auto odataSource = this->data;
const auto value = this->data.read<uint64_t>();
const auto scriptLen = readVI(this->data);
const auto script = this->data.readN(scriptLen);
const auto odata = Slice(odataSource.begin(), this->data.begin());
outputs.emplace_back(Transaction::Output(odata, script, value));
}
const auto locktime = this->data.read<uint32_t>();
const auto _data = source.take(source.length() - this->data.length());
this->current = Transaction(_data, version, std::move(inputs), std::move(outputs), locktime);
this->lazy = false;
}
public:
TransactionRange(size_t n, Slice data) : n(n), data(data) {}
auto empty () const { return this->n == 0; }
auto length () const { return this->n; }
auto front () {
if (this->lazy) this->readTransaction();
return this->current;
}
// TODO: verify
// void popFront () {
// this->lazy = true;
// this->n--;
// }
void popFront () {
this->n--;
if (this->n > 0) this->readTransaction();
}
};
struct Block {
Slice header, data;
Block(Slice header) : header(header) {
assert(header.length() == 80);
}
Block(Slice header, Slice data) : header(header), data(data) {
assert(header.length() == 80);
}
static void calculateTarget (uint8_t* dest, uint32_t bits) {
const auto exponent = ((bits & 0xff000000) >> 24) - 3;
const auto mantissa = bits & 0x007fffff;
const auto i = static_cast<size_t>(31 - exponent);
if (i > 31) return;
dest[i] = static_cast<uint8_t>(mantissa & 0xff);
dest[i - 1] = static_cast<uint8_t>(mantissa >> 8);
dest[i - 2] = static_cast<uint8_t>(mantissa >> 16);
dest[i - 3] = static_cast<uint8_t>(mantissa >> 24);
}
auto bits () const {
return this->header.peek<uint32_t>(72);
}
auto previousBlockHash () const {
return this->header.drop(4).take(32);
}
auto transactions () const {
auto _data = this->data;
const auto n = readVI(_data);
return TransactionRange(n, _data);
}
auto utc () const {
return this->header.peek<uint32_t>(68);
}
auto verify () const {
uint8_t hash[32];
uint8_t target[32] = {};
hash256(hash, this->header);
std::reverse(hash, hash + 32);
const auto bits = this->header.peek<uint32_t>(72);
Block::calculateTarget(target, bits);
return memcmp(hash, target, 32) <= 0;
}
};
<|endoftext|> |
<commit_before>#include "SlitherlinkField.h"
#include "SlitherlinkProblem.h"
namespace Penciloid
{
SlitherlinkField::SlitherlinkField()
{
height = 0;
width = 0;
hints = nullptr;
}
SlitherlinkField::~SlitherlinkField()
{
if (hints) delete[] hints;
}
void SlitherlinkField::Init(int height_t, int width_t)
{
height = height_t;
width = width_t;
if (hints) delete[] hints;
hints = new int[height * width];
for (int i = 0; i < height * width; ++i) hints[i] = HINT_NONE;
auxiliary.Init(this);
grid.SetAuxiliarySolver(&auxiliary);
grid.Init(height, width);
}
void SlitherlinkField::Init(SlitherlinkProblem &prob)
{
Init(prob.GetHeight(), prob.GetWidth());
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int hint = prob.GetHint(i, j);
if (hint != HINT_NONE) SetHint(i, j, hint);
}
}
}
int SlitherlinkField::SetHint(int y, int x, int hint)
{
int id = CellId(y, x);
if (hints[id] != HINT_NONE) {
if (hints[id] != hint) {
return grid.UpdateStatus(SolverStatus::INCONSISTENT);
}
return grid.UpdateStatus(0);
}
hints[id] = hint;
CheckTheorem(y * 2 + 1, x * 2 + 1);
CheckCell(y * 2 + 1, x * 2 + 1);
return grid.GetStatus();
}
void SlitherlinkField::CheckTheorem(int y, int x)
{
if (GetHint(y / 2, x / 2) == 3) {
// vertically or horizontally adjacent 3
for (int i = 0; i < 4; ++i) {
int dy = GridConstant::GRID_DY[i], dx = GridConstant::GRID_DX[i];
if (GetHintSafe(y / 2 + dy, x / 2 + dx) == 3) {
grid.DetermineLine(y - dy, x - dx);
grid.DetermineLine(y + dy, x + dx);
grid.DetermineBlank(y + dy + 2 * dx, x + dx + 2 * dy);
grid.DetermineBlank(y + dy - 2 * dx, x + dx - 2 * dy);
grid.DetermineLine(y + 3 * dy, x + 3 * dx);
}
int dy2 = GridConstant::GRID_DY[(i + 1) % 4], dx2 = GridConstant::GRID_DX[(i + 1) % 4];
if (GetHintSafe(y / 2 + dy + dy2, x / 2 + dx + dx2) == 3) {
grid.DetermineLine(y - dy, x - dx);
grid.DetermineLine(y - dy2, x - dx2);
grid.DetermineLine(y + dy * 3 + dy2 * 2, x + dx * 3 + dx2 * 2);
grid.DetermineLine(y + dy2 * 3 + dy * 2, x + dx2 * 3 + dx * 2);
}
}
}
}
void SlitherlinkField::CheckCell(int y, int x)
{
int id = CellId(y / 2, x / 2);
if (hints[id] == HINT_NONE) return;
// TODO: faster checker is required
static const int bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3};
int segment_line = 15, segment_blank = 15;
for (int i = 0; i < 15; ++i) {
if (hints[id] != bits[i]) continue;
// checking the consistency with the current status
for (int j = 0; j < 4; ++j) {
int style = grid.GetSegmentStyle(y + GridConstant::GRID_DY[j], x + GridConstant::GRID_DX[j]);
if ((style == LOOP_LINE && ((i & (1 << j)) == 0)) || (style == LOOP_BLANK && ((i & (1 << j)) != 0))) goto fail;
}
for (int j = 0; j < 4; ++j) {
int dy1 = GridConstant::GRID_DY[j], dx1 = GridConstant::GRID_DX[j];
int dy2 = GridConstant::GRID_DY[(j + 1) & 3], dx2 = GridConstant::GRID_DX[(j + 1) & 3];
int num_lines = 0, num_blanks = 0;
if (i & (1 << j)) ++num_lines;
else ++num_blanks;
if (i & (1 << ((j + 1) & 3))) ++num_lines;
else ++num_blanks;
int style1 = grid.GetSegmentStyleSafe(y + dy1 + dy2 * 2, x + dx1 + dx2 * 2);
if (style1 == LOOP_LINE) ++num_lines;
else if (style1 == LOOP_BLANK) ++num_blanks;
int style2 = grid.GetSegmentStyleSafe(y + dy2 + dy1 * 2, x + dx2 + dx1 * 2);
if (style2 == LOOP_LINE) ++num_lines;
else if (style2 == LOOP_BLANK) ++num_blanks;
if (num_lines >= 3 || (num_lines == 1 && num_blanks == 3)) goto fail;
}
segment_line &= i;
segment_blank &= ~i;
fail:
continue;
}
if (segment_line & segment_blank) {
grid.UpdateStatus(SolverStatus::INCONSISTENT);
return;
}
for (int i = 0; i < 4; ++i) {
if (segment_line & (1 << i)) {
grid.DetermineLine(y + GridConstant::GRID_DY[i], x + GridConstant::GRID_DX[i]);
}
if (segment_blank & (1 << i)) {
grid.DetermineBlank(y + GridConstant::GRID_DY[i], x + GridConstant::GRID_DX[i]);
}
}
}
void SlitherlinkField::Debug()
{
for (int i = 0; i <= height * 2; ++i) {
for (int j = 0; j <= width * 2; ++j) {
if (i % 2 == 0 && j % 2 == 0) {
fprintf(stderr, "+");
} else if (i % 2 == 0 && j % 2 == 1) {
int style = GetSegmentStyle(i, j);
if (style == LOOP_UNDECIDED) fprintf(stderr, " ");
if (style == LOOP_LINE) fprintf(stderr, "---");
if (style == LOOP_BLANK) fprintf(stderr, " X ");
} else if (i % 2 == 1 && j % 2 == 0) {
int style = GetSegmentStyle(i, j);
if (style == LOOP_UNDECIDED) fprintf(stderr, " ");
if (style == LOOP_LINE) fprintf(stderr, "|");
if (style == LOOP_BLANK) fprintf(stderr, "X");
} else if (i % 2 == 1 && j % 2 == 1) {
if (GetHint(i / 2, j / 2) == HINT_NONE) fprintf(stderr, " ");
else fprintf(stderr, " %d ", GetHint(i / 2, j / 2));
}
}
fprintf(stderr, "\n");
}
}
}<commit_msg>Add a rule around 3 in SlitherlinkField<commit_after>#include "SlitherlinkField.h"
#include "SlitherlinkProblem.h"
namespace Penciloid
{
SlitherlinkField::SlitherlinkField()
{
height = 0;
width = 0;
hints = nullptr;
}
SlitherlinkField::~SlitherlinkField()
{
if (hints) delete[] hints;
}
void SlitherlinkField::Init(int height_t, int width_t)
{
height = height_t;
width = width_t;
if (hints) delete[] hints;
hints = new int[height * width];
for (int i = 0; i < height * width; ++i) hints[i] = HINT_NONE;
auxiliary.Init(this);
grid.SetAuxiliarySolver(&auxiliary);
grid.Init(height, width);
}
void SlitherlinkField::Init(SlitherlinkProblem &prob)
{
Init(prob.GetHeight(), prob.GetWidth());
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int hint = prob.GetHint(i, j);
if (hint != HINT_NONE) SetHint(i, j, hint);
}
}
}
int SlitherlinkField::SetHint(int y, int x, int hint)
{
int id = CellId(y, x);
if (hints[id] != HINT_NONE) {
if (hints[id] != hint) {
return grid.UpdateStatus(SolverStatus::INCONSISTENT);
}
return grid.UpdateStatus(0);
}
hints[id] = hint;
CheckTheorem(y * 2 + 1, x * 2 + 1);
CheckCell(y * 2 + 1, x * 2 + 1);
return grid.GetStatus();
}
void SlitherlinkField::CheckTheorem(int y, int x)
{
if (GetHint(y / 2, x / 2) == 3) {
// vertically or horizontally adjacent 3
for (int i = 0; i < 4; ++i) {
int dy = GridConstant::GRID_DY[i], dx = GridConstant::GRID_DX[i];
if (GetHintSafe(y / 2 + dy, x / 2 + dx) == 3) {
grid.DetermineLine(y - dy, x - dx);
grid.DetermineLine(y + dy, x + dx);
grid.DetermineBlank(y + dy + 2 * dx, x + dx + 2 * dy);
grid.DetermineBlank(y + dy - 2 * dx, x + dx - 2 * dy);
grid.DetermineLine(y + 3 * dy, x + 3 * dx);
}
int dy2 = GridConstant::GRID_DY[(i + 1) % 4], dx2 = GridConstant::GRID_DX[(i + 1) % 4];
if (GetHintSafe(y / 2 + dy + dy2, x / 2 + dx + dx2) == 3) {
grid.DetermineLine(y - dy, x - dx);
grid.DetermineLine(y - dy2, x - dx2);
grid.DetermineLine(y + dy * 3 + dy2 * 2, x + dx * 3 + dx2 * 2);
grid.DetermineLine(y + dy2 * 3 + dy * 2, x + dx2 * 3 + dx * 2);
}
}
}
}
void SlitherlinkField::CheckCell(int y, int x)
{
int id = CellId(y / 2, x / 2);
if (hints[id] == HINT_NONE) return;
// TODO: faster checker is required
static const int bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3};
int segment_line = 15, segment_blank = 15;
for (int i = 0; i < 15; ++i) {
if (hints[id] != bits[i]) continue;
// checking the consistency with the current status
for (int j = 0; j < 4; ++j) {
int style = grid.GetSegmentStyle(y + GridConstant::GRID_DY[j], x + GridConstant::GRID_DX[j]);
if ((style == LOOP_LINE && ((i & (1 << j)) == 0)) || (style == LOOP_BLANK && ((i & (1 << j)) != 0))) goto fail;
}
for (int j = 0; j < 4; ++j) {
int dy1 = GridConstant::GRID_DY[j], dx1 = GridConstant::GRID_DX[j];
int dy2 = GridConstant::GRID_DY[(j + 1) & 3], dx2 = GridConstant::GRID_DX[(j + 1) & 3];
int num_lines = 0, num_blanks = 0;
if (i & (1 << j)) ++num_lines;
else ++num_blanks;
if (i & (1 << ((j + 1) & 3))) ++num_lines;
else ++num_blanks;
int style1 = grid.GetSegmentStyleSafe(y + dy1 + dy2 * 2, x + dx1 + dx2 * 2);
if (style1 == LOOP_LINE) ++num_lines;
else if (style1 == LOOP_BLANK) ++num_blanks;
int style2 = grid.GetSegmentStyleSafe(y + dy2 + dy1 * 2, x + dx2 + dx1 * 2);
if (style2 == LOOP_LINE) ++num_lines;
else if (style2 == LOOP_BLANK) ++num_blanks;
if (num_lines >= 3 || (num_lines == 1 && num_blanks == 3)) goto fail;
}
segment_line &= i;
segment_blank &= ~i;
fail:
continue;
}
if (segment_line & segment_blank) {
grid.UpdateStatus(SolverStatus::INCONSISTENT);
return;
}
for (int i = 0; i < 4; ++i) {
if (segment_line & (1 << i)) {
grid.DetermineLine(y + GridConstant::GRID_DY[i], x + GridConstant::GRID_DX[i]);
}
if (segment_blank & (1 << i)) {
grid.DetermineBlank(y + GridConstant::GRID_DY[i], x + GridConstant::GRID_DX[i]);
}
}
if (hints[id] == 3) {
for (int i = 0; i < 4; ++i) {
int dy1 = GridConstant::GRID_DY[i], dx1 = GridConstant::GRID_DX[i];
int dy2 = GridConstant::GRID_DY[(i + 1) & 3], dx2 = GridConstant::GRID_DX[(i + 1) & 3];
if (grid.GetSegmentStyleSafe(y + dy1 + dy2 * 2, x + dx1 + dx2 * 2) == LOOP_LINE) {
grid.DetermineBlank(y + dy2 + dy1 * 2, x + dx2 + dx1 * 2);
}
if (grid.GetSegmentStyleSafe(y + dy2 + dy1 * 2, x + dx2 + dx1 * 2) == LOOP_LINE) {
grid.DetermineBlank(y + dy1 + dy2 * 2, x + dx1 + dx2 * 2);
}
}
}
}
void SlitherlinkField::Debug()
{
for (int i = 0; i <= height * 2; ++i) {
for (int j = 0; j <= width * 2; ++j) {
if (i % 2 == 0 && j % 2 == 0) {
fprintf(stderr, "+");
} else if (i % 2 == 0 && j % 2 == 1) {
int style = GetSegmentStyle(i, j);
if (style == LOOP_UNDECIDED) fprintf(stderr, " ");
if (style == LOOP_LINE) fprintf(stderr, "---");
if (style == LOOP_BLANK) fprintf(stderr, " X ");
} else if (i % 2 == 1 && j % 2 == 0) {
int style = GetSegmentStyle(i, j);
if (style == LOOP_UNDECIDED) fprintf(stderr, " ");
if (style == LOOP_LINE) fprintf(stderr, "|");
if (style == LOOP_BLANK) fprintf(stderr, "X");
} else if (i % 2 == 1 && j % 2 == 1) {
if (GetHint(i / 2, j / 2) == HINT_NONE) fprintf(stderr, " ");
else fprintf(stderr, " %d ", GetHint(i / 2, j / 2));
}
}
fprintf(stderr, "\n");
}
}
}<|endoftext|> |
<commit_before>/**
* @file cossb.hpp
* @brief COSSB Header
* @author Byunghun Hwang<[email protected]>
* @date 2015. 6. 9
* @details
*/
#ifndef _COSSB_HEADER_HPP_
#define _COSSB_HEADER_HPP_
#if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__)
#include "version.hpp"
#include "errorcode.hpp"
#include "manager.hpp"
#include "broker.hpp"
#include "base/configreader.hpp"
#include "instance.hpp"
#include "logger.hpp"
#include "util/pid.h"
#endif
#endif
<commit_msg>rename to utilloader<commit_after>/**
* @file cossb.hpp
* @brief COSSB Header
* @author Byunghun Hwang<[email protected]>
* @date 2015. 6. 9
* @details
*/
#ifndef _COSSB_HEADER_HPP_
#define _COSSB_HEADER_HPP_
#if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__)
#include "version.hpp"
#include "errorcode.hpp"
#include "manager.hpp"
#include "broker.hpp"
#include "base/configreader.hpp"
#include "instance.hpp"
#include "logger.hpp"
#include "util/pid.h"
#include "util/utilloader.hpp"
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_CALLBACKS_STREAM_LOGGER_HPP
#define STAN_CALLBACKS_STREAM_LOGGER_HPP
#include <stan/callbacks/logger.hpp>
#include <ostream>
#include <string>
#include <sstream>
namespace stan {
namespace callbacks {
/**
* <code>stream_logger</code> is an implementation of
* <code>logger</code> that writes messages to separate
* std::stringstream outputs.
*/
class stream_logger : public logger {
private:
std::ostream& debug_;
std::ostream& info_;
std::ostream& warn_;
std::ostream& error_;
std::ostream& fatal_;
public:
/**
* Constructs a <code>stream_logger</code> with an output
* stream for each log level.
*
* @param[in] debug stream to output debug messages
*/
stream_logger(std::ostream& debug,
std::ostream& info,
std::ostream& warn,
std::ostream& error,
std::ostream& fatal)
: debug_(debug), info_(info), warn_(warn), error_(error),
fatal_(fatal) { }
void debug(const std::string& message) {
debug_ << message << std::endl;
}
void debug(const std::stringstream& message) {
debug_ << message.str() << std::endl;
}
void info(const std::string& message) {
info_ << message << std::endl;
}
void info(const std::stringstream& message) {
info_ << message.str() << std::endl;
}
void warn(const std::string& message) {
warn_ << message << std::endl;
}
void warn(const std::stringstream& message) {
warn_ << message.str() << std::endl;
}
void error(const std::string& message) {
error_ << message << std::endl;
}
void error(const std::stringstream& message) {
error_ << message.str() << std::endl;
}
void fatal(const std::string& message) {
fatal_ << message << std::endl;
}
void fatal(const std::stringstream& message) {
fatal_ << message.str() << std::endl;
}
};
}
}
#endif
<commit_msg>Doxygen<commit_after>#ifndef STAN_CALLBACKS_STREAM_LOGGER_HPP
#define STAN_CALLBACKS_STREAM_LOGGER_HPP
#include <stan/callbacks/logger.hpp>
#include <ostream>
#include <string>
#include <sstream>
namespace stan {
namespace callbacks {
/**
* <code>stream_logger</code> is an implementation of
* <code>logger</code> that writes messages to separate
* std::stringstream outputs.
*/
class stream_logger : public logger {
private:
std::ostream& debug_;
std::ostream& info_;
std::ostream& warn_;
std::ostream& error_;
std::ostream& fatal_;
public:
/**
* Constructs a <code>stream_logger</code> with an output
* stream for each log level.
*
* @param[in,out] debug stream to output debug messages
* @param[in,out] info stream to output info messages
* @param[in,out] warn stream to output warn messages
* @param[in,out] error stream to output error messages
* @param[in,out] fatal stream to output fatal messages
*/
stream_logger(std::ostream& debug,
std::ostream& info,
std::ostream& warn,
std::ostream& error,
std::ostream& fatal)
: debug_(debug), info_(info), warn_(warn), error_(error),
fatal_(fatal) { }
void debug(const std::string& message) {
debug_ << message << std::endl;
}
void debug(const std::stringstream& message) {
debug_ << message.str() << std::endl;
}
void info(const std::string& message) {
info_ << message << std::endl;
}
void info(const std::stringstream& message) {
info_ << message.str() << std::endl;
}
void warn(const std::string& message) {
warn_ << message << std::endl;
}
void warn(const std::stringstream& message) {
warn_ << message.str() << std::endl;
}
void error(const std::string& message) {
error_ << message << std::endl;
}
void error(const std::stringstream& message) {
error_ << message.str() << std::endl;
}
void fatal(const std::string& message) {
fatal_ << message << std::endl;
}
void fatal(const std::stringstream& message) {
fatal_ << message.str() << std::endl;
}
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef STAN__COMMON__INITIALIZE_STATE_HPP
#define STAN__COMMON__INITIALIZE_STATE_HPP
#include <string>
#include <iostream>
#include <math.h>
#include <stan/math/matrix/Eigen.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/model/util.hpp>
#include <stan/gm/error_codes.hpp>
#include <stan/common/context_factory.hpp>
#include <stan/common/write_error_msg.hpp>
namespace stan {
namespace common {
/**
* Sets initial state to zero
*
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] output output stream for messages
*/
template <class Model>
bool initialize_state_zero(Eigen::VectorXd& cont_params,
Model& model,
std::ostream* output) {
cont_params.setZero();
double init_log_prob;
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, output);
} catch (const std::exception& e) {
if (output)
*output << "Rejecting initialization at zero because of gradient failure."
<< std::endl << e.what() << std::endl;
return false;
}
if (!boost::math::isfinite(init_log_prob)) {
if (output)
*output << "Rejecting initialization at zero because of vanishing density."
<< std::endl;
return false;
}
for (int i = 0; i < init_grad.size(); ++i) {
if (!boost::math::isfinite(init_grad[i])) {
if (output)
*output << "Rejecting initialization at zero because of divergent gradient."
<< std::endl;
return false;
}
}
return true;
}
/**
* Initializes state to random uniform values within range.
*
* @param[in] R valid range of the initialization; must be
* greater than or equal to 0.
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
*/
template <class Model, class RNG>
bool initialize_state_random(const double R,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output) {
int num_init_tries = -1;
boost::random::uniform_real_distribution<double>
init_range_distribution(-R, R);
boost::variate_generator<RNG&, boost::random::uniform_real_distribution<double> >
init_rng(base_rng, init_range_distribution);
cont_params.setZero();
// Random initializations until log_prob is finite
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
static int MAX_INIT_TRIES = 100;
for (num_init_tries = 1; num_init_tries <= MAX_INIT_TRIES; ++num_init_tries) {
for (int i = 0; i < cont_params.size(); ++i)
cont_params(i) = init_rng();
double init_log_prob;
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, &std::cout);
} catch (const std::exception& e) {
write_error_msg(output, e);
if (output)
*output << "Rejecting proposed initial value with zero density." << std::endl;
init_log_prob = -std::numeric_limits<double>::infinity();
}
if (!boost::math::isfinite(init_log_prob))
continue;
for (int i = 0; i < init_grad.size(); ++i)
if (!boost::math::isfinite(init_grad(i)))
continue;
break;
}
if (num_init_tries > MAX_INIT_TRIES) {
if (output)
*output << std::endl << std::endl
<< "Initialization between (" << -R << ", " << R << ") failed after "
<< MAX_INIT_TRIES << " attempts. " << std::endl
<< " Try specifying initial values,"
<< " reducing ranges of constrained values,"
<< " or reparameterizing the model."
<< std::endl;
return false;
}
return true;
}
/**
* Creates the initial state using the source parameter
*
* @param[in] source a string that the context_factory can
* interpret and provide a valid var_context
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
* @param[in,out] context_factory an instantiated factory that implements
* the concept of a context_factory. This has
* one method that takes a string.
*/
template <class ContextFactory, class Model, class RNG>
bool initialize_state_source(const std::string source,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output,
ContextFactory& context_factory) {
stan::io::var_context* context = context_factory(source);
model.transform_inits(*context, cont_params);
delete context;
double init_log_prob;
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, &std::cout);
} catch (const std::exception& e) {
if (output)
*output << "Rejecting user-specified initialization because of gradient failure."
<< std::endl << e.what() << std::endl;
return false;
}
if (!boost::math::isfinite(init_log_prob)) {
if (output)
*output << "Rejecting user-specified initialization because of vanishing density."
<< std::endl;
return false;
}
for (int i = 0; i < init_grad.size(); ++i) {
if (!boost::math::isfinite(init_grad[i])) {
if (output)
*output << "Rejecting user-specified initialization because of divergent gradient."
<< std::endl;
return false;
}
}
return true;
}
/**
* Creates the initial state.
*
* @param[in] init init can either be "0", a number as a string,
* or a filename.
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
* @param[in,out] context_factory an instantiated factory that implements
* the concept of a context_factory. This has
* one method that takes a string.
*/
template <class ContextFactory, class Model, class RNG>
bool initialize_state(const std::string init,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output,
ContextFactory& context_factory) {
try {
double R = std::fabs(boost::lexical_cast<double>(init));
if (R == 0) {
initialize_state_zero(cont_params, model, output);
} else {
initialize_state_random(R, cont_params, model,
base_rng, output);
}
} catch(...) {
stan::io::var_context* context = context_factory(init);
model.transform_inits(*context, cont_params);
delete context;
double init_log_prob;
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, &std::cout);
} catch (const std::exception& e) {
if (output)
*output << "Rejecting user-specified initialization because of gradient failure."
<< std::endl << e.what() << std::endl;
return false;
}
if (!boost::math::isfinite(init_log_prob)) {
if (output)
*output << "Rejecting user-specified initialization because of vanishing density."
<< std::endl;
return false;
}
for (int i = 0; i < init_grad.size(); ++i) {
if (!boost::math::isfinite(init_grad[i])) {
if (output)
*output << "Rejecting user-specified initialization because of divergent gradient."
<< std::endl;
return false;
}
}
}
return true;
}
} // common
} // stan
#endif
<commit_msg>updated initialize_state to use initialize_state_source<commit_after>#ifndef STAN__COMMON__INITIALIZE_STATE_HPP
#define STAN__COMMON__INITIALIZE_STATE_HPP
#include <string>
#include <iostream>
#include <math.h>
#include <stan/math/matrix/Eigen.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/model/util.hpp>
#include <stan/gm/error_codes.hpp>
#include <stan/common/context_factory.hpp>
#include <stan/common/write_error_msg.hpp>
namespace stan {
namespace common {
/**
* Sets initial state to zero
*
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] output output stream for messages
*/
template <class Model>
bool initialize_state_zero(Eigen::VectorXd& cont_params,
Model& model,
std::ostream* output) {
cont_params.setZero();
double init_log_prob;
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, output);
} catch (const std::exception& e) {
if (output)
*output << "Rejecting initialization at zero because of gradient failure."
<< std::endl << e.what() << std::endl;
return false;
}
if (!boost::math::isfinite(init_log_prob)) {
if (output)
*output << "Rejecting initialization at zero because of vanishing density."
<< std::endl;
return false;
}
for (int i = 0; i < init_grad.size(); ++i) {
if (!boost::math::isfinite(init_grad[i])) {
if (output)
*output << "Rejecting initialization at zero because of divergent gradient."
<< std::endl;
return false;
}
}
return true;
}
/**
* Initializes state to random uniform values within range.
*
* @param[in] R valid range of the initialization; must be
* greater than or equal to 0.
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
*/
template <class Model, class RNG>
bool initialize_state_random(const double R,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output) {
int num_init_tries = -1;
boost::random::uniform_real_distribution<double>
init_range_distribution(-R, R);
boost::variate_generator<RNG&, boost::random::uniform_real_distribution<double> >
init_rng(base_rng, init_range_distribution);
cont_params.setZero();
// Random initializations until log_prob is finite
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
static int MAX_INIT_TRIES = 100;
for (num_init_tries = 1; num_init_tries <= MAX_INIT_TRIES; ++num_init_tries) {
for (int i = 0; i < cont_params.size(); ++i)
cont_params(i) = init_rng();
double init_log_prob;
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, &std::cout);
} catch (const std::exception& e) {
write_error_msg(output, e);
if (output)
*output << "Rejecting proposed initial value with zero density." << std::endl;
init_log_prob = -std::numeric_limits<double>::infinity();
}
if (!boost::math::isfinite(init_log_prob))
continue;
for (int i = 0; i < init_grad.size(); ++i)
if (!boost::math::isfinite(init_grad(i)))
continue;
break;
}
if (num_init_tries > MAX_INIT_TRIES) {
if (output)
*output << std::endl << std::endl
<< "Initialization between (" << -R << ", " << R << ") failed after "
<< MAX_INIT_TRIES << " attempts. " << std::endl
<< " Try specifying initial values,"
<< " reducing ranges of constrained values,"
<< " or reparameterizing the model."
<< std::endl;
return false;
}
return true;
}
/**
* Creates the initial state using the source parameter
*
* @param[in] source a string that the context_factory can
* interpret and provide a valid var_context
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
* @param[in,out] context_factory an instantiated factory that implements
* the concept of a context_factory. This has
* one method that takes a string.
*/
template <class ContextFactory, class Model, class RNG>
bool initialize_state_source(const std::string source,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output,
ContextFactory& context_factory) {
stan::io::var_context* context = context_factory(source);
model.transform_inits(*context, cont_params);
delete context;
double init_log_prob;
Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());
try {
stan::model::gradient(model, cont_params, init_log_prob, init_grad, &std::cout);
} catch (const std::exception& e) {
if (output)
*output << "Rejecting user-specified initialization because of gradient failure."
<< std::endl << e.what() << std::endl;
return false;
}
if (!boost::math::isfinite(init_log_prob)) {
if (output)
*output << "Rejecting user-specified initialization because of vanishing density."
<< std::endl;
return false;
}
for (int i = 0; i < init_grad.size(); ++i) {
if (!boost::math::isfinite(init_grad[i])) {
if (output)
*output << "Rejecting user-specified initialization because of divergent gradient."
<< std::endl;
return false;
}
}
return true;
}
/**
* Creates the initial state.
*
* @param[in] init init can either be "0", a number as a string,
* or a filename.
* @param[out] cont_params the initialized state. This should be the
* right size and set to 0.
* @param[in,out] model the model. Side effects on model? I'm not
* quite sure
* @param[in,out] base_rng the random number generator. State may change.
* @param[in,out] output output stream for messages
* @param[in,out] context_factory an instantiated factory that implements
* the concept of a context_factory. This has
* one method that takes a string.
*/
template <class ContextFactory, class Model, class RNG>
bool initialize_state(const std::string init,
Eigen::VectorXd& cont_params,
Model& model,
RNG& base_rng,
std::ostream* output,
ContextFactory& context_factory) {
try {
double R = std::fabs(boost::lexical_cast<double>(init));
if (R == 0) {
return initialize_state_zero(cont_params, model, output);
} else {
return initialize_state_random(R, cont_params, model,
base_rng, output);
}
} catch(...) {
return initialize_state_source(init, cont_params, model,
base_rng, output,
context_factory);
}
return false;
}
} // common
} // stan
#endif
<|endoftext|> |
<commit_before><commit_msg>Adding some helpful comments<commit_after><|endoftext|> |
<commit_before>///
/// @file imath.hpp
/// @brief Integer math functions
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef IMATH_HPP
#define IMATH_HPP
#include <isqrt.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>
namespace {
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename A, typename B>
inline A ceil_div(A a, B b)
{
assert(b > 0);
return (A) ((a + b - 1) / b);
}
template <typename T>
inline T number_of_bits(T)
{
return (T) (sizeof(T) * 8);
}
template <typename T>
inline T next_power_of_2(T x)
{
if (x == 0)
return 1;
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
template <typename T>
inline T prev_power_of_2(T x)
{
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline int ilog(T x)
{
return (int) std::log((double) x);
}
template <typename T>
inline T ipow(T x, int n)
{
T r = 1;
for (int i = 0; i < n; i++)
r *= x;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
if (N == 0)
return 0;
T r = (T) std::pow((double) x, 1.0 / N);
// fix root too large
for (; r > 0; r--)
{
if (ipow(r, N - 1) <= x / r)
break;
}
// fix root too small
while (ipow(r + 1, N - 1) <= x / (r + 1))
r += 1;
return r;
}
/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
assert(primes.size() < 2 || primes[1] == 2);
return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}
} // namespace
#endif
<commit_msg>Improve number_of_bits()<commit_after>///
/// @file imath.hpp
/// @brief Integer math functions
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef IMATH_HPP
#define IMATH_HPP
#include <isqrt.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <vector>
namespace {
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename A, typename B>
inline A ceil_div(A a, B b)
{
assert(b > 0);
return (A) ((a + b - 1) / b);
}
template <typename T>
inline T number_of_bits(T)
{
static_assert(sizeof(uint64_t) * CHAR_BIT == 64, "number_of_bits() is broken");
return (T) (sizeof(T) * CHAR_BIT);
}
template <typename T>
inline T next_power_of_2(T x)
{
if (x == 0)
return 1;
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
template <typename T>
inline T prev_power_of_2(T x)
{
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline int ilog(T x)
{
return (int) std::log((double) x);
}
template <typename T>
inline T ipow(T x, int n)
{
T r = 1;
for (int i = 0; i < n; i++)
r *= x;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
if (N == 0)
return 0;
T r = (T) std::pow((double) x, 1.0 / N);
// fix root too large
for (; r > 0; r--)
{
if (ipow(r, N - 1) <= x / r)
break;
}
// fix root too small
while (ipow(r + 1, N - 1) <= x / (r + 1))
r += 1;
return r;
}
/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
assert(primes.size() < 2 || primes[1] == 2);
return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}
} // namespace
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: layer.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef LAYER_HPP
#define LAYER_HPP
#include <vector>
#include "feature.hpp"
#include "datasource.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/serialization/serialization.hpp>
namespace mapnik
{
class MAPNIK_DECL Layer
{
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
ar & boost::serialization::make_nvp("name",name_)
& boost::serialization::make_nvp("params",params_)
& boost::serialization::make_nvp("min_zoom",minZoom_)
& boost::serialization::make_nvp("max_zoom",maxZoom_)
& boost::serialization::make_nvp("active",active_)
& boost::serialization::make_nvp("selectable",selectable_)
& boost::serialization::make_nvp("styles",styles_)
;
}
parameters params_;
std::string name_;
double minZoom_;
double maxZoom_;
bool active_;
bool selectable_;
mutable datasource_p ds_;
std::vector<std::string> styles_;
std::string selection_style_;
mutable std::vector<boost::shared_ptr<Feature> > selection_;
public:
Layer();
explicit Layer(const parameters& params);
Layer(Layer const& l);
Layer& operator=(Layer const& l);
bool operator==(Layer const& other) const;
parameters const& params() const;
const std::string& name() const;
void add_style(std::string const& stylename);
std::vector<std::string> const& styles() const;
void selection_style(const std::string& name);
const std::string& selection_style() const;
void setMinZoom(double minZoom);
void setMaxZoom(double maxZoom);
double getMinZoom() const;
double getMaxZoom() const;
void setActive(bool active);
bool isActive() const;
void setSelectable(bool selectable);
bool isSelectable() const;
bool isVisible(double scale) const;
void add_to_selection(boost::shared_ptr<Feature>& feature) const;
std::vector<boost::shared_ptr<Feature> >& selection() const;
void clear_selection() const;
void set_datasource(datasource_p const& ds);
datasource_p const& datasource() const;
Envelope<double> envelope() const;
virtual ~Layer();
private:
void swap(const Layer& other);
};
}
BOOST_CLASS_IMPLEMENTATION(std::vector<std::string>, boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(std::vector<std::string>, boost::serialization::track_never)
BOOST_CLASS_IMPLEMENTATION(mapnik::Layer, boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(mapnik::Layer, boost::serialization::track_never)
#endif //LAYER_HPP
<commit_msg>added set_name method<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: layer.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef LAYER_HPP
#define LAYER_HPP
#include <vector>
#include "feature.hpp"
#include "datasource.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/serialization/serialization.hpp>
namespace mapnik
{
class MAPNIK_DECL Layer
{
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
ar & boost::serialization::make_nvp("name",name_)
& boost::serialization::make_nvp("params",params_)
& boost::serialization::make_nvp("min_zoom",minZoom_)
& boost::serialization::make_nvp("max_zoom",maxZoom_)
& boost::serialization::make_nvp("active",active_)
& boost::serialization::make_nvp("selectable",selectable_)
& boost::serialization::make_nvp("styles",styles_)
;
}
parameters params_;
std::string name_;
double minZoom_;
double maxZoom_;
bool active_;
bool selectable_;
std::vector<std::string> styles_;
std::string selection_style_;
mutable datasource_p ds_;
mutable std::vector<boost::shared_ptr<Feature> > selection_;
public:
Layer();
explicit Layer(const parameters& params);
Layer(Layer const& l);
Layer& operator=(Layer const& l);
bool operator==(Layer const& other) const;
parameters const& params() const;
void set_name(std::string const& name);
const std::string& name() const;
void add_style(std::string const& stylename);
std::vector<std::string> const& styles() const;
void selection_style(const std::string& name);
const std::string& selection_style() const;
void setMinZoom(double minZoom);
void setMaxZoom(double maxZoom);
double getMinZoom() const;
double getMaxZoom() const;
void setActive(bool active);
bool isActive() const;
void setSelectable(bool selectable);
bool isSelectable() const;
bool isVisible(double scale) const;
void add_to_selection(boost::shared_ptr<Feature>& feature) const;
std::vector<boost::shared_ptr<Feature> >& selection() const;
void clear_selection() const;
void set_datasource(datasource_p const& ds);
datasource_p const& datasource() const;
Envelope<double> envelope() const;
virtual ~Layer();
private:
void swap(const Layer& other);
};
}
BOOST_CLASS_IMPLEMENTATION(std::vector<std::string>, boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(std::vector<std::string>, boost::serialization::track_never)
BOOST_CLASS_IMPLEMENTATION(mapnik::Layer, boost::serialization::object_serializable)
BOOST_CLASS_TRACKING(mapnik::Layer, boost::serialization::track_never)
#endif //LAYER_HPP
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsystemdeviceinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)
#ifdef QT_SIMULATOR
QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }
#endif
// device
/*!
\class QSystemDeviceInfo
\ingroup systeminfo
\inmodule QtSystemInfo
\brief The QSystemDeviceInfo class provides access to device information from the system.
\fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
Constructs a QSystemDeviceInfo with the given \a parent.
*/
/*!
\fn void QSystemDeviceInfo::batteryLevelChanged(int level)
This signal is emitted when battery level has changed.
\a level is the new level.
*/
/*!
\fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)
This signal is emitted when battery status has changed.
\a status is the new status.
*/
/*!
\fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)
This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.
\a state is the new power state.
*/
/*!
\fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)
This signal is emitted whenever the users active profile changes, specified by \a profile.
*/
/*!
\enum QSystemDeviceInfo::BatteryStatus
This enum describes the status of the main battery.
\value NoBatteryLevel Battery level undetermined.
\value BatteryCritical Battery level is critical 3% or less.
\value BatteryVeryLow Battery level is very low, 10% or less.
\value BatteryLow Battery level is low 40% or less.
\value BatteryNormal Battery level is above 40%.
*/
/*!
\enum QSystemDeviceInfo::PowerState
This enum describes the power state:
\value UnknownPower Power error.
\value BatteryPower On battery power.
\value WallPower On wall power.
\value WallPowerChargingBattery On wall power and charging main battery.
*/
/*!
\enum QSystemDeviceInfo::Profile
This enum describes the current operating profile of the device or computer.
\value UnknownProfile Profile unknown or error.
\value SilentProfile Silent profile.
\value NormalProfile Normal profile.
\value LoudProfile Loud profile.
\value VibProfile Vibrate profile.
\value OfflineProfile Offline profile.
\value PowersaveProfile Powersave profile.
\value CustomProfile Custom profile.
*/
/*!
\enum QSystemDeviceInfo::SimStatus
This enum describes the status is the sim card or cards.
\value SimNotAvailable SIM is not available on this device.
\value SingleSimAvailable One SIM card is available on this.
\value DualSimAvailable Two SIM cards are available on this device.
\value SimLocked Device has SIM lock enabled.
*/
/*!
\enum QSystemDeviceInfo::InputMethod
This enum describes the device method of user input.
\value Keys Device has key/buttons.
\value Keypad Device has keypad (1,2,3, etc).
\value Keyboard Device has qwerty keyboard.
\value SingleTouch Device has single touch screen.
\value MultiTouch Device has muti touch screen.
\value Mouse Device has a mouse.
*/
/*!
\fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)
This signal is emitted whenever bluetooth state changes, specified by \a on.
*/
QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
: QObject(parent), d(deviceInfoPrivate())
{
qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus");
qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState");
qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus");
qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile");
qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags");
connect(d,SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
connect(d,SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
/*!
Destroys the QSystemDeviceInfo object.
*/
QSystemDeviceInfo::~QSystemDeviceInfo()
{
}
/*!
\internal
This function is called when the client connects to signals.
\sa connectNotify()
*/
void QSystemDeviceInfo::connectNotify(const char *signal)
{
Q_UNUSED(signal);
}
/*!
\internal
This function is called when the client disconnects from the signals.
\sa connectNotify()
*/
void QSystemDeviceInfo::disconnectNotify(const char *signal)
{
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryLevelChanged(int))))) {
disconnect(d,SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {
disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
bluetoothStateChanged(bool))))) {
disconnect(d,SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentProfileChanged(QSystemDeviceInfo::Profile))))) {
disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
powerStateChanged(QSystemDeviceInfo::PowerState))))) {
disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
}
/*!
\property QSystemDeviceInfo::inputMethodType
\brief The supported inputmethods.
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()
{
return deviceInfoPrivate()->inputMethodType();
}
/*!
\property QSystemDeviceInfo::imei
\brief The IMEI.
Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imei()
{
return deviceInfoPrivate()->imei();
}
/*!
\property QSystemDeviceInfo::imsi
\brief The IMSI.
Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imsi()
{
return deviceInfoPrivate()->imsi();
}
/*!
\property QSystemDeviceInfo::manufacturer
\brief The manufacture's name.
Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
of the motherboard.
*/
QString QSystemDeviceInfo::manufacturer()
{
return deviceInfoPrivate()->manufacturer();
}
/*!
\property QSystemDeviceInfo::model
\brief The model name.
Returns the model information of the device. In the case of desktops where no
model information is present, the CPU architect, such as i686, and machine type, such as Server,
Desktop or Laptop.
*/
QString QSystemDeviceInfo::model()
{
return deviceInfoPrivate()->model();
}
/*!
\property QSystemDeviceInfo::productName
\brief The product name.
Returns the product name of the device. In the case where no product information is available,
*/
QString QSystemDeviceInfo::productName()
{
return deviceInfoPrivate()->productName();
}
/*!
\property QSystemDeviceInfo::batteryLevel
\brief The battery level.
Returns the battery charge level as percentage 1 - 100 scale.
*/
int QSystemDeviceInfo::batteryLevel() const
{
return deviceInfoPrivate()->batteryLevel();
}
/*!
\property QSystemDeviceInfo::batteryStatus
\brief The battery status.
Returns the battery charge status.
*/
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()
{
int level = batteryLevel();
if(level < 4) {
return QSystemDeviceInfo::BatteryCritical;
} else if(level < 11) {
return QSystemDeviceInfo::BatteryVeryLow;
} else if(level < 41) {
return QSystemDeviceInfo::BatteryLow;
} else if(level > 40) {
return QSystemDeviceInfo::BatteryNormal;
}
return QSystemDeviceInfo::NoBatteryLevel;
}
/*!
\property QSystemDeviceInfo::simStatus
\brief the status of the sim card.
Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()
{
return deviceInfoPrivate()->simStatus();
}
/*!
\property QSystemDeviceInfo::isDeviceLocked
\brief Device lock.
Returns true if the device is locked, otherwise false.
*/
bool QSystemDeviceInfo::isDeviceLocked()
{
return deviceInfoPrivate()->isDeviceLocked();
}
/*!
\property QSystemDeviceInfo::currentProfile
\brief the device profile
Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()
{
return deviceInfoPrivate()->currentProfile();
}
/*!
\property QSystemDeviceInfo::currentPowerState
\brief the power state.
Gets the current QSystemDeviceInfo::currentPowerState state.
*/
QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()
{
return deviceInfoPrivate()->currentPowerState();
}
/*!
\property QSystemDeviceInfo::currentBluetoothPowerState
\brief bluetooth power state.
Gets the current bluetooth power state.
*/
bool QSystemDeviceInfo::currentBluetoothPowerState()
{
return deviceInfoPrivate()->currentBluetoothPowerState();
}
#include "moc_qsystemdeviceinfo.cpp"
QTM_END_NAMESPACE
<commit_msg>move connect stuff back to connectNotify<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsystemdeviceinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)
#ifdef QT_SIMULATOR
QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }
#endif
// device
/*!
\class QSystemDeviceInfo
\ingroup systeminfo
\inmodule QtSystemInfo
\brief The QSystemDeviceInfo class provides access to device information from the system.
\fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
Constructs a QSystemDeviceInfo with the given \a parent.
*/
/*!
\fn void QSystemDeviceInfo::batteryLevelChanged(int level)
This signal is emitted when battery level has changed.
\a level is the new level.
*/
/*!
\fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)
This signal is emitted when battery status has changed.
\a status is the new status.
*/
/*!
\fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)
This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.
\a state is the new power state.
*/
/*!
\fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)
This signal is emitted whenever the users active profile changes, specified by \a profile.
*/
/*!
\enum QSystemDeviceInfo::BatteryStatus
This enum describes the status of the main battery.
\value NoBatteryLevel Battery level undetermined.
\value BatteryCritical Battery level is critical 3% or less.
\value BatteryVeryLow Battery level is very low, 10% or less.
\value BatteryLow Battery level is low 40% or less.
\value BatteryNormal Battery level is above 40%.
*/
/*!
\enum QSystemDeviceInfo::PowerState
This enum describes the power state:
\value UnknownPower Power error.
\value BatteryPower On battery power.
\value WallPower On wall power.
\value WallPowerChargingBattery On wall power and charging main battery.
*/
/*!
\enum QSystemDeviceInfo::Profile
This enum describes the current operating profile of the device or computer.
\value UnknownProfile Profile unknown or error.
\value SilentProfile Silent profile.
\value NormalProfile Normal profile.
\value LoudProfile Loud profile.
\value VibProfile Vibrate profile.
\value OfflineProfile Offline profile.
\value PowersaveProfile Powersave profile.
\value CustomProfile Custom profile.
*/
/*!
\enum QSystemDeviceInfo::SimStatus
This enum describes the status is the sim card or cards.
\value SimNotAvailable SIM is not available on this device.
\value SingleSimAvailable One SIM card is available on this.
\value DualSimAvailable Two SIM cards are available on this device.
\value SimLocked Device has SIM lock enabled.
*/
/*!
\enum QSystemDeviceInfo::InputMethod
This enum describes the device method of user input.
\value Keys Device has key/buttons.
\value Keypad Device has keypad (1,2,3, etc).
\value Keyboard Device has qwerty keyboard.
\value SingleTouch Device has single touch screen.
\value MultiTouch Device has muti touch screen.
\value Mouse Device has a mouse.
*/
/*!
\fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)
This signal is emitted whenever bluetooth state changes, specified by \a on.
*/
QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
: QObject(parent), d(deviceInfoPrivate())
{
qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus");
qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState");
qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus");
qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile");
qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags");
}
/*!
Destroys the QSystemDeviceInfo object.
*/
QSystemDeviceInfo::~QSystemDeviceInfo()
{
}
/*!
\internal
This function is called when the client connects to signals.
\sa connectNotify()
*/
void QSystemDeviceInfo::connectNotify(const char *signal)
{
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryLevelChanged(int))))) {
connect(d,SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {
connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
bluetoothStateChanged(bool))))) {
connect(d,SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentProfileChanged(QSystemDeviceInfo::Profile))))) {
connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
powerStateChanged(QSystemDeviceInfo::PowerState))))) {
connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
}
/*!
\internal
This function is called when the client disconnects from the signals.
\sa connectNotify()
*/
void QSystemDeviceInfo::disconnectNotify(const char *signal)
{
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryLevelChanged(int))))) {
disconnect(d,SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {
disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
bluetoothStateChanged(bool))))) {
disconnect(d,SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentProfileChanged(QSystemDeviceInfo::Profile))))) {
disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
powerStateChanged(QSystemDeviceInfo::PowerState))))) {
disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
}
/*!
\property QSystemDeviceInfo::inputMethodType
\brief The supported inputmethods.
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()
{
return deviceInfoPrivate()->inputMethodType();
}
/*!
\property QSystemDeviceInfo::imei
\brief The IMEI.
Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imei()
{
return deviceInfoPrivate()->imei();
}
/*!
\property QSystemDeviceInfo::imsi
\brief The IMSI.
Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imsi()
{
return deviceInfoPrivate()->imsi();
}
/*!
\property QSystemDeviceInfo::manufacturer
\brief The manufacture's name.
Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
of the motherboard.
*/
QString QSystemDeviceInfo::manufacturer()
{
return deviceInfoPrivate()->manufacturer();
}
/*!
\property QSystemDeviceInfo::model
\brief The model name.
Returns the model information of the device. In the case of desktops where no
model information is present, the CPU architect, such as i686, and machine type, such as Server,
Desktop or Laptop.
*/
QString QSystemDeviceInfo::model()
{
return deviceInfoPrivate()->model();
}
/*!
\property QSystemDeviceInfo::productName
\brief The product name.
Returns the product name of the device. In the case where no product information is available,
*/
QString QSystemDeviceInfo::productName()
{
return deviceInfoPrivate()->productName();
}
/*!
\property QSystemDeviceInfo::batteryLevel
\brief The battery level.
Returns the battery charge level as percentage 1 - 100 scale.
*/
int QSystemDeviceInfo::batteryLevel() const
{
return deviceInfoPrivate()->batteryLevel();
}
/*!
\property QSystemDeviceInfo::batteryStatus
\brief The battery status.
Returns the battery charge status.
*/
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()
{
int level = batteryLevel();
if(level < 4) {
return QSystemDeviceInfo::BatteryCritical;
} else if(level < 11) {
return QSystemDeviceInfo::BatteryVeryLow;
} else if(level < 41) {
return QSystemDeviceInfo::BatteryLow;
} else if(level > 40) {
return QSystemDeviceInfo::BatteryNormal;
}
return QSystemDeviceInfo::NoBatteryLevel;
}
/*!
\property QSystemDeviceInfo::simStatus
\brief the status of the sim card.
Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()
{
return deviceInfoPrivate()->simStatus();
}
/*!
\property QSystemDeviceInfo::isDeviceLocked
\brief Device lock.
Returns true if the device is locked, otherwise false.
*/
bool QSystemDeviceInfo::isDeviceLocked()
{
return deviceInfoPrivate()->isDeviceLocked();
}
/*!
\property QSystemDeviceInfo::currentProfile
\brief the device profile
Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()
{
return deviceInfoPrivate()->currentProfile();
}
/*!
\property QSystemDeviceInfo::currentPowerState
\brief the power state.
Gets the current QSystemDeviceInfo::currentPowerState state.
*/
QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()
{
return deviceInfoPrivate()->currentPowerState();
}
/*!
\property QSystemDeviceInfo::currentBluetoothPowerState
\brief bluetooth power state.
Gets the current bluetooth power state.
*/
bool QSystemDeviceInfo::currentBluetoothPowerState()
{
return deviceInfoPrivate()->currentBluetoothPowerState();
}
#include "moc_qsystemdeviceinfo.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>/*!
\file timestamp.cpp
\brief Timestamp implementation
\author Ivan Shynkarenka
\date 26.01.2016
\copyright MIT License
*/
#include "time/timestamp.h"
#include "math/math.h"
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/time.h>
#include <math.h>
#include <time.h>
#elif defined(unix) || defined(__unix) || defined(__unix__)
#include <time.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
namespace CppCommon {
//! @cond INTERNALS
namespace Internals {
#if defined(__APPLE__)
uint32_t CeilLog2(uint32_t x)
{
uint32_t result = 0;
--x;
while (x > 0)
{
++result;
x >>= 1;
}
return result;
}
// This function returns the rational number inside the given interval with
// the smallest denominator (and smallest numerator breaks ties; correctness
// proof neglects floating-point errors).
mach_timebase_info_data_t BestFrac(double a, double b)
{
if (floor(a) < floor(b))
{
mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };
return rv;
}
double m = floor(a);
mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m));
mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };
return rv;
}
// This is just less than the smallest thing we can multiply numer by without
// overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer
uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)
{
uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;
return maxDiffWithoutOverflow * numer / denom;
}
// The clock may run up to 0.1% faster or slower than the "exact" tick count.
// However, although the bound on the error is the same as for the pragmatic
// answer, the error is actually minimized over the given accuracy bound.
uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)
{
tb.numer = 0;
tb.denom = 1;
kern_return_t mtiStatus = mach_timebase_info(&tb);
if (mtiStatus != KERN_SUCCESS)
return 0;
double frac = (double)tb.numer / tb.denom;
uint64_t spanTarget = 315360000000000000llu;
if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)
return 0;
for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;)
{
mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);
if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)
break;
tb = newFrac;
errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8;
}
return 0;
}
#endif
} // namespace Internals
//! @endcond
uint64_t Timestamp::utc()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
struct timespec timestamp;
if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)
throwex SystemException("Cannot get value of CLOCK_REALTIME timer!");
return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft);
ULARGE_INTEGER result;
result.LowPart = ft.dwLowDateTime;
result.HighPart = ft.dwHighDateTime;
return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}
uint64_t Timestamp::local()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
uint64_t timestamp = utc();
// Adjust UTC time with local timezone offset
struct tm local;
time_t seconds = timestamp / (1000000000);
if (localtime_r(&seconds, &local) != &local)
throwex SystemException("Cannot convert CLOCK_REALTIME time to local date & time structure!");
return timestamp + (local.tm_gmtoff * 1000000000);
#elif defined(_WIN32) || defined(_WIN64)
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft);
FILETIME ft_local;
if (!FileTimeToLocalFileTime(&ft, &ft_local))
throwex SystemException("Cannot convert UTC file time to local file time structure!");
ULARGE_INTEGER result;
result.LowPart = ft_local.dwLowDateTime;
result.HighPart = ft_local.dwHighDateTime;
return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}
uint64_t Timestamp::nano()
{
#if defined(__APPLE__)
static mach_timebase_info_data_t info;
static uint64_t bias = Internals::PrepareTimebaseInfo(info);
return ((mach_absolute_time() - bias) * info.numer) / info.denom;
#elif defined(unix) || defined(__unix) || defined(__unix__)
struct timespec timestamp = { 0 };
if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)
throwex SystemException("Cannot get value of CLOCK_MONOTONIC timer!");
return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
static uint64_t offset = 0;
static LARGE_INTEGER first = { 0 };
static LARGE_INTEGER frequency = { 0 };
static bool initialized = false;
static bool qpc = true;
if (!initialized)
{
// Calculate timestamp offset
FILETIME timestamp;
GetSystemTimePreciseAsFileTime(×tamp);
ULARGE_INTEGER result;
result.LowPart = timestamp.dwLowDateTime;
result.HighPart = timestamp.dwHighDateTime;
// Convert 01.01.1601 to 01.01.1970
result.QuadPart -= 116444736000000000ll;
offset = result.QuadPart * 100;
// Setup performance counter
qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);
initialized = true;
}
if (qpc)
{
LARGE_INTEGER timestamp = { 0 };
QueryPerformanceCounter(×tamp);
timestamp.QuadPart -= first.QuadPart;
return offset + Math::MulDiv64(timestamp.QuadPart, 1000000000, frequency.QuadPart);
}
else
return offset;
#else
#error Unsupported platform
#endif
}
uint64_t Timestamp::rdts()
{
#if defined(_MSC_VER)
return __rdtsc();
#elif defined(__i386__)
uint64_t x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
#elif defined(__x86_64__)
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo) | (((uint64_t)hi) << 32);
#endif
}
} // namespace CppCommon
<commit_msg>Use GetSystemTimeAsFileTime in case of old Windows API<commit_after>/*!
\file timestamp.cpp
\brief Timestamp implementation
\author Ivan Shynkarenka
\date 26.01.2016
\copyright MIT License
*/
#include "time/timestamp.h"
#include "math/math.h"
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/time.h>
#include <math.h>
#include <time.h>
#elif defined(unix) || defined(__unix) || defined(__unix__)
#include <time.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
namespace CppCommon {
//! @cond INTERNALS
namespace Internals {
#if defined(__APPLE__)
uint32_t CeilLog2(uint32_t x)
{
uint32_t result = 0;
--x;
while (x > 0)
{
++result;
x >>= 1;
}
return result;
}
// This function returns the rational number inside the given interval with
// the smallest denominator (and smallest numerator breaks ties; correctness
// proof neglects floating-point errors).
mach_timebase_info_data_t BestFrac(double a, double b)
{
if (floor(a) < floor(b))
{
mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };
return rv;
}
double m = floor(a);
mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m));
mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };
return rv;
}
// This is just less than the smallest thing we can multiply numer by without
// overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer
uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)
{
uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;
return maxDiffWithoutOverflow * numer / denom;
}
// The clock may run up to 0.1% faster or slower than the "exact" tick count.
// However, although the bound on the error is the same as for the pragmatic
// answer, the error is actually minimized over the given accuracy bound.
uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)
{
tb.numer = 0;
tb.denom = 1;
kern_return_t mtiStatus = mach_timebase_info(&tb);
if (mtiStatus != KERN_SUCCESS)
return 0;
double frac = (double)tb.numer / tb.denom;
uint64_t spanTarget = 315360000000000000llu;
if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)
return 0;
for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;)
{
mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);
if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)
break;
tb = newFrac;
errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8;
}
return 0;
}
#endif
} // namespace Internals
//! @endcond
uint64_t Timestamp::utc()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
struct timespec timestamp;
if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)
throwex SystemException("Cannot get value of CLOCK_REALTIME timer!");
return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft);
ULARGE_INTEGER result;
result.LowPart = ft.dwLowDateTime;
result.HighPart = ft.dwHighDateTime;
return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}
uint64_t Timestamp::local()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
uint64_t timestamp = utc();
// Adjust UTC time with local timezone offset
struct tm local;
time_t seconds = timestamp / (1000000000);
if (localtime_r(&seconds, &local) != &local)
throwex SystemException("Cannot convert CLOCK_REALTIME time to local date & time structure!");
return timestamp + (local.tm_gmtoff * 1000000000);
#elif defined(_WIN32) || defined(_WIN64)
FILETIME ft;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
GetSystemTimePreciseAsFileTime(&ft);
#else
GetSystemTimeAsFileTime(&ft);
#endif
FILETIME ft_local;
if (!FileTimeToLocalFileTime(&ft, &ft_local))
throwex SystemException("Cannot convert UTC file time to local file time structure!");
ULARGE_INTEGER result;
result.LowPart = ft_local.dwLowDateTime;
result.HighPart = ft_local.dwHighDateTime;
return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}
uint64_t Timestamp::nano()
{
#if defined(__APPLE__)
static mach_timebase_info_data_t info;
static uint64_t bias = Internals::PrepareTimebaseInfo(info);
return ((mach_absolute_time() - bias) * info.numer) / info.denom;
#elif defined(unix) || defined(__unix) || defined(__unix__)
struct timespec timestamp = { 0 };
if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)
throwex SystemException("Cannot get value of CLOCK_MONOTONIC timer!");
return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
static uint64_t offset = 0;
static LARGE_INTEGER first = { 0 };
static LARGE_INTEGER frequency = { 0 };
static bool initialized = false;
static bool qpc = true;
if (!initialized)
{
// Calculate timestamp offset
FILETIME timestamp;
GetSystemTimePreciseAsFileTime(×tamp);
ULARGE_INTEGER result;
result.LowPart = timestamp.dwLowDateTime;
result.HighPart = timestamp.dwHighDateTime;
// Convert 01.01.1601 to 01.01.1970
result.QuadPart -= 116444736000000000ll;
offset = result.QuadPart * 100;
// Setup performance counter
qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);
initialized = true;
}
if (qpc)
{
LARGE_INTEGER timestamp = { 0 };
QueryPerformanceCounter(×tamp);
timestamp.QuadPart -= first.QuadPart;
return offset + Math::MulDiv64(timestamp.QuadPart, 1000000000, frequency.QuadPart);
}
else
return offset;
#else
#error Unsupported platform
#endif
}
uint64_t Timestamp::rdts()
{
#if defined(_MSC_VER)
return __rdtsc();
#elif defined(__i386__)
uint64_t x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
#elif defined(__x86_64__)
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo) | (((uint64_t)hi) << 32);
#endif
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>#include "sensing/object_detection.hpp"
DetectObjectAction::DetectObjectAction(ros::NodeHandle nh, std::string name) :
nh_(nh),
as_(nh_, name, false),
action_name_(name),
object_sub_(nh_.subscribe(
"/recognized_object_array",
1,
&DetectObjectAction::detectedCB, this)) {
//register the goal and feeback callbacks
as_.registerGoalCallback(boost::bind(&DetectObjectAction::goalCB, this));
as_.registerPreemptCallback(boost::bind(&DetectObjectAction::preemptCB, this));
this->init();
ROS_INFO("Starting DetectObject server");
as_.start();
}
DetectObjectAction::~DetectObjectAction(void) {
}
void DetectObjectAction::init() {
detect_ = false;
object_found_ = false;
}
void DetectObjectAction::goalCB() {
detect_ = as_.acceptNewGoal()->detect;
this->executeCB();
}
void DetectObjectAction::preemptCB() {
ROS_INFO("Preempt");
as_.setPreempted();
}
void DetectObjectAction::executeCB() {
bool going = true;
bool success = false;
ros::Rate r(10);
ROS_INFO("Executing goal for %s", action_name_.c_str());
feedback_.curr_state = 0;
as_.publishFeedback(feedback_);
while (going) {
if (as_.isPreemptRequested() || !ros::ok()) {
ROS_INFO("%s: Preempted", action_name_.c_str());
as_.setPreempted();
going = false;
}
if (object_found_) {
result_.pose = object_pose_;
going = false;
success = true;
}
ros::spinOnce();
r.sleep();
}
feedback_.curr_state = 3;
as_.publishFeedback(feedback_);
if (success) {
ROS_INFO("%s: Succeeded!", action_name_.c_str());
as_.setSucceeded(result_);
} else {
ROS_INFO("%s: Failed!", action_name_.c_str());
as_.setAborted(result_);
}
}
void DetectObjectAction::detectedCB(const object_recognition_msgs::RecognizedObjectArray::ConstPtr& msg) {
// ROS_INFO("Object message received");
// TODO uncomment line
// if (msg->objects.size() == 1 && detect) {
if (msg->objects.size() == 1) {
tf::StampedTransform stransform;
tf::TransformListener listener;
const object_recognition_msgs::RecognizedObject& object = msg->objects[0];
const geometry_msgs::Pose obj_pose = object.pose.pose.pose;
ROS_INFO("Object was recognized. Key: %s", object.type.key.c_str());
try {
ROS_INFO("Object detection frame: %s", object.pose.header.frame_id.c_str());
geometry_msgs::PoseStamped pin;
pin.header.frame_id = object.pose.header.frame_id;
pin.header.stamp = ros::Time(0);
pin.pose = obj_pose;
geometry_msgs::PoseStamped pout;
listener.waitForTransform("/base_footprint", object.pose.header.frame_id.c_str(), ros::Time(0), ros::Duration(13.0) );
ROS_INFO("Received transform to robot base");
listener.transformPose("/base_footprint", pin, pout);
ROS_INFO("Transformed pose into robot's frame");
// DEBUG
// listener.lookupTransform("/base_footprint", object.pose.header.frame_id.c_str(), ros::Time(0), stransform);
// ROS_INFO("Computed transform to /base_footprint, Point (x,y,z): (%f,%f,%f)", stransform.getOrigin().x(), stransform.getOrigin().y(), stransform.getOrigin().z());
ROS_INFO("3D point in frame of /base_footprint, Point (x,y,z): (%f,%f,%f)", pout.pose.position.x, pout.pose.position.z, pout.pose.position.y);
// TODO
// ATTENTION: it seems coordinates z-y are flipped, so modify it
object_pose_ = pout;
object_found_ = true;
} catch (tf::TransformException ex) {
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
}
// TEST
// geometry_msgs::PoseStamped target_pose;
// target_pose.header.frame_id = "base_footprint";
// geometry_msgs::Quaternion quat;
// quat = tf::createQuaternionMsgFromRollPitchYaw(-3.129, 0.0549, 1.686);
// target_pose.pose.orientation.x = quat.x;
// target_pose.pose.orientation.y = quat.y;
// target_pose.pose.orientation.z = quat.z;
// target_pose.pose.orientation.w = quat.w;
// ROS_INFO("Quaternion info- x: %f y: %f z: %f w: %f", quat.x, quat.y, quat.z, quat.w);
// target_pose.pose.position.x = 0.1;
// target_pose.pose.position.y = -0.3;
// target_pose.pose.position.z = 0.02;
// object_pose_ = target_pose;
// object_found_ = true;
}
}
<commit_msg>fixed bug where transformed object coordinates were flipped and added guard to only parse object messages when goal has been accepted<commit_after>#include "sensing/object_detection.hpp"
DetectObjectAction::DetectObjectAction(ros::NodeHandle nh, std::string name) :
nh_(nh),
as_(nh_, name, false),
action_name_(name),
object_sub_(nh_.subscribe(
"/recognized_object_array",
1,
&DetectObjectAction::detectedCB, this)) {
//register the goal and feeback callbacks
as_.registerGoalCallback(boost::bind(&DetectObjectAction::goalCB, this));
as_.registerPreemptCallback(boost::bind(&DetectObjectAction::preemptCB, this));
this->init();
ROS_INFO("Starting DetectObject server");
as_.start();
}
DetectObjectAction::~DetectObjectAction(void) {
}
void DetectObjectAction::init() {
detect_ = false;
object_found_ = false;
}
void DetectObjectAction::goalCB() {
detect_ = as_.acceptNewGoal()->detect;
this->executeCB();
}
void DetectObjectAction::preemptCB() {
ROS_INFO("Preempt");
as_.setPreempted();
}
void DetectObjectAction::executeCB() {
bool going = true;
bool success = false;
ros::Rate r(10);
ROS_INFO("Executing goal for %s", action_name_.c_str());
feedback_.curr_state = 0;
as_.publishFeedback(feedback_);
while (going) {
if (as_.isPreemptRequested() || !ros::ok()) {
ROS_INFO("%s: Preempted", action_name_.c_str());
as_.setPreempted();
going = false;
}
if (object_found_) {
result_.pose = object_pose_;
going = false;
success = true;
}
ros::spinOnce();
r.sleep();
}
feedback_.curr_state = 3;
as_.publishFeedback(feedback_);
if (success) {
ROS_INFO("%s: Succeeded!", action_name_.c_str());
as_.setSucceeded(result_);
} else {
ROS_INFO("%s: Failed!", action_name_.c_str());
as_.setAborted(result_);
}
}
void DetectObjectAction::detectedCB(const object_recognition_msgs::RecognizedObjectArray::ConstPtr& msg) {
// ROS_INFO("Object message received");
if (msg->objects.size() == 1 && detect_) {
tf::StampedTransform stransform;
tf::TransformListener listener;
const object_recognition_msgs::RecognizedObject& object = msg->objects[0];
const geometry_msgs::Pose obj_pose = object.pose.pose.pose;
ROS_INFO("Object was recognized. Key: %s", object.type.key.c_str());
try {
ROS_INFO("Object detection frame: %s", object.pose.header.frame_id.c_str());
geometry_msgs::PoseStamped pin;
pin.header.frame_id = object.pose.header.frame_id;
pin.header.stamp = ros::Time(0);
pin.pose = obj_pose;
geometry_msgs::PoseStamped pout;
listener.waitForTransform("/base_footprint", object.pose.header.frame_id.c_str(), ros::Time(0), ros::Duration(13.0) );
ROS_INFO("Received transform to robot base");
listener.transformPose("/base_footprint", pin, pout);
ROS_INFO("Transformed pose into robot's frame");
ROS_INFO("3D point in frame of /base_footprint, Point (x,y,z): (%f,%f,%f)", pout.pose.position.x, pout.pose.position.y, pout.pose.position.z);
object_pose_ = pout;
object_found_ = true;
} catch (tf::TransformException ex) {
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
}
// TEST
// geometry_msgs::PoseStamped target_pose;
// target_pose.header.frame_id = "base_footprint";
// geometry_msgs::Quaternion quat;
// quat = tf::createQuaternionMsgFromRollPitchYaw(-3.129, 0.0549, 1.686);
// target_pose.pose.orientation.x = quat.x;
// target_pose.pose.orientation.y = quat.y;
// target_pose.pose.orientation.z = quat.z;
// target_pose.pose.orientation.w = quat.w;
// ROS_INFO("Quaternion info- x: %f y: %f z: %f w: %f", quat.x, quat.y, quat.z, quat.w);
// target_pose.pose.position.x = 0.1;
// target_pose.pose.position.y = -0.3;
// target_pose.pose.position.z = 0.02;
// object_pose_ = target_pose;
// object_found_ = true;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/fuzz/fuzz.h>
#include <base58.h>
#include <util/string.h>
#include <util/strencodings.h>
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
void test_one_input(const std::vector<uint8_t>& buffer)
{
const std::string random_encoded_string(buffer.begin(), buffer.end());
std::vector<unsigned char> decoded;
if (DecodeBase58(random_encoded_string, decoded, 100)) {
const std::string encoded_string = EncodeBase58(decoded);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
if (DecodeBase58Check(random_encoded_string, decoded, 100)) {
const std::string encoded_string = EncodeBase58Check(decoded);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
bool pf_invalid;
std::string decoded_string = DecodeBase32(random_encoded_string, &pf_invalid);
if (!pf_invalid) {
const std::string encoded_string = EncodeBase32(decoded_string);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
decoded_string = DecodeBase64(random_encoded_string, &pf_invalid);
if (!pf_invalid) {
const std::string encoded_string = EncodeBase64(decoded_string);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
}
<commit_msg>tests: Fuzz DecodeBase64PSBT(...)<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/fuzz/fuzz.h>
#include <base58.h>
#include <psbt.h>
#include <util/string.h>
#include <util/strencodings.h>
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
void test_one_input(const std::vector<uint8_t>& buffer)
{
const std::string random_encoded_string(buffer.begin(), buffer.end());
std::vector<unsigned char> decoded;
if (DecodeBase58(random_encoded_string, decoded, 100)) {
const std::string encoded_string = EncodeBase58(decoded);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
if (DecodeBase58Check(random_encoded_string, decoded, 100)) {
const std::string encoded_string = EncodeBase58Check(decoded);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
bool pf_invalid;
std::string decoded_string = DecodeBase32(random_encoded_string, &pf_invalid);
if (!pf_invalid) {
const std::string encoded_string = EncodeBase32(decoded_string);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
decoded_string = DecodeBase64(random_encoded_string, &pf_invalid);
if (!pf_invalid) {
const std::string encoded_string = EncodeBase64(decoded_string);
assert(encoded_string == TrimString(encoded_string));
assert(ToLower(encoded_string) == ToLower(TrimString(random_encoded_string)));
}
PartiallySignedTransaction psbt;
std::string error;
(void)DecodeBase64PSBT(psbt, random_encoded_string, error);
}
<|endoftext|> |
<commit_before>#include "extensions/filters/network/rbac/rbac_filter.h"
#include "envoy/buffer/buffer.h"
#include "envoy/network/connection.h"
#include "extensions/filters/network/well_known_names.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace RBACFilter {
RoleBasedAccessControlFilterConfig::RoleBasedAccessControlFilterConfig(
const envoy::config::filter::network::rbac::v2::RBAC& proto_config, Stats::Scope& scope)
: stats_(Filters::Common::RBAC::generateStats(proto_config.stat_prefix(), scope)),
engine_(Filters::Common::RBAC::createEngine(proto_config)),
shadow_engine_(Filters::Common::RBAC::createShadowEngine(proto_config)) {}
Network::FilterStatus RoleBasedAccessControlFilter::onData(Buffer::Instance&, bool) {
ENVOY_LOG(
debug, "checking connection: remoteAddress: {}, localAddress: {}, ssl: {}",
callbacks_->connection().remoteAddress()->asString(),
callbacks_->connection().localAddress()->asString(),
callbacks_->connection().ssl()
? "uriSanPeerCertificate: " + callbacks_->connection().ssl()->uriSanPeerCertificate() +
", subjectPeerCertificate: " +
callbacks_->connection().ssl()->subjectPeerCertificate()
: "none");
if (shadow_engine_result_ == Unknown) {
// TODO(quanlin): Pass the shadow engine results to other filters.
// Only check the engine and increase stats for the first time call to onData(), any following
// calls to onData() could just use the cached result and no need to increase the stats anymore.
shadow_engine_result_ = checkEngine(Filters::Common::RBAC::EnforcementMode::Shadow);
}
if (engine_result_ == Unknown) {
engine_result_ = checkEngine(Filters::Common::RBAC::EnforcementMode::Enforced);
}
if (engine_result_ == Allow) {
return Network::FilterStatus::Continue;
} else if (engine_result_ == Deny) {
callbacks_->connection().close(Network::ConnectionCloseType::NoFlush);
return Network::FilterStatus::StopIteration;
}
ENVOY_LOG(debug, "no engine, allowed by default");
return Network::FilterStatus::Continue;
}
EngineResult
RoleBasedAccessControlFilter::checkEngine(Filters::Common::RBAC::EnforcementMode mode) {
const auto& engine = config_->engine(mode);
if (engine.has_value()) {
if (engine->allowed(callbacks_->connection())) {
if (mode == Filters::Common::RBAC::EnforcementMode::Shadow) {
ENVOY_LOG(debug, "shadow allowed");
config_->stats().shadow_allowed_.inc();
} else if (mode == Filters::Common::RBAC::EnforcementMode::Enforced) {
ENVOY_LOG(debug, "enforced allowed");
config_->stats().allowed_.inc();
}
return Allow;
} else {
if (mode == Filters::Common::RBAC::EnforcementMode::Shadow) {
ENVOY_LOG(debug, "shadow denied");
config_->stats().shadow_denied_.inc();
} else if (mode == Filters::Common::RBAC::EnforcementMode::Enforced) {
ENVOY_LOG(debug, "enforced denied");
config_->stats().denied_.inc();
}
return Deny;
}
}
return None;
}
} // namespace RBACFilter
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
<commit_msg>rbac: add requestedServerName to debug output (#4798)<commit_after>#include "extensions/filters/network/rbac/rbac_filter.h"
#include "envoy/buffer/buffer.h"
#include "envoy/network/connection.h"
#include "extensions/filters/network/well_known_names.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace RBACFilter {
RoleBasedAccessControlFilterConfig::RoleBasedAccessControlFilterConfig(
const envoy::config::filter::network::rbac::v2::RBAC& proto_config, Stats::Scope& scope)
: stats_(Filters::Common::RBAC::generateStats(proto_config.stat_prefix(), scope)),
engine_(Filters::Common::RBAC::createEngine(proto_config)),
shadow_engine_(Filters::Common::RBAC::createShadowEngine(proto_config)) {}
Network::FilterStatus RoleBasedAccessControlFilter::onData(Buffer::Instance&, bool) {
ENVOY_LOG(
debug,
"checking connection: requestedServerName: {}, remoteAddress: {}, localAddress: {}, ssl: {}",
callbacks_->connection().requestedServerName(),
callbacks_->connection().remoteAddress()->asString(),
callbacks_->connection().localAddress()->asString(),
callbacks_->connection().ssl()
? "uriSanPeerCertificate: " + callbacks_->connection().ssl()->uriSanPeerCertificate() +
", subjectPeerCertificate: " +
callbacks_->connection().ssl()->subjectPeerCertificate()
: "none");
if (shadow_engine_result_ == Unknown) {
// TODO(quanlin): Pass the shadow engine results to other filters.
// Only check the engine and increase stats for the first time call to onData(), any following
// calls to onData() could just use the cached result and no need to increase the stats anymore.
shadow_engine_result_ = checkEngine(Filters::Common::RBAC::EnforcementMode::Shadow);
}
if (engine_result_ == Unknown) {
engine_result_ = checkEngine(Filters::Common::RBAC::EnforcementMode::Enforced);
}
if (engine_result_ == Allow) {
return Network::FilterStatus::Continue;
} else if (engine_result_ == Deny) {
callbacks_->connection().close(Network::ConnectionCloseType::NoFlush);
return Network::FilterStatus::StopIteration;
}
ENVOY_LOG(debug, "no engine, allowed by default");
return Network::FilterStatus::Continue;
}
EngineResult
RoleBasedAccessControlFilter::checkEngine(Filters::Common::RBAC::EnforcementMode mode) {
const auto& engine = config_->engine(mode);
if (engine.has_value()) {
if (engine->allowed(callbacks_->connection())) {
if (mode == Filters::Common::RBAC::EnforcementMode::Shadow) {
ENVOY_LOG(debug, "shadow allowed");
config_->stats().shadow_allowed_.inc();
} else if (mode == Filters::Common::RBAC::EnforcementMode::Enforced) {
ENVOY_LOG(debug, "enforced allowed");
config_->stats().allowed_.inc();
}
return Allow;
} else {
if (mode == Filters::Common::RBAC::EnforcementMode::Shadow) {
ENVOY_LOG(debug, "shadow denied");
config_->stats().shadow_denied_.inc();
} else if (mode == Filters::Common::RBAC::EnforcementMode::Enforced) {
ENVOY_LOG(debug, "enforced denied");
config_->stats().denied_.inc();
}
return Deny;
}
}
return None;
}
} // namespace RBACFilter
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
<|endoftext|> |
<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright 2016 [bk]door.maus
#include <algorithm>
#include "glurg/trace/structureSignature.hpp"
#include "glurg/trace/traceFile.hpp"
glurg::trace::StructureSignature::ID
glurg::trace::StructureSignature::get_id() const
{
return this->id;
}
std::size_t glurg::trace::StructureSignature::get_num_fields() const
{
return fields.size();
}
std::string glurg::trace::StructureSignature::get_field_name(
std::size_t index) const
{
return fields.at(index);
}
bool glurg::trace::StructureSignature::has_field_name(
const std::string& name) const
{
auto begin = this->fields.begin();
auto end = this->fields.end();
return std::find(begin, end, name) != end;
}
glurg::trace::StructureSignature* glurg::trace::StructureSignature::read(
ID id, TraceFile& trace, FileStream& stream)
{
StructureSignature* signature = new StructureSignature();
signature->id = id;
signature->name = trace.read_string(stream);
std::size_t count = trace.read_unsigned_integer(stream);
signature->set_num_fields(count);
for (std::size_t i = 0; i < count; ++i)
{
std::string field = trace.read_string(stream);
signature->set_field_name(i, field);
}
return signature;
}
void glurg::trace::StructureSignature::set_num_fields(std::size_t value)
{
fields.resize(value);
}
void glurg::trace::StructureSignature::set_field_name(
std::size_t index, const std::string& value)
{
fields.at(index) = value;
}
<commit_msg>Added missing method implementation.<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright 2016 [bk]door.maus
#include <algorithm>
#include "glurg/trace/structureSignature.hpp"
#include "glurg/trace/traceFile.hpp"
glurg::trace::StructureSignature::ID
glurg::trace::StructureSignature::get_id() const
{
return this->id;
}
std::string glurg::trace::StructureSignature::get_name() const
{
return this->name;
}
std::size_t glurg::trace::StructureSignature::get_num_fields() const
{
return fields.size();
}
std::string glurg::trace::StructureSignature::get_field_name(
std::size_t index) const
{
return fields.at(index);
}
bool glurg::trace::StructureSignature::has_field_name(
const std::string& name) const
{
auto begin = this->fields.begin();
auto end = this->fields.end();
return std::find(begin, end, name) != end;
}
glurg::trace::StructureSignature* glurg::trace::StructureSignature::read(
ID id, TraceFile& trace, FileStream& stream)
{
StructureSignature* signature = new StructureSignature();
signature->id = id;
signature->name = trace.read_string(stream);
std::size_t count = trace.read_unsigned_integer(stream);
signature->set_num_fields(count);
for (std::size_t i = 0; i < count; ++i)
{
std::string field = trace.read_string(stream);
signature->set_field_name(i, field);
}
return signature;
}
void glurg::trace::StructureSignature::set_num_fields(std::size_t value)
{
fields.resize(value);
}
void glurg::trace::StructureSignature::set_field_name(
std::size_t index, const std::string& value)
{
fields.at(index) = value;
}
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <vector>
#include <map>
#include <qi/os.hpp>
#include <qimessaging/service_directory.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
// declare the program options
po::options_description desc("Usage:\n qi-master masterAddress [options]\nOptions");
desc.add_options()
("help", "Print this help.")
("master-address",
po::value<std::string>()->default_value(std::string("tcp://0.0.0.0:5555")),
"The master address");
// allow master address to be specified as the first arg
po::positional_options_description pos;
pos.add("master-address", 1);
// parse and store
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 0;
}
if (vm.count("master-address") == 1)
{
std::string masterAddress = vm["master-address"].as<std::string>();
qi::ServiceDirectory sd;
if (!sd.listen(masterAddress))
{
exit(1);
}
std::cout << "ready." << std::endl;
sd.join();
}
else
{
std::cout << desc << "\n";
}
}
catch (const boost::program_options::error&)
{
std::cout << desc << "\n";
}
return 0;
}
<commit_msg>qi-master: Use qi::Application.<commit_after>/*
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <vector>
#include <map>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <qimessaging/service_directory.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
qi::Application app(argc, argv);
// declare the program options
po::options_description desc("Usage:\n qi-master masterAddress [options]\nOptions");
desc.add_options()
("help", "Print this help.")
("master-address",
po::value<std::string>()->default_value(std::string("tcp://0.0.0.0:5555")),
"The master address");
// allow master address to be specified as the first arg
po::positional_options_description pos;
pos.add("master-address", 1);
// parse and store
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 0;
}
if (vm.count("master-address") == 1)
{
std::string masterAddress = vm["master-address"].as<std::string>();
qi::ServiceDirectory sd;
if (!sd.listen(masterAddress))
{
exit(1);
}
std::cout << "ready." << std::endl;
app.run();
}
else
{
std::cout << desc << "\n";
}
}
catch (const boost::program_options::error&)
{
std::cout << desc << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "applicationlauncher.h"
#include "consoleprocess.h"
#ifdef Q_OS_WIN
#include "windebuginterface.h"
#endif
#include <coreplugin/icore.h>
#include <utils/qtcprocess.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
#include <QtCore/QTimer>
#include <QtCore/QTextCodec>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
#include "projectexplorerconstants.h"
#include "projectexplorer.h"
#include "projectexplorersettings.h"
/*!
\class ProjectExplorer::ApplicationLauncher
\brief Application launcher of the ProjectExplorer plugin.
Encapsulates processes running in a console or as GUI processes,
captures debug output of GUI processes on Windows (outputDebugString()).
\sa Utils::ConsoleProcess
*/
namespace ProjectExplorer {
#ifdef Q_OS_WIN
using namespace Internal; // for WinDebugInterface
#endif
struct ApplicationLauncherPrivate {
ApplicationLauncherPrivate();
Utils::QtcProcess m_guiProcess;
Utils::ConsoleProcess m_consoleProcess;
ApplicationLauncher::Mode m_currentMode;
QTextCodec *m_outputCodec;
QTextCodec::ConverterState m_outputCodecState;
QTextCodec::ConverterState m_errorCodecState;
};
ApplicationLauncherPrivate::ApplicationLauncherPrivate() :
m_currentMode(ApplicationLauncher::Gui),
m_outputCodec(QTextCodec::codecForLocale())
{
}
ApplicationLauncher::ApplicationLauncher(QObject *parent)
: QObject(parent), d(new ApplicationLauncherPrivate)
{
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().mergeStdErrAndStdOut){
d->m_guiProcess.setReadChannelMode(QProcess::MergedChannels);
} else {
d->m_guiProcess.setReadChannelMode(QProcess::SeparateChannels);
connect(&d->m_guiProcess, SIGNAL(readyReadStandardError()),
this, SLOT(readStandardError()));
}
connect(&d->m_guiProcess, SIGNAL(readyReadStandardOutput()),
this, SLOT(readStandardOutput()));
connect(&d->m_guiProcess, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(guiProcessError()));
connect(&d->m_guiProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(processDone(int, QProcess::ExitStatus)));
connect(&d->m_guiProcess, SIGNAL(started()),
this, SLOT(bringToForeground()));
#ifdef Q_OS_UNIX
d->m_consoleProcess.setSettings(Core::ICore::instance()->settings());
#endif
connect(&d->m_consoleProcess, SIGNAL(processError(QString)),
this, SLOT(consoleProcessError(QString)));
connect(&d->m_consoleProcess, SIGNAL(processStopped()),
this, SLOT(processStopped()));
#ifdef Q_OS_WIN
connect(WinDebugInterface::instance(), SIGNAL(debugOutput(qint64,QString)),
this, SLOT(checkDebugOutput(qint64,QString)));
#endif
}
ApplicationLauncher::~ApplicationLauncher()
{
}
void ApplicationLauncher::setWorkingDirectory(const QString &dir)
{
#ifdef Q_OS_WIN
// Work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch' ...)
const QString fixedPath = Utils::normalizePathName(dir);
#else
# define fixedPath dir
#endif
d->m_guiProcess.setWorkingDirectory(fixedPath);
d->m_consoleProcess.setWorkingDirectory(fixedPath);
#ifndef Q_OS_WIN
# undef fixedPath
#endif
}
void ApplicationLauncher::setEnvironment(const Utils::Environment &env)
{
d->m_guiProcess.setEnvironment(env);
d->m_consoleProcess.setEnvironment(env);
}
void ApplicationLauncher::start(Mode mode, const QString &program, const QString &args)
{
#ifdef Q_OS_WIN
if (!WinDebugInterface::instance()->isRunning())
WinDebugInterface::instance()->start(); // Try to start listener again...
if (!WinDebugInterface::instance()->isRunning())
emit appendMessage(msgWinCannotRetrieveDebuggingOutput(), Utils::ErrorMessageFormat);
#endif
d->m_currentMode = mode;
if (mode == Gui) {
d->m_guiProcess.setCommand(program, args);
d->m_guiProcess.start();
} else {
d->m_consoleProcess.start(program, args);
}
}
void ApplicationLauncher::stop()
{
if (!isRunning())
return;
if (d->m_currentMode == Gui) {
d->m_guiProcess.terminate();
if (!d->m_guiProcess.waitForFinished(1000)) { // This is blocking, so be fast.
d->m_guiProcess.kill();
d->m_guiProcess.waitForFinished();
}
} else {
d->m_consoleProcess.stop();
processStopped();
}
}
bool ApplicationLauncher::isRunning() const
{
if (d->m_currentMode == Gui)
return d->m_guiProcess.state() != QProcess::NotRunning;
else
return d->m_consoleProcess.isRunning();
}
qint64 ApplicationLauncher::applicationPID() const
{
qint64 result = 0;
if (!isRunning())
return result;
if (d->m_currentMode == Console) {
result = d->m_consoleProcess.applicationPID();
} else {
#ifdef Q_OS_WIN
result = (qint64)d->m_guiProcess.pid()->dwProcessId;
#else
result = (qint64)d->m_guiProcess.pid();
#endif
}
return result;
}
void ApplicationLauncher::guiProcessError()
{
QString error;
switch (d->m_guiProcess.error()) {
case QProcess::FailedToStart:
error = tr("Failed to start program. Path or permissions wrong?");
break;
case QProcess::Crashed:
error = tr("The program has unexpectedly finished.");
break;
default:
error = tr("Some error has occurred while running the program.");
}
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
emit processExited(d->m_guiProcess.exitCode());
}
void ApplicationLauncher::consoleProcessError(const QString &error)
{
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
}
void ApplicationLauncher::readStandardOutput()
{
QByteArray data = d->m_guiProcess.readAllStandardOutput();
QString msg = d->m_outputCodec->toUnicode(
data.constData(), data.length(), &d->m_outputCodecState);
emit appendMessage(msg, Utils::StdOutFormatSameLine);
}
void ApplicationLauncher::readStandardError()
{
QByteArray data = d->m_guiProcess.readAllStandardError();
QString msg = d->m_outputCodec->toUnicode(
data.constData(), data.length(), &d->m_outputCodecState);
emit appendMessage(msg, Utils::StdErrFormatSameLine);
}
#ifdef Q_OS_WIN
void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message)
{
if (applicationPID() == pid)
emit appendMessage(message, Utils::DebugFormat);
}
#endif
void ApplicationLauncher::processStopped()
{
emit processExited(0);
}
void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus)
{
emit processExited(exitCode);
}
void ApplicationLauncher::bringToForeground()
{
emit bringToForegroundRequested(applicationPID());
}
QString ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput()
{
return tr("Cannot retrieve debugging output.\n");
}
} // namespace ProjectExplorer
<commit_msg>Fix double message introduced for killed applications<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "applicationlauncher.h"
#include "consoleprocess.h"
#ifdef Q_OS_WIN
#include "windebuginterface.h"
#endif
#include <coreplugin/icore.h>
#include <utils/qtcprocess.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
#include <QtCore/QTimer>
#include <QtCore/QTextCodec>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
#include "projectexplorerconstants.h"
#include "projectexplorer.h"
#include "projectexplorersettings.h"
/*!
\class ProjectExplorer::ApplicationLauncher
\brief Application launcher of the ProjectExplorer plugin.
Encapsulates processes running in a console or as GUI processes,
captures debug output of GUI processes on Windows (outputDebugString()).
\sa Utils::ConsoleProcess
*/
namespace ProjectExplorer {
#ifdef Q_OS_WIN
using namespace Internal; // for WinDebugInterface
#endif
struct ApplicationLauncherPrivate {
ApplicationLauncherPrivate();
Utils::QtcProcess m_guiProcess;
Utils::ConsoleProcess m_consoleProcess;
ApplicationLauncher::Mode m_currentMode;
QTextCodec *m_outputCodec;
QTextCodec::ConverterState m_outputCodecState;
QTextCodec::ConverterState m_errorCodecState;
};
ApplicationLauncherPrivate::ApplicationLauncherPrivate() :
m_currentMode(ApplicationLauncher::Gui),
m_outputCodec(QTextCodec::codecForLocale())
{
}
ApplicationLauncher::ApplicationLauncher(QObject *parent)
: QObject(parent), d(new ApplicationLauncherPrivate)
{
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().mergeStdErrAndStdOut){
d->m_guiProcess.setReadChannelMode(QProcess::MergedChannels);
} else {
d->m_guiProcess.setReadChannelMode(QProcess::SeparateChannels);
connect(&d->m_guiProcess, SIGNAL(readyReadStandardError()),
this, SLOT(readStandardError()));
}
connect(&d->m_guiProcess, SIGNAL(readyReadStandardOutput()),
this, SLOT(readStandardOutput()));
connect(&d->m_guiProcess, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(guiProcessError()));
connect(&d->m_guiProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(processDone(int, QProcess::ExitStatus)));
connect(&d->m_guiProcess, SIGNAL(started()),
this, SLOT(bringToForeground()));
#ifdef Q_OS_UNIX
d->m_consoleProcess.setSettings(Core::ICore::instance()->settings());
#endif
connect(&d->m_consoleProcess, SIGNAL(processError(QString)),
this, SLOT(consoleProcessError(QString)));
connect(&d->m_consoleProcess, SIGNAL(processStopped()),
this, SLOT(processStopped()));
#ifdef Q_OS_WIN
connect(WinDebugInterface::instance(), SIGNAL(debugOutput(qint64,QString)),
this, SLOT(checkDebugOutput(qint64,QString)));
#endif
}
ApplicationLauncher::~ApplicationLauncher()
{
}
void ApplicationLauncher::setWorkingDirectory(const QString &dir)
{
#ifdef Q_OS_WIN
// Work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch' ...)
const QString fixedPath = Utils::normalizePathName(dir);
#else
# define fixedPath dir
#endif
d->m_guiProcess.setWorkingDirectory(fixedPath);
d->m_consoleProcess.setWorkingDirectory(fixedPath);
#ifndef Q_OS_WIN
# undef fixedPath
#endif
}
void ApplicationLauncher::setEnvironment(const Utils::Environment &env)
{
d->m_guiProcess.setEnvironment(env);
d->m_consoleProcess.setEnvironment(env);
}
void ApplicationLauncher::start(Mode mode, const QString &program, const QString &args)
{
#ifdef Q_OS_WIN
if (!WinDebugInterface::instance()->isRunning())
WinDebugInterface::instance()->start(); // Try to start listener again...
if (!WinDebugInterface::instance()->isRunning())
emit appendMessage(msgWinCannotRetrieveDebuggingOutput(), Utils::ErrorMessageFormat);
#endif
d->m_currentMode = mode;
if (mode == Gui) {
d->m_guiProcess.setCommand(program, args);
d->m_guiProcess.start();
} else {
d->m_consoleProcess.start(program, args);
}
}
void ApplicationLauncher::stop()
{
if (!isRunning())
return;
if (d->m_currentMode == Gui) {
d->m_guiProcess.terminate();
if (!d->m_guiProcess.waitForFinished(1000)) { // This is blocking, so be fast.
d->m_guiProcess.kill();
d->m_guiProcess.waitForFinished();
}
} else {
d->m_consoleProcess.stop();
processStopped();
}
}
bool ApplicationLauncher::isRunning() const
{
if (d->m_currentMode == Gui)
return d->m_guiProcess.state() != QProcess::NotRunning;
else
return d->m_consoleProcess.isRunning();
}
qint64 ApplicationLauncher::applicationPID() const
{
qint64 result = 0;
if (!isRunning())
return result;
if (d->m_currentMode == Console) {
result = d->m_consoleProcess.applicationPID();
} else {
#ifdef Q_OS_WIN
result = (qint64)d->m_guiProcess.pid()->dwProcessId;
#else
result = (qint64)d->m_guiProcess.pid();
#endif
}
return result;
}
void ApplicationLauncher::guiProcessError()
{
QString error;
switch (d->m_guiProcess.error()) {
case QProcess::FailedToStart:
error = tr("Failed to start program. Path or permissions wrong?");
break;
case QProcess::Crashed:
error = tr("The program has unexpectedly finished.");
break;
default:
error = tr("Some error has occurred while running the program.");
}
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
}
void ApplicationLauncher::consoleProcessError(const QString &error)
{
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
}
void ApplicationLauncher::readStandardOutput()
{
QByteArray data = d->m_guiProcess.readAllStandardOutput();
QString msg = d->m_outputCodec->toUnicode(
data.constData(), data.length(), &d->m_outputCodecState);
emit appendMessage(msg, Utils::StdOutFormatSameLine);
}
void ApplicationLauncher::readStandardError()
{
QByteArray data = d->m_guiProcess.readAllStandardError();
QString msg = d->m_outputCodec->toUnicode(
data.constData(), data.length(), &d->m_outputCodecState);
emit appendMessage(msg, Utils::StdErrFormatSameLine);
}
#ifdef Q_OS_WIN
void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message)
{
if (applicationPID() == pid)
emit appendMessage(message, Utils::DebugFormat);
}
#endif
void ApplicationLauncher::processStopped()
{
emit processExited(0);
}
void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus)
{
emit processExited(exitCode);
}
void ApplicationLauncher::bringToForeground()
{
emit bringToForegroundRequested(applicationPID());
}
QString ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput()
{
return tr("Cannot retrieve debugging output.\n");
}
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "remotelinuxdebugsupport.h"
#include "linuxdeviceconfiguration.h"
#include "remotelinuxapplicationrunner.h"
#include "remotelinuxrunconfiguration.h"
#include "remotelinuxusedportsgatherer.h"
#include <debugger/debuggerengine.h>
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerprofileinformation.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/profile.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qtsupport/qtprofileinformation.h>
#include <utils/qtcassert.h>
#include <QPointer>
#include <QSharedPointer>
using namespace QSsh;
using namespace Debugger;
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
namespace {
enum State { Inactive, StartingRunner, StartingRemoteProcess, Debugging };
} // anonymous namespace
class AbstractRemoteLinuxDebugSupportPrivate
{
public:
AbstractRemoteLinuxDebugSupportPrivate(RunConfiguration *runConfig,
DebuggerEngine *engine)
: engine(engine),
qmlDebugging(runConfig->debuggerAspect()->useQmlDebugger()),
cppDebugging(runConfig->debuggerAspect()->useCppDebugger()),
state(Inactive),
gdbServerPort(-1), qmlPort(-1)
{
}
const QPointer<Debugger::DebuggerEngine> engine;
bool qmlDebugging;
bool cppDebugging;
QByteArray gdbserverOutput;
State state;
int gdbServerPort;
int qmlPort;
};
class RemoteLinuxDebugSupportPrivate
{
public:
RemoteLinuxDebugSupportPrivate(RemoteLinuxRunConfiguration *runConfig) : runner(runConfig) {}
GenericRemoteLinuxApplicationRunner runner;
};
} // namespace Internal
using namespace Internal;
DebuggerStartParameters AbstractRemoteLinuxDebugSupport::startParameters(const RemoteLinuxRunConfiguration *runConfig)
{
DebuggerStartParameters params;
const LinuxDeviceConfiguration::ConstPtr devConf
= ProjectExplorer::DeviceProfileInformation::device(runConfig->target()->profile())
.dynamicCast<const RemoteLinux::LinuxDeviceConfiguration>();
if (runConfig->debuggerAspect()->useQmlDebugger()) {
params.languages |= QmlLanguage;
params.qmlServerAddress = devConf->sshParameters().host;
params.qmlServerPort = 0; // port is selected later on
}
if (runConfig->debuggerAspect()->useCppDebugger()) {
params.languages |= CppLanguage;
params.processArgs = runConfig->arguments();
QString systemRoot;
if (ProjectExplorer::SysRootProfileInformation::hasSysRoot(runConfig->target()->profile()))
systemRoot = ProjectExplorer::SysRootProfileInformation::sysRoot(runConfig->target()->profile()).toString();
params.sysroot = systemRoot;
params.toolChainAbi = runConfig->abi();
params.startMode = AttachToRemoteServer;
params.executable = runConfig->localExecutableFilePath();
params.debuggerCommand = Debugger::DebuggerProfileInformation::debuggerCommand(runConfig->target()->profile()).toString();
params.remoteChannel = devConf->sshParameters().host + QLatin1String(":-1");
// TODO: This functionality should be inside the debugger.
ToolChain *tc = ToolChainProfileInformation::toolChain(runConfig->target()->profile());
if (tc) {
const ProjectExplorer::Abi &abi = tc->targetAbi();
params.remoteArchitecture = abi.toString();
params.gnuTarget = QLatin1String(abi.architecture() == ProjectExplorer::Abi::ArmArchitecture
? "arm-none-linux-gnueabi": "i386-unknown-linux-gnu");
}
} else {
params.startMode = AttachToRemoteServer;
}
params.remoteSetupNeeded = true;
params.displayName = runConfig->displayName();
if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory();
if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration()) {
params.projectBuildDirectory = buildConfig->buildDirectory();
}
params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
}
return params;
}
AbstractRemoteLinuxDebugSupport::AbstractRemoteLinuxDebugSupport(RunConfiguration *runConfig,
DebuggerEngine *engine)
: QObject(engine), d(new AbstractRemoteLinuxDebugSupportPrivate(runConfig, engine))
{
connect(d->engine, SIGNAL(requestRemoteSetup()), this, SLOT(handleRemoteSetupRequested()));
}
AbstractRemoteLinuxDebugSupport::~AbstractRemoteLinuxDebugSupport()
{
setFinished();
delete d;
}
void AbstractRemoteLinuxDebugSupport::showMessage(const QString &msg, int channel)
{
if (d->engine)
d->engine->showMessage(msg, channel);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteSetupRequested()
{
QTC_ASSERT(d->state == Inactive, return);
d->state = StartingRunner;
showMessage(tr("Preparing remote side...\n"), AppStuff);
disconnect(runner(), 0, this, 0);
connect(runner(), SIGNAL(error(QString)), this, SLOT(handleSshError(QString)));
connect(runner(), SIGNAL(readyForExecution()), this, SLOT(startExecution()));
connect(runner(), SIGNAL(reportProgress(QString)), this, SLOT(handleProgressReport(QString)));
runner()->start();
}
void AbstractRemoteLinuxDebugSupport::handleSshError(const QString &error)
{
if (d->state == Debugging) {
showMessage(error, AppError);
if (d->engine)
d->engine->notifyInferiorIll();
} else if (d->state != Inactive) {
handleAdapterSetupFailed(error);
}
}
void AbstractRemoteLinuxDebugSupport::startExecution()
{
if (d->state == Inactive)
return;
QTC_ASSERT(d->state == StartingRunner, return);
if (d->cppDebugging && !setPort(d->gdbServerPort))
return;
if (d->qmlDebugging && !setPort(d->qmlPort))
return;
d->state = StartingRemoteProcess;
d->gdbserverOutput.clear();
connect(runner(), SIGNAL(remoteErrorOutput(QByteArray)), this,
SLOT(handleRemoteErrorOutput(QByteArray)));
connect(runner(), SIGNAL(remoteOutput(QByteArray)), this,
SLOT(handleRemoteOutput(QByteArray)));
if (d->qmlDebugging && !d->cppDebugging) {
connect(runner(), SIGNAL(remoteProcessStarted()),
SLOT(handleRemoteProcessStarted()));
}
const QString &remoteExe = runner()->remoteExecutable();
QString args = runner()->arguments();
if (d->qmlDebugging) {
args += QString::fromLatin1(" -qmljsdebugger=port:%1,block")
.arg(d->qmlPort);
}
const QHostAddress peerAddress = runner()->connection()->connectionInfo().peerAddress;
QString peerAddressString = peerAddress.toString();
if (peerAddress.protocol() == QAbstractSocket::IPv6Protocol)
peerAddressString.prepend(QLatin1Char('[')).append(QLatin1Char(']'));
const QString remoteCommandLine = (d->qmlDebugging && !d->cppDebugging)
? QString::fromLatin1("%1 %2 %3").arg(runner()->commandPrefix()).arg(remoteExe).arg(args)
: QString::fromLatin1("%1 gdbserver %5:%2 %3 %4").arg(runner()->commandPrefix())
.arg(d->gdbServerPort).arg(remoteExe).arg(args).arg(peerAddressString);
connect(runner(), SIGNAL(remoteProcessFinished(qint64)),
SLOT(handleRemoteProcessFinished(qint64)));
runner()->startExecution(remoteCommandLine.toUtf8());
}
void AbstractRemoteLinuxDebugSupport::handleRemoteProcessFinished(qint64 exitCode)
{
if (!d->engine || d->state == Inactive)
return;
if (d->state == Debugging) {
// The QML engine does not realize on its own that the application has finished.
if (d->qmlDebugging && !d->cppDebugging)
d->engine->quitDebugger();
else if (exitCode != 0)
d->engine->notifyInferiorIll();
} else {
const QString errorMsg = (d->qmlDebugging && !d->cppDebugging)
? tr("Remote application failed with exit code %1.").arg(exitCode)
: tr("The gdbserver process closed unexpectedly.");
d->engine->notifyEngineRemoteSetupFailed(errorMsg);
}
}
void AbstractRemoteLinuxDebugSupport::handleDebuggingFinished()
{
setFinished();
}
void AbstractRemoteLinuxDebugSupport::handleRemoteOutput(const QByteArray &output)
{
QTC_ASSERT(d->state == Inactive || d->state == Debugging, return);
showMessage(QString::fromUtf8(output), AppOutput);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteErrorOutput(const QByteArray &output)
{
QTC_ASSERT(d->state == Inactive || d->state == StartingRemoteProcess || d->state == Debugging,
return);
if (!d->engine)
return;
showMessage(QString::fromUtf8(output), AppOutput);
if (d->state == StartingRemoteProcess && d->cppDebugging) {
d->gdbserverOutput += output;
if (d->gdbserverOutput.contains("Listening on port")) {
handleAdapterSetupDone();
d->gdbserverOutput.clear();
}
}
}
void AbstractRemoteLinuxDebugSupport::handleProgressReport(const QString &progressOutput)
{
showMessage(progressOutput + QLatin1Char('\n'), AppStuff);
}
void AbstractRemoteLinuxDebugSupport::handleAdapterSetupFailed(const QString &error)
{
setFinished();
d->engine->notifyEngineRemoteSetupFailed(tr("Initial setup failed: %1").arg(error));
}
void AbstractRemoteLinuxDebugSupport::handleAdapterSetupDone()
{
d->state = Debugging;
d->engine->notifyEngineRemoteSetupDone(d->gdbServerPort, d->qmlPort);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteProcessStarted()
{
Q_ASSERT(d->qmlDebugging && !d->cppDebugging);
QTC_ASSERT(d->state == StartingRemoteProcess, return);
handleAdapterSetupDone();
}
void AbstractRemoteLinuxDebugSupport::setFinished()
{
if (d->state == Inactive)
return;
d->state = Inactive;
runner()->stop();
}
bool AbstractRemoteLinuxDebugSupport::setPort(int &port)
{
port = runner()->usedPortsGatherer()->getNextFreePort(runner()->freePorts());
if (port == -1) {
handleAdapterSetupFailed(tr("Not enough free ports on device for debugging."));
return false;
}
return true;
}
RemoteLinuxDebugSupport::RemoteLinuxDebugSupport(RemoteLinuxRunConfiguration *runConfig,
DebuggerEngine *engine)
: AbstractRemoteLinuxDebugSupport(runConfig, engine),
d(new RemoteLinuxDebugSupportPrivate(runConfig))
{
}
RemoteLinuxDebugSupport::~RemoteLinuxDebugSupport()
{
delete d;
}
AbstractRemoteLinuxApplicationRunner *RemoteLinuxDebugSupport::runner() const
{
return &d->runner;
}
} // namespace RemoteLinux
<commit_msg>remotelinux: remove line noise<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "remotelinuxdebugsupport.h"
#include "linuxdeviceconfiguration.h"
#include "remotelinuxapplicationrunner.h"
#include "remotelinuxrunconfiguration.h"
#include "remotelinuxusedportsgatherer.h"
#include <debugger/debuggerengine.h>
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerprofileinformation.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/profile.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qtsupport/qtprofileinformation.h>
#include <utils/qtcassert.h>
#include <QPointer>
#include <QSharedPointer>
using namespace QSsh;
using namespace Debugger;
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
namespace {
enum State { Inactive, StartingRunner, StartingRemoteProcess, Debugging };
} // anonymous namespace
class AbstractRemoteLinuxDebugSupportPrivate
{
public:
AbstractRemoteLinuxDebugSupportPrivate(RunConfiguration *runConfig,
DebuggerEngine *engine)
: engine(engine),
qmlDebugging(runConfig->debuggerAspect()->useQmlDebugger()),
cppDebugging(runConfig->debuggerAspect()->useCppDebugger()),
state(Inactive),
gdbServerPort(-1), qmlPort(-1)
{
}
const QPointer<DebuggerEngine> engine;
bool qmlDebugging;
bool cppDebugging;
QByteArray gdbserverOutput;
State state;
int gdbServerPort;
int qmlPort;
};
class RemoteLinuxDebugSupportPrivate
{
public:
RemoteLinuxDebugSupportPrivate(RemoteLinuxRunConfiguration *runConfig) : runner(runConfig) {}
GenericRemoteLinuxApplicationRunner runner;
};
} // namespace Internal
using namespace Internal;
DebuggerStartParameters AbstractRemoteLinuxDebugSupport::startParameters(const RemoteLinuxRunConfiguration *runConfig)
{
DebuggerStartParameters params;
const LinuxDeviceConfiguration::ConstPtr devConf
= DeviceProfileInformation::device(runConfig->target()->profile())
.dynamicCast<const RemoteLinux::LinuxDeviceConfiguration>();
if (runConfig->debuggerAspect()->useQmlDebugger()) {
params.languages |= QmlLanguage;
params.qmlServerAddress = devConf->sshParameters().host;
params.qmlServerPort = 0; // port is selected later on
}
if (runConfig->debuggerAspect()->useCppDebugger()) {
params.languages |= CppLanguage;
params.processArgs = runConfig->arguments();
QString systemRoot;
if (SysRootProfileInformation::hasSysRoot(runConfig->target()->profile()))
systemRoot = SysRootProfileInformation::sysRoot(runConfig->target()->profile()).toString();
params.sysroot = systemRoot;
params.toolChainAbi = runConfig->abi();
params.startMode = AttachToRemoteServer;
params.executable = runConfig->localExecutableFilePath();
params.debuggerCommand = DebuggerProfileInformation::debuggerCommand(runConfig->target()->profile()).toString();
params.remoteChannel = devConf->sshParameters().host + QLatin1String(":-1");
// TODO: This functionality should be inside the debugger.
ToolChain *tc = ToolChainProfileInformation::toolChain(runConfig->target()->profile());
if (tc) {
const Abi &abi = tc->targetAbi();
params.remoteArchitecture = abi.toString();
params.gnuTarget = QLatin1String(abi.architecture() == Abi::ArmArchitecture
? "arm-none-linux-gnueabi": "i386-unknown-linux-gnu");
}
} else {
params.startMode = AttachToRemoteServer;
}
params.remoteSetupNeeded = true;
params.displayName = runConfig->displayName();
if (const Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory();
if (const BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
params.projectBuildDirectory = buildConfig->buildDirectory();
params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
}
return params;
}
AbstractRemoteLinuxDebugSupport::AbstractRemoteLinuxDebugSupport(RunConfiguration *runConfig,
DebuggerEngine *engine)
: QObject(engine), d(new AbstractRemoteLinuxDebugSupportPrivate(runConfig, engine))
{
connect(d->engine, SIGNAL(requestRemoteSetup()), this, SLOT(handleRemoteSetupRequested()));
}
AbstractRemoteLinuxDebugSupport::~AbstractRemoteLinuxDebugSupport()
{
setFinished();
delete d;
}
void AbstractRemoteLinuxDebugSupport::showMessage(const QString &msg, int channel)
{
if (d->engine)
d->engine->showMessage(msg, channel);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteSetupRequested()
{
QTC_ASSERT(d->state == Inactive, return);
d->state = StartingRunner;
showMessage(tr("Preparing remote side...\n"), AppStuff);
disconnect(runner(), 0, this, 0);
connect(runner(), SIGNAL(error(QString)), this, SLOT(handleSshError(QString)));
connect(runner(), SIGNAL(readyForExecution()), this, SLOT(startExecution()));
connect(runner(), SIGNAL(reportProgress(QString)), this, SLOT(handleProgressReport(QString)));
runner()->start();
}
void AbstractRemoteLinuxDebugSupport::handleSshError(const QString &error)
{
if (d->state == Debugging) {
showMessage(error, AppError);
if (d->engine)
d->engine->notifyInferiorIll();
} else if (d->state != Inactive) {
handleAdapterSetupFailed(error);
}
}
void AbstractRemoteLinuxDebugSupport::startExecution()
{
if (d->state == Inactive)
return;
QTC_ASSERT(d->state == StartingRunner, return);
if (d->cppDebugging && !setPort(d->gdbServerPort))
return;
if (d->qmlDebugging && !setPort(d->qmlPort))
return;
d->state = StartingRemoteProcess;
d->gdbserverOutput.clear();
connect(runner(), SIGNAL(remoteErrorOutput(QByteArray)), this,
SLOT(handleRemoteErrorOutput(QByteArray)));
connect(runner(), SIGNAL(remoteOutput(QByteArray)), this,
SLOT(handleRemoteOutput(QByteArray)));
if (d->qmlDebugging && !d->cppDebugging) {
connect(runner(), SIGNAL(remoteProcessStarted()),
SLOT(handleRemoteProcessStarted()));
}
const QString &remoteExe = runner()->remoteExecutable();
QString args = runner()->arguments();
if (d->qmlDebugging) {
args += QString::fromLatin1(" -qmljsdebugger=port:%1,block")
.arg(d->qmlPort);
}
const QHostAddress peerAddress = runner()->connection()->connectionInfo().peerAddress;
QString peerAddressString = peerAddress.toString();
if (peerAddress.protocol() == QAbstractSocket::IPv6Protocol)
peerAddressString.prepend(QLatin1Char('[')).append(QLatin1Char(']'));
const QString remoteCommandLine = (d->qmlDebugging && !d->cppDebugging)
? QString::fromLatin1("%1 %2 %3").arg(runner()->commandPrefix()).arg(remoteExe).arg(args)
: QString::fromLatin1("%1 gdbserver %5:%2 %3 %4").arg(runner()->commandPrefix())
.arg(d->gdbServerPort).arg(remoteExe).arg(args).arg(peerAddressString);
connect(runner(), SIGNAL(remoteProcessFinished(qint64)),
SLOT(handleRemoteProcessFinished(qint64)));
runner()->startExecution(remoteCommandLine.toUtf8());
}
void AbstractRemoteLinuxDebugSupport::handleRemoteProcessFinished(qint64 exitCode)
{
if (!d->engine || d->state == Inactive)
return;
if (d->state == Debugging) {
// The QML engine does not realize on its own that the application has finished.
if (d->qmlDebugging && !d->cppDebugging)
d->engine->quitDebugger();
else if (exitCode != 0)
d->engine->notifyInferiorIll();
} else {
const QString errorMsg = (d->qmlDebugging && !d->cppDebugging)
? tr("Remote application failed with exit code %1.").arg(exitCode)
: tr("The gdbserver process closed unexpectedly.");
d->engine->notifyEngineRemoteSetupFailed(errorMsg);
}
}
void AbstractRemoteLinuxDebugSupport::handleDebuggingFinished()
{
setFinished();
}
void AbstractRemoteLinuxDebugSupport::handleRemoteOutput(const QByteArray &output)
{
QTC_ASSERT(d->state == Inactive || d->state == Debugging, return);
showMessage(QString::fromUtf8(output), AppOutput);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteErrorOutput(const QByteArray &output)
{
QTC_ASSERT(d->state == Inactive || d->state == StartingRemoteProcess || d->state == Debugging,
return);
if (!d->engine)
return;
showMessage(QString::fromUtf8(output), AppOutput);
if (d->state == StartingRemoteProcess && d->cppDebugging) {
d->gdbserverOutput += output;
if (d->gdbserverOutput.contains("Listening on port")) {
handleAdapterSetupDone();
d->gdbserverOutput.clear();
}
}
}
void AbstractRemoteLinuxDebugSupport::handleProgressReport(const QString &progressOutput)
{
showMessage(progressOutput + QLatin1Char('\n'), AppStuff);
}
void AbstractRemoteLinuxDebugSupport::handleAdapterSetupFailed(const QString &error)
{
setFinished();
d->engine->notifyEngineRemoteSetupFailed(tr("Initial setup failed: %1").arg(error));
}
void AbstractRemoteLinuxDebugSupport::handleAdapterSetupDone()
{
d->state = Debugging;
d->engine->notifyEngineRemoteSetupDone(d->gdbServerPort, d->qmlPort);
}
void AbstractRemoteLinuxDebugSupport::handleRemoteProcessStarted()
{
Q_ASSERT(d->qmlDebugging && !d->cppDebugging);
QTC_ASSERT(d->state == StartingRemoteProcess, return);
handleAdapterSetupDone();
}
void AbstractRemoteLinuxDebugSupport::setFinished()
{
if (d->state == Inactive)
return;
d->state = Inactive;
runner()->stop();
}
bool AbstractRemoteLinuxDebugSupport::setPort(int &port)
{
port = runner()->usedPortsGatherer()->getNextFreePort(runner()->freePorts());
if (port == -1) {
handleAdapterSetupFailed(tr("Not enough free ports on device for debugging."));
return false;
}
return true;
}
RemoteLinuxDebugSupport::RemoteLinuxDebugSupport(RemoteLinuxRunConfiguration *runConfig,
DebuggerEngine *engine)
: AbstractRemoteLinuxDebugSupport(runConfig, engine),
d(new RemoteLinuxDebugSupportPrivate(runConfig))
{
}
RemoteLinuxDebugSupport::~RemoteLinuxDebugSupport()
{
delete d;
}
AbstractRemoteLinuxApplicationRunner *RemoteLinuxDebugSupport::runner() const
{
return &d->runner;
}
} // namespace RemoteLinux
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef MONEY_H
#define MONEY_H
#include <string>
#include <ostream>
#include "utils.hpp"
namespace budget {
constexpr const int SCALE = 100;
struct money {
long value;
money() : value(0) {
//Nothing to init
}
explicit money(int dollars) : value(dollars * SCALE) {
//Nothing to init
}
money(int dollars, int cents) : value(dollars * SCALE + cents) {
//Nothing to init
}
money operator+(const money& rhs) const {
money new_money = *this;
new_money.value += rhs.value;
return new_money;
}
money& operator+=(const money& rhs){
value += rhs.value;
return *this;
}
money operator-(const money& rhs) const {
money new_money = *this;
new_money.value -= rhs.value;
return new_money;
}
money& operator-=(const money& rhs){
value -= rhs.value;
return *this;
}
money operator*(double factor) const {
money new_money = *this;
new_money.value *= factor;
return new_money;
}
money& operator*=(double factor){
value *= factor;
return *this;
}
money operator*(int factor) const {
money new_money = *this;
new_money.value *= factor;
return new_money;
}
money& operator*=(int factor){
value *= factor;
return *this;
}
money operator/(int factor) const {
money new_money = *this;
new_money.value /= factor;
return new_money;
}
money& operator/=(int factor){
value /= factor;
return *this;
}
bool operator==(const budget::money& rhs) const {
return value == rhs.value;
}
bool operator!=(const budget::money& rhs) const {
return value != rhs.value;
}
bool operator<(const budget::money& rhs) const {
return value < rhs.value;
}
bool operator<=(const budget::money& rhs) const {
return value < rhs.value;
}
bool operator>(const budget::money& rhs) const {
return value > rhs.value;
}
bool operator>=(const budget::money& rhs) const {
return value >= rhs.value;
}
int cents() const {
return std::abs(value % SCALE);
}
int dollars() const {
return value / SCALE;
}
bool positive() const {
return value > 0;
}
bool negative() const {
return value < 0;
}
bool zero() const {
return value == 0;
}
};
std::ostream& operator<<(std::ostream& stream, const money& amount);
money parse_money(const std::string& money_string);
money random_money(size_t min, size_t max);
std::string random_name(size_t length);
template<>
inline std::string to_string(money amount){
std::stringstream stream;
stream << amount;
return stream.str();
}
template<typename InputIt, typename Functor>
inline budget::money accumulate_amount_if(InputIt first, InputIt last, Functor f){
budget::money init;
for (; first != last; ++first) {
if(f(*first)){
init = init + first->amount;
}
}
return init;
}
template<typename T, typename Functor>
inline budget::money accumulate_amount_if(std::vector<T>& container, Functor f){
return accumulate_amount_if(container.begin(), container.end(), f);
}
} //end of namespace budget
#endif
<commit_msg>Add conversion to bool<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef MONEY_H
#define MONEY_H
#include <string>
#include <ostream>
#include "utils.hpp"
namespace budget {
constexpr const int SCALE = 100;
struct money {
long value;
money() : value(0) {
//Nothing to init
}
explicit money(int dollars) : value(dollars * SCALE) {
//Nothing to init
}
money(int dollars, int cents) : value(dollars * SCALE + cents) {
//Nothing to init
}
money operator+(const money& rhs) const {
money new_money = *this;
new_money.value += rhs.value;
return new_money;
}
money& operator+=(const money& rhs){
value += rhs.value;
return *this;
}
money operator-(const money& rhs) const {
money new_money = *this;
new_money.value -= rhs.value;
return new_money;
}
money& operator-=(const money& rhs){
value -= rhs.value;
return *this;
}
money operator*(double factor) const {
money new_money = *this;
new_money.value *= factor;
return new_money;
}
money& operator*=(double factor){
value *= factor;
return *this;
}
money operator*(int factor) const {
money new_money = *this;
new_money.value *= factor;
return new_money;
}
money& operator*=(int factor){
value *= factor;
return *this;
}
money operator/(int factor) const {
money new_money = *this;
new_money.value /= factor;
return new_money;
}
money& operator/=(int factor){
value /= factor;
return *this;
}
bool operator==(const budget::money& rhs) const {
return value == rhs.value;
}
bool operator!=(const budget::money& rhs) const {
return value != rhs.value;
}
bool operator<(const budget::money& rhs) const {
return value < rhs.value;
}
bool operator<=(const budget::money& rhs) const {
return value < rhs.value;
}
bool operator>(const budget::money& rhs) const {
return value > rhs.value;
}
bool operator>=(const budget::money& rhs) const {
return value >= rhs.value;
}
int cents() const {
return std::abs(value % SCALE);
}
int dollars() const {
return value / SCALE;
}
bool positive() const {
return value > 0;
}
bool negative() const {
return value < 0;
}
bool zero() const {
return value == 0;
}
operator bool() const {
return value;
}
};
std::ostream& operator<<(std::ostream& stream, const money& amount);
money parse_money(const std::string& money_string);
money random_money(size_t min, size_t max);
std::string random_name(size_t length);
template<>
inline std::string to_string(money amount){
std::stringstream stream;
stream << amount;
return stream.str();
}
template<typename InputIt, typename Functor>
inline budget::money accumulate_amount_if(InputIt first, InputIt last, Functor f){
budget::money init;
for (; first != last; ++first) {
if(f(*first)){
init = init + first->amount;
}
}
return init;
}
template<typename T, typename Functor>
inline budget::money accumulate_amount_if(std::vector<T>& container, Functor f){
return accumulate_amount_if(container.begin(), container.end(), f);
}
} //end of namespace budget
#endif
<|endoftext|> |
<commit_before>class PO2_ON {
title = " Enemy - OCB Patrol Ops 2";
values[]= {1, 0};
texts[]= {"On","Off"};
default = 1;
};
class MISSIONTYPE_PO { // MISSION TYPE
title= " Mission Type Patrol Ops";
values[]={0,1,2,3,4,5,6,7,8};
default=7;
texts[]={"Off","Domination","Reconstruction","Search and Rescue","Mix Standard","Mix Hard","Target Capture","MSO Auto-tasking","MSO Sniper Operations"};
};
class MISSIONTYPE_AIR { // MISSION TYPE
title= " Mission Type Air Ops";
values[]={0,1};
default=1;
texts[]={"Off","Experimental"};
};
class MISSIONCOUNT { // MISSION COUNT
title=" Number of Missions";
values[]={1,3,5,7,9,15,20,9999};
default=9999;
texts[]={"1","3","5","7","9","15","20","unlimited"};
};
class PO2_EFACTION { // ENEMY FACTION
title=" Enemy Faction";
values[]={0,1,2,3,4,5,6};
default=0;
texts[]={"Takistani Army","Takistani Guerillas","Russia","Guerillas","CWR2 RU","CWR2 FIA","Tigerianne"};
};
class PO2_IFACTION { // INS FACTION
title=" Insurgents Faction";
values[]={0,1,2,3};
default=0;
texts[]={"Takistani Insurgents","Takistani Guerillas","European Insurgents","Guerillas"};
};
class MISSIONDIFF { // MISSION Difficulty
title=" Difficulty";
values[]={1,2,3,4};
default=2;
texts[]={"Easy","Medium","Hard","Experienced"};
};
class AMBAIRPARTOLS { // AMBiENT Air Patrols
title=" Ambient Air Patrols";
values[]={0,1};
default=0;
texts[]={"Off","On"};
};
<commit_msg>[ENEMY] Stated in Params that RMM_EnPop is needed for autotasking<commit_after>class PO2_ON {
title = " Enemy - OCB Patrol Ops 2";
values[]= {1, 0};
texts[]= {"On","Off"};
default = 1;
};
class MISSIONTYPE_PO { // MISSION TYPE
title= " Mission Type Patrol Ops";
values[]={0,1,2,3,4,5,6,7,8};
default=7;
texts[]={"Off","Domination","Reconstruction","Search and Rescue","Mix Standard","Mix Hard","Target Capture","MSO Auto (needs RMM_Enpop)","MSO Sniper Operations"};
};
class MISSIONTYPE_AIR { // MISSION TYPE
title= " Mission Type Air Ops";
values[]={0,1};
default=1;
texts[]={"Off","Experimental"};
};
class MISSIONCOUNT { // MISSION COUNT
title=" Number of Missions";
values[]={1,3,5,7,9,15,20,9999};
default=9999;
texts[]={"1","3","5","7","9","15","20","unlimited"};
};
class PO2_EFACTION { // ENEMY FACTION
title=" Enemy Faction";
values[]={0,1,2,3,4,5,6};
default=0;
texts[]={"Takistani Army","Takistani Guerillas","Russia","Guerillas","CWR2 RU","CWR2 FIA","Tigerianne"};
};
class PO2_IFACTION { // INS FACTION
title=" Insurgents Faction";
values[]={0,1,2,3};
default=0;
texts[]={"Takistani Insurgents","Takistani Guerillas","European Insurgents","Guerillas"};
};
class MISSIONDIFF { // MISSION Difficulty
title=" Difficulty";
values[]={1,2,3,4};
default=2;
texts[]={"Easy","Medium","Hard","Experienced"};
};
class AMBAIRPARTOLS { // AMBiENT Air Patrols
title=" Ambient Air Patrols";
values[]={0,1};
default=0;
texts[]={"Off","On"};
};
<|endoftext|> |
<commit_before>#include <cstdio>
#include <string>
#include <random>
#include <iostream>
#include "rocksdb/db.h"
#include "rocksdb/statistics.h"
#include "rocksdb/perf_context.h"
#include "rocksdb/utilities/spatial_db.h"
#include "rocksdb/env.h"
using namespace rocksdb;
using namespace spatial;
using std::pair;
using std::vector;
using std::cout;
using std::endl;
std::string kDBPath;
uint32_t kN = 10;
uint32_t kZoomLevels = 10;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> uniform(0,100);
bool kRamDisk = true;
void RandomCoords(int n, vector<Coord<double>> *result) {
result->clear();
for (int i=0; i<n; ++i) {
double x = uniform(gen);
double y = uniform(gen);
result->push_back(Coord<double>(x, y));
}
}
void RandomBoxes(int n,
std::uniform_real_distribution<> dist,
vector<BoundingBox<double>> *result) {
result->clear();
for (int i=0; i<n; ++i) {
double minx = uniform(gen);
double miny = uniform(gen);
double maxx = std::min(100.0, dist(gen) + minx);
double maxy = std::min(100.0, dist(gen) + miny);
result->push_back(BoundingBox<double>(minx, miny, maxx, maxy));
}
}
DBOptions GetDBOptions(const SpatialDBOptions& options) {
DBOptions db_options;
db_options.IncreaseParallelism(3);
db_options.statistics = rocksdb::CreateDBStatistics();
if (options.bulk_load) {
db_options.stats_dump_period_sec = 600;
db_options.disableDataSync = true;
} else {
db_options.stats_dump_period_sec = 1800; // 30min
}
return db_options;
}
int main(int argc, char** argv) {
for (int i=1; i<argc; ++i) {
if (strncmp(argv[i], "--db=", 5) == 0) {
kDBPath = argv[i] + 5;
}
else if (strncmp(argv[i], "--n=", 4) == 0) {
kN = atoi(argv[i] + 4);
}
else {
exit(1);
}
}
DestroyDB(kDBPath, Options());
const BoundingBox<double> outer_box(0, 0, 100, 100);
SpatialDBOptions options;
DBOptions db_options = GetDBOptions(options);
db_options.allow_mmap_writes = true;
db_options.allow_mmap_reads = true;
SetPerfLevel(kEnableTime);
rocksdb::Status s = SpatialDB::Create(db_options, kDBPath, outer_box, kZoomLevels, kRamDisk);
cout << s.ToString() << endl;
assert(s.ok());
SpatialDB* db;
s = SpatialDB::Open(db_options, kDBPath, &db, false, kZoomLevels, kRamDisk);
cout << s.ToString() << endl;
assert(s.ok());
cout << "created DB" << endl;
vector<Coord<double>> data;
RandomCoords(kN, &data);
cout << "generated data" << endl;
vector<rocksdb::Slice> blobs(kN, "blob");
vector<FeatureSet> feature_sets(kN);
rocksdb::WriteOptions write_options;
write_options.disableWAL = true;
s = db->BulkInsert(write_options, data, blobs, feature_sets);
assert(s.ok());
cout << "inserted data" << endl;
auto dbstats = db_options.statistics.get();
printf("STATISTCS:\n %s", dbstats->ToString().c_str());
// db->Compact();
return 0;
}<commit_msg>empty<commit_after>#include <cstdio>
#include <string>
#include <random>
#include <iostream>
#include "rocksdb/db.h"
#include "rocksdb/statistics.h"
#include "rocksdb/perf_context.h"
#include "rocksdb/utilities/spatial_db.h"
#include "rocksdb/env.h"
using namespace rocksdb;
using namespace spatial;
using std::pair;
using std::vector;
using std::cout;
using std::endl;
std::string kDBPath;
uint32_t kN = 10;
uint32_t kZoomLevels = 10;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> uniform(0,100);
bool kRamDisk = true;
void RandomCoords(int n, vector<Coord<double>> *result) {
result->clear();
for (int i=0; i<n; ++i) {
double x = uniform(gen);
double y = uniform(gen);
result->push_back(Coord<double>(x, y));
}
}
void RandomBoxes(int n,
std::uniform_real_distribution<> dist,
vector<BoundingBox<double>> *result) {
result->clear();
for (int i=0; i<n; ++i) {
double minx = uniform(gen);
double miny = uniform(gen);
double maxx = std::min(100.0, dist(gen) + minx);
double maxy = std::min(100.0, dist(gen) + miny);
result->push_back(BoundingBox<double>(minx, miny, maxx, maxy));
}
}
DBOptions GetDBOptions(const SpatialDBOptions& options) {
DBOptions db_options;
db_options.IncreaseParallelism(3);
db_options.statistics = rocksdb::CreateDBStatistics();
if (options.bulk_load) {
db_options.stats_dump_period_sec = 600;
db_options.disableDataSync = true;
} else {
db_options.stats_dump_period_sec = 1800; // 30min
}
return db_options;
}
int main(int argc, char** argv) {
for (int i=1; i<argc; ++i) {
if (strncmp(argv[i], "--db=", 5) == 0) {
kDBPath = argv[i] + 5;
}
else if (strncmp(argv[i], "--n=", 4) == 0) {
kN = atoi(argv[i] + 4);
}
else {
exit(1);
}
}
DestroyDB(kDBPath, Options());
const BoundingBox<double> outer_box(0, 0, 100, 100);
SpatialDBOptions options;
DBOptions db_options = GetDBOptions(options);
db_options.allow_mmap_writes = true;
db_options.allow_mmap_reads = true;
SetPerfLevel(kEnableTime);
rocksdb::Status s = SpatialDB::Create(db_options, kDBPath, outer_box, kZoomLevels, kRamDisk);
cout << s.ToString() << endl;
assert(s.ok());
SpatialDB* db;
s = SpatialDB::Open(db_options, kDBPath, &db, false, kZoomLevels, kRamDisk);
cout << s.ToString() << endl;
assert(s.ok());
cout << "created DB" << endl;
vector<Coord<double>> data;
RandomCoords(kN, &data);
cout << "generated data" << endl;
vector<rocksdb::Slice> blobs(kN, "blob");
vector<FeatureSet> feature_sets(kN);
rocksdb::WriteOptions write_options;
write_options.disableWAL = true;
s = db->BulkInsert(write_options, data, blobs, feature_sets);
assert(s.ok());
cout << "inserted data" << endl;
LogFlush(db_options.info_log);
return 0;
}<|endoftext|> |
<commit_before>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
main_thread->async( [&]{ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<commit_msg>Log data-dir on startup<commit_after>#include "ClientWrapper.hpp"
#include <bts/net/upnp.hpp>
#include <bts/db/exception.hpp>
#include <QApplication>
#include <QResource>
#include <QSettings>
#include <QJsonDocument>
#include <QUrl>
#include <QMessageBox>
#include <iostream>
void get_htdocs_file( const fc::path& filename, const fc::http::server::response& r )
{
std::cout << filename.generic_string() << "\n";
QResource file_to_send( ("/htdocs/htdocs/" + filename.generic_string()).c_str() );
if( !file_to_send.data() )
{
std::string not_found = "this is not the file you are looking for: " + filename.generic_string();
r.set_status( fc::http::reply::NotFound );
r.set_length( not_found.size() );
r.write( not_found.c_str(), not_found.size() );
return;
}
r.set_status( fc::http::reply::OK );
if( file_to_send.isCompressed() )
{
auto data = qUncompress( file_to_send.data(), file_to_send.size() );
r.set_length( data.size() );
r.write( (const char*)data.data(), data.size() );
}
else
{
r.set_length( file_to_send.size() );
r.write( (const char*)file_to_send.data(), file_to_send.size() );
}
}
ClientWrapper::ClientWrapper(QObject *parent)
: QObject(parent),
_bitshares_thread("bitshares")
{
}
ClientWrapper::~ClientWrapper()
{
try {
_init_complete.wait();
_bitshares_thread.async( [this](){ _client->stop(); _client.reset(); } ).wait();
} catch ( ... )
{
elog( "uncaught exception" );
}
}
void ClientWrapper::initialize()
{
QSettings settings("BitShares", BTS_BLOCKCHAIN_NAME);
bool upnp = settings.value( "network/p2p/use_upnp", true ).toBool();
uint32_t p2pport = settings.value( "network/p2p/port", BTS_NETWORK_DEFAULT_P2P_PORT ).toInt();
std::string default_wallet_name = settings.value("client/default_wallet_name", "default").toString().toStdString();
settings.setValue("client/default_wallet_name", QString::fromStdString(default_wallet_name));
Q_UNUSED(p2pport);
#ifdef _WIN32
_cfg.rpc.rpc_user = "";
_cfg.rpc.rpc_password = "";
#else
_cfg.rpc.rpc_user = "randomuser";
_cfg.rpc.rpc_password = fc::variant(fc::ecc::private_key::generate()).as_string();
#endif
_cfg.rpc.httpd_endpoint = fc::ip::endpoint::from_string( "127.0.0.1:9999" );
_cfg.rpc.httpd_endpoint.set_port(0);
ilog( "config: ${d}", ("d", fc::json::to_pretty_string(_cfg) ) );
auto data_dir = fc::app_path() / BTS_BLOCKCHAIN_NAME;
int data_dir_index = qApp->arguments().indexOf("--data-dir");
if (data_dir_index != -1 && qApp->arguments().size() > data_dir_index+1)
data_dir = qApp->arguments()[data_dir_index+1].toStdString();
wlog("Starting client with data-dir: ${ddir}", ("ddir", data_dir));
fc::thread* main_thread = &fc::thread::current();
_init_complete = _bitshares_thread.async( [this,main_thread,data_dir,upnp,p2pport,default_wallet_name](){
try
{
main_thread->async( [&]{ Q_EMIT status_update(tr("Starting %1 client").arg(qApp->applicationName())); });
_client = std::make_shared<bts::client::client>();
_client->open( data_dir );
// setup RPC / HTTP services
main_thread->async( [&]{ Q_EMIT status_update(tr("Loading interface")); });
_client->get_rpc_server()->set_http_file_callback( get_htdocs_file );
_client->get_rpc_server()->configure_http( _cfg.rpc );
_actual_httpd_endpoint = _client->get_rpc_server()->get_httpd_endpoint();
// load config for p2p node.. creates cli
_client->configure( data_dir );
_client->init_cli();
main_thread->async( [&]{ Q_EMIT status_update(tr("Connecting to %1 network").arg(qApp->applicationName())); });
_client->listen_on_port(0, false /*don't wait if not available*/);
fc::ip::endpoint actual_p2p_endpoint = _client->get_p2p_listening_endpoint();
_client->set_daemon_mode(true);
_client->start();
if( !_actual_httpd_endpoint )
{
main_thread->async( [&]{ Q_EMIT error( tr("Unable to start HTTP server...")); });
}
_client->start_networking([=]{
for (std::string default_peer : _cfg.default_peers)
_client->connect_to_peer(default_peer);
});
main_thread->async( [&]{ Q_EMIT status_update(tr("Forwarding port")); });
if( upnp )
{
auto upnp_service = new bts::net::upnp_service();
upnp_service->map_port( actual_p2p_endpoint.port() );
}
try
{
_client->wallet_open(default_wallet_name);
}
catch(...)
{}
main_thread->async( [&]{ Q_EMIT initialized(); });
}
catch (const bts::db::db_in_use_exception&)
{
main_thread->async( [&]{ Q_EMIT error( tr("An instance of %1 is already running! Please close it and try again.").arg(qApp->applicationName())); });
}
catch (const fc::exception &e)
{
ilog("Failure when attempting to initialize client");
main_thread->async( [&]{ Q_EMIT error( tr("An error occurred while trying to start")); });
}
});
}
void ClientWrapper::close()
{
_bitshares_thread.async([this]{
_client->get_wallet()->close();
_client->get_chain()->close();
_client->get_rpc_server()->shutdown_rpc_server();
_client->get_rpc_server()->wait_till_rpc_server_shutdown();
}).wait();
}
QUrl ClientWrapper::http_url() const
{
QUrl url = QString::fromStdString("http://" + std::string( *_actual_httpd_endpoint ) );
url.setUserName(_cfg.rpc.rpc_user.c_str() );
url.setPassword(_cfg.rpc.rpc_password.c_str() );
return url;
}
QVariant ClientWrapper::get_info( )
{
fc::variant_object result = _bitshares_thread.async( [this](){ return _client->get_info(); }).wait();
std::string sresult = fc::json::to_string( result );
return QJsonDocument::fromJson( QByteArray( sresult.c_str(), sresult.length() ) ).toVariant();
}
QString ClientWrapper::get_http_auth_token()
{
QByteArray result = _cfg.rpc.rpc_user.c_str();
result += ":";
result += _cfg.rpc.rpc_password.c_str();
return result.toBase64( QByteArray::Base64Encoding | QByteArray::KeepTrailingEquals );
}
void ClientWrapper::confirm_and_set_approval(QString delegate_name, bool approve)
{
auto account = get_client()->blockchain_get_account(delegate_name.toStdString());
if( account.valid() && account->is_delegate() )
{
if( QMessageBox::question(nullptr,
tr("Set Delegate Approval"),
tr("Would you like to update approval rating of Delegate %1 to %2?")
.arg(delegate_name)
.arg(approve?"Approve":"Disapprove")
)
== QMessageBox::Yes )
get_client()->wallet_account_set_approval(delegate_name.toStdString(), approve);
}
else
QMessageBox::warning(nullptr, tr("Invalid Account"), tr("Account %1 is not a delegate, so its approval cannot be set.").arg(delegate_name));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <uavcan/time.hpp>
#include <uavcan/protocol/debug/LogMessage.hpp>
#include <uavcan/marshal/char_array_formatter.hpp>
#include <uavcan/node/publisher.hpp>
#if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11)
# error UAVCAN_CPP_VERSION
#endif
namespace uavcan
{
class ILogSink
{
public:
typedef typename StorageType<typename protocol::debug::LogLevel::FieldTypes::value>::Type LogLevel;
virtual ~ILogSink() { }
/**
* Logger will not sink messages with level lower than returned by this method.
*/
virtual LogLevel getLogLevel() const = 0;
/**
* Logger will call this method for every log message with level not less than the current level of this sink.
*/
virtual void log(const protocol::debug::LogMessage& message) = 0;
};
class Logger
{
public:
typedef ILogSink::LogLevel LogLevel;
static const LogLevel LevelAboveAll = (protocol::debug::LogLevel::FieldTypes::value::BitLen << 1) - 1;
private:
enum { DefaultTxTimeoutMs = 2000 };
Publisher<protocol::debug::LogMessage> logmsg_pub_;
protocol::debug::LogMessage msg_buf_;
LogLevel level_;
ILogSink* external_sink_;
LogLevel getExternalSinkLevel() const;
public:
Logger(INode& node)
: logmsg_pub_(node)
, external_sink_(NULL)
{
level_ = protocol::debug::LogLevel::ERROR;
setTxTimeout(MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
assert(getTxTimeout() == MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
}
int log(const protocol::debug::LogMessage& message);
LogLevel getLevel() const { return level_; }
void setLevel(LogLevel level) { level_ = level; }
ILogSink* getExternalSink() const { return external_sink_; }
void setExternalSink(ILogSink* sink) { external_sink_ = sink; }
MonotonicDuration getTxTimeout() const { return logmsg_pub_.getTxTimeout(); }
void setTxTimeout(MonotonicDuration val) { logmsg_pub_.setTxTimeout(val); }
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
template <typename... Args>
int log(LogLevel level, const char* source, const char* format, Args... args)
{
if (level >= level_ || level >= getExternalSinkLevel())
{
msg_buf_.level.value = level;
msg_buf_.source = source;
msg_buf_.text.clear();
CharArrayFormatter<typename protocol::debug::LogMessage::FieldTypes::text> formatter(msg_buf_.text);
formatter.write(format, args...);
return log(msg_buf_);
}
return 0;
}
template <typename... Args>
inline int logDebug(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::DEBUG, source, format, args...);
}
template <typename... Args>
inline int logInfo(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::INFO, source, format, args...);
}
template <typename... Args>
inline int logWarning(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::WARNING, source, format, args...);
}
template <typename... Args>
inline int logError(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::ERROR, source, format, args...);
}
#else
int log(LogLevel level, const char* source, const char* text)
{
if (level >= level_ || level >= getExternalSinkLevel())
{
msg_buf_.level.value = level;
msg_buf_.source = source;
msg_buf_.text = text;
return log(msg_buf_);
}
return 0;
}
int logDebug(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::DEBUG, source, text);
}
int logInfo(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::INFO, source, text);
}
int logWarning(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::WARNING, source, text);
}
int logError(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::ERROR, source, text);
}
#endif
};
}
<commit_msg>Fix for Logger::LogLevelAboveAll<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <uavcan/time.hpp>
#include <uavcan/protocol/debug/LogMessage.hpp>
#include <uavcan/marshal/char_array_formatter.hpp>
#include <uavcan/node/publisher.hpp>
#if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11)
# error UAVCAN_CPP_VERSION
#endif
namespace uavcan
{
class ILogSink
{
public:
typedef typename StorageType<typename protocol::debug::LogLevel::FieldTypes::value>::Type LogLevel;
virtual ~ILogSink() { }
/**
* Logger will not sink messages with level lower than returned by this method.
*/
virtual LogLevel getLogLevel() const = 0;
/**
* Logger will call this method for every log message with level not less than the current level of this sink.
*/
virtual void log(const protocol::debug::LogMessage& message) = 0;
};
class Logger
{
public:
typedef ILogSink::LogLevel LogLevel;
static const LogLevel LevelAboveAll = (1 << protocol::debug::LogLevel::FieldTypes::value::BitLen) - 1;
private:
enum { DefaultTxTimeoutMs = 2000 };
Publisher<protocol::debug::LogMessage> logmsg_pub_;
protocol::debug::LogMessage msg_buf_;
LogLevel level_;
ILogSink* external_sink_;
LogLevel getExternalSinkLevel() const;
public:
Logger(INode& node)
: logmsg_pub_(node)
, external_sink_(NULL)
{
level_ = protocol::debug::LogLevel::ERROR;
setTxTimeout(MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
assert(getTxTimeout() == MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
}
int log(const protocol::debug::LogMessage& message);
LogLevel getLevel() const { return level_; }
void setLevel(LogLevel level) { level_ = level; }
ILogSink* getExternalSink() const { return external_sink_; }
void setExternalSink(ILogSink* sink) { external_sink_ = sink; }
MonotonicDuration getTxTimeout() const { return logmsg_pub_.getTxTimeout(); }
void setTxTimeout(MonotonicDuration val) { logmsg_pub_.setTxTimeout(val); }
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
template <typename... Args>
int log(LogLevel level, const char* source, const char* format, Args... args)
{
if (level >= level_ || level >= getExternalSinkLevel())
{
msg_buf_.level.value = level;
msg_buf_.source = source;
msg_buf_.text.clear();
CharArrayFormatter<typename protocol::debug::LogMessage::FieldTypes::text> formatter(msg_buf_.text);
formatter.write(format, args...);
return log(msg_buf_);
}
return 0;
}
template <typename... Args>
inline int logDebug(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::DEBUG, source, format, args...);
}
template <typename... Args>
inline int logInfo(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::INFO, source, format, args...);
}
template <typename... Args>
inline int logWarning(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::WARNING, source, format, args...);
}
template <typename... Args>
inline int logError(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::ERROR, source, format, args...);
}
#else
int log(LogLevel level, const char* source, const char* text)
{
if (level >= level_ || level >= getExternalSinkLevel())
{
msg_buf_.level.value = level;
msg_buf_.source = source;
msg_buf_.text = text;
return log(msg_buf_);
}
return 0;
}
int logDebug(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::DEBUG, source, text);
}
int logInfo(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::INFO, source, text);
}
int logWarning(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::WARNING, source, text);
}
int logError(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::ERROR, source, text);
}
#endif
};
}
<|endoftext|> |
<commit_before>/* linbox/algorithms/gauss-solve.inl
* Copyright (C) LinBox 2008
*
* Written by Jean-Guillaume Dumas <[email protected]>
* Time-stamp: <16 Jun 10 14:21:31 [email protected]>
*
* See COPYING for license information.
*/
#ifndef __GAUSS_NULLSPACE_INL
#define __GAUSS_NULLSPACE_INL
#include "linbox/algorithms/gauss.h"
#include "linbox/algorithms/triangular-solve.h"
#include "linbox/blackbox/permutation.h"
namespace LinBox
{
// U is supposed full rank upper triangular
template <class _Field>
template <class Matrix, class Perm, class Block> inline Block&
GaussDomain<_Field>::nullspacebasis(Block& x, unsigned long rank, const Matrix& U, const Perm& P) const {
if (rank == 0) {
for(size_t i=0; i<U.coldim(); ++i)
x.setEntry(i,i,_F.one);
} else {
unsigned long nullity = U.coldim()-rank;
if (nullity != 0) {
// compute U1 and U2T s.t. U = [ U1 | -U2T^T ]
Matrix U1(_F,rank,rank);
Matrix U2T(_F,nullity,rank);
for(typename Matrix::ConstRawIndexedIterator uit=U.rawIndexedBegin();
uit != U.rawIndexedEnd(); ++uit) {
if (uit.colIndex()<rank)
U1.setEntry(uit.rowIndex(),uit.colIndex(),uit.value());
else
U2T.setEntry(uit.colIndex()-rank,uit.rowIndex(),uit.value());
}
for(typename Matrix::RawIterator u2it=U2T.rawBegin();
u2it != U2T.rawEnd(); ++u2it)
_F.negin(*u2it);
// Compute the basis vector by vector
typedef Sparse_Vector< typename _Field::Element > SparseVect;
for(size_t i=0; i<nullity; ++i) {
SparseVect W1Ti;
// Solve for upper part of basis
upperTriangularSparseSolve(W1Ti, U1, U2T[i]);
// Add identity for lower part
W1Ti.push_back( typename SparseVect::Element(rank+i, _F.one ) );
for(size_t j=0; j<W1Ti.size(); ++j) {
// P.applyTranspose(x[i],W1T[i]);
// Transposein(x)
x.setEntry( P.getStorage()[ W1Ti[j].first ], i, W1Ti[j].second );
}
}
}
}
// x.write( std::cerr << "X:=", FORMAT_MAPLE ) << ';' << std::endl;
return x;
}
template <class Matrix>
inline bool nextnonzero(size_t& k, size_t Ni, const Matrix& A) {
for(++k; k<Ni; ++k)
if (A[k].size() > 0) return true;
return false;
}
template <class _Field>
template <class Matrix, class Block> inline Block&
GaussDomain<_Field>::nullspacebasisin(Block& x, Matrix& A) const {
typename Field::Element det;
unsigned long rank;
size_t Ni(A.rowdim()),Nj(A.coldim());
Permutation<Field> P(Nj,_F);
// A.write( std::cerr << "A:=", FORMAT_MAPLE ) << ';' << std::endl;
this->InPlaceLinearPivoting(rank, det, A, P, Ni, Nj );
// P.write( std::cerr << "P:=", FORMAT_MAPLE ) << ';' << std::endl;
// A.write( std::cerr << "Ua:=", FORMAT_MAPLE ) << ';' << std::endl;
for(size_t i=0; i< Ni; ++i) {
if (A[i].size() == 0) {
size_t j(i);
if (nextnonzero(j,Ni,A)) {
A[i] = A[j];
A[j].resize(0);
} else {
break;
}
}
}
// A.write( std::cerr << "Ub:=", FORMAT_MAPLE ) << ';' << std::endl;
return this->nullspacebasis(x, rank, A, P);
}
} // namespace LinBox
#endif // __GAUSS_NULLSPACE_INL
<commit_msg>removed recopy of U1 part<commit_after>/* linbox/algorithms/gauss-solve.inl
* Copyright (C) LinBox 2008
*
* Written by Jean-Guillaume Dumas <[email protected]>
* Time-stamp: <18 Jun 10 10:39:25 [email protected]>
*
* See COPYING for license information.
*/
#ifndef __GAUSS_NULLSPACE_INL
#define __GAUSS_NULLSPACE_INL
#include "linbox/algorithms/gauss.h"
#include "linbox/algorithms/triangular-solve.h"
#include "linbox/blackbox/permutation.h"
namespace LinBox
{
// U is supposed full rank upper triangular
template <class _Field>
template <class Matrix, class Perm, class Block> inline Block&
GaussDomain<_Field>::nullspacebasis(Block& x, unsigned long rank, const Matrix& U, const Perm& P) const {
if (rank == 0) {
for(size_t i=0; i<U.coldim(); ++i)
x.setEntry(i,i,_F.one);
} else {
unsigned long nullity = U.coldim()-rank;
if (nullity != 0) {
// compute U2T s.t. U = [ U1 | -U2T^T ]
Matrix U2T(_F,nullity,rank);
for(typename Matrix::ConstRawIndexedIterator uit=U.rawIndexedBegin();
uit != U.rawIndexedEnd(); ++uit) {
if (uit.colIndex() >= rank)
U2T.setEntry(uit.colIndex()-rank,uit.rowIndex(),uit.value());
}
for(typename Matrix::RawIterator u2it=U2T.rawBegin();
u2it != U2T.rawEnd(); ++u2it)
_F.negin(*u2it);
// Compute the basis vector by vector
typedef Sparse_Vector< typename _Field::Element > SparseVect;
for(size_t i=0; i<nullity; ++i) {
SparseVect W1Ti;
// Solve for upper part of basis
upperTriangularSparseSolve(W1Ti, rank, U, U2T[i]);
// Add identity for lower part
W1Ti.push_back( typename SparseVect::Element(rank+i, _F.one ) );
for(size_t j=0; j<W1Ti.size(); ++j) {
// P.applyTranspose(x[i],W1T[i]);
// Transposein(x)
x.setEntry( P.getStorage()[ W1Ti[j].first ], i, W1Ti[j].second );
}
}
}
}
// x.write( std::cerr << "X:=", FORMAT_MAPLE ) << ';' << std::endl;
return x;
}
template <class Matrix>
inline bool nextnonzero(size_t& k, size_t Ni, const Matrix& A) {
for(++k; k<Ni; ++k)
if (A[k].size() > 0) return true;
return false;
}
template <class _Field>
template <class Matrix, class Block> inline Block&
GaussDomain<_Field>::nullspacebasisin(Block& x, Matrix& A) const {
typename Field::Element det;
unsigned long rank;
size_t Ni(A.rowdim()),Nj(A.coldim());
Permutation<Field> P(Nj,_F);
// A.write( std::cerr << "A:=", FORMAT_MAPLE ) << ';' << std::endl;
this->InPlaceLinearPivoting(rank, det, A, P, Ni, Nj );
// P.write( std::cerr << "P:=", FORMAT_MAPLE ) << ';' << std::endl;
// A.write( std::cerr << "Ua:=", FORMAT_MAPLE ) << ';' << std::endl;
for(size_t i=0; i< Ni; ++i) {
if (A[i].size() == 0) {
size_t j(i);
if (nextnonzero(j,Ni,A)) {
A[i] = A[j];
A[j].resize(0);
} else {
break;
}
}
}
// A.write( std::cerr << "Ub:=", FORMAT_MAPLE ) << ';' << std::endl;
return this->nullspacebasis(x, rank, A, P);
}
} // namespace LinBox
#endif // __GAUSS_NULLSPACE_INL
<|endoftext|> |
<commit_before>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>
class bitset
{
public:
explicit bitset(size_t size) /*strong*/;
bitset(bitset const & other) = delete;
auto operator =(bitset const & other)->bitset & = delete;
bitset(bitset && other) = delete;
auto operator =(bitset && other)->bitset & = delete;
auto set(size_t index) /*strong*/ -> void;
auto reset(size_t index) /*strong*/ -> void;
auto test(size_t index) /*strong*/ -> bool;
auto size() /*noexcept*/ -> size_t;
auto counter() /*noexcept*/ -> size_t;
private:
std::unique_ptr<bool[]> ptr_;
size_t size_;
size_t counter_;
};
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0){}
auto bitset::set(size_t index)->void {
if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; }
else throw("bad_index");
}
auto bitset::reset(size_t index)->void {
if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; }
else throw("bad_index");
}
auto bitset::test(size_t index)->bool {
if (index >= 0 && index < size_) return !ptr_[index];
else throw("bad_index");
}
auto bitset::size()->size_t{ return size_; }
auto bitset::counter()->size_t{ return counter_; }
template <typename T>
class allocator{
public:
explicit allocator(std::size_t size = 0) /*strong*/;
allocator(allocator const & other) /*strong*/;
auto operator =(allocator const & other)->allocator & = delete;
~allocator();
auto resize() /*strong*/ -> void;
auto construct(T * ptr, T const & value) /*strong*/ -> void;
auto destroy(T * ptr) /*noexcept*/ -> void;
auto get() /*noexcept*/ -> T *;
auto get() const /*noexcept*/ -> T const *;
auto count() const /*noexcept*/ -> size_t;
auto full() const /*noexcept*/ -> bool;
auto empty() const /*noexcept*/ -> bool;
auto swap(allocator & other) /*noexcept*/ -> void;
private:
auto destroy(T * first, T * last) /*noexcept*/ -> void;
size_t count_;
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template<typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size)), count_(0) {}
template<typename T>
allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) {
for (size_t i = 0; i < other.count_; i++) if(map_->test(i)) construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator(){
if (this->count() > 0) {
destroy(ptr_, ptr_ + size_);
}
operator delete(ptr_);
}
template<typename T>
auto allocator<T>::resize()->void{
allocator<T> al(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; ++i) if (al.map_->test(i)) al.construct(al.get() + i, ptr_[i]);
al.swap(*this);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void{
if (ptr >= ptr_&&ptr < ptr_ + size_){
new(ptr)T(value);
map_->set(ptr - ptr_);
++count_;
}
else { throw("error"); }
}
template<typename T>
auto allocator<T>::destroy(T* ptr)->void{
if (!map_->test(ptr - ptr_) && ptr >= ptr_&&ptr <= ptr_ + this->count())
{
ptr->~T();
map_->reset(ptr - ptr_);
--count_;
}
}
template<typename T>
auto allocator<T>::get()-> T* { return ptr_; }
template<typename T>
auto allocator<T>::get() const -> T const * { return ptr_; }
template<typename T>
auto allocator<T>::count() const -> size_t{ return count_; }
template<typename T>
auto allocator<T>::full() const -> bool { return (map_->counter() == size_); }
template<typename T>
auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); }
template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void{
if (first >= ptr_&&last <= ptr_ + this->count())
for (; first != last; ++first) {
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::swap(allocator & other)->void{
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
std::swap(count_, other.count_);
}
template <typename T>
class stack {
public:
explicit stack(size_t size = 0);
stack(stack const & other); /*strong*/
auto operator =(stack const & other) /*strong*/ -> stack &;
auto empty() const /*noexcept*/ -> bool;
auto count() const /*noexcept*/ -> size_t;
auto push(T const & value) /*strong*/ -> void;
auto pop() /*strong*/ -> std::shared_ptr<T>;
//auto top()const -> const T&;
private:
allocator<T> allocator_;
auto throw_is_empty()/*strong*/ const -> void;
mutable std::mutex m;
};
template <typename T>
stack<T>::stack(size_t size) : allocator_(size), m() {};
template <typename T>
stack<T>::stack(stack const & other) : allocator_(0), m()
{
std::lock_guard<std::mutex> locker(other.m);
allocator_.swap(allocator<T>(other.allocator_));
}
template <typename T>
auto stack<T>::operator=(const stack &other)->stack&
{
if (this != &other)
{
std::lock(m, other.m);
std::lock_guard<std::mutex> locker1(m, std::adopt_lock);
std::lock_guard<std::mutex> locker2(other.m, std::adopt_lock);
(allocator<T>(other.allocator_)).swap(allocator_);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const->bool
{
std::lock_guard<std::mutex> locker(other.m);
return (allocator_.count() == 0);
}
template <typename T>
auto stack<T>::count() const ->size_t
{
std::lock_guard<std::mutex> locker(other.m);
return allocator_.count();
}
template <typename T>
auto stack<T>::push(T const &val)->void
{
std::lock_guard<std::mutex> locker(other.m);
if (allocator_.full())
{
allocator_.resize();
}
allocator_.construct(allocator_.get() + allocator_.count(), val);
}
template <typename T>
auto stack<T>::pop()->std::shared_ptr<T>
{
std::lock_guard<std::mutex> locker(other.m);
if (allocator_.count() == 0) throw_is_empty();
std::shared_ptr<T> top_(std::make_shared<T>(std::move(allocator_.get()[allocator_.count() - 1])));
allocator_.destroy(allocator_.get() + allocator_.count() - 1);
return top_;
}
template <typename T>
auto stack<T>::throw_is_empty()const->void
{
std::lock_guard<std::mutex> locker(other.m);
throw("EMPTY!");
}
<commit_msg>Update stack.hpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>
class bitset
{
public:
explicit bitset(size_t size) /*strong*/;
bitset(bitset const & other) = delete;
auto operator =(bitset const & other)->bitset & = delete;
bitset(bitset && other) = delete;
auto operator =(bitset && other)->bitset & = delete;
auto set(size_t index) /*strong*/ -> void;
auto reset(size_t index) /*strong*/ -> void;
auto test(size_t index) /*strong*/ -> bool;
auto size() /*noexcept*/ -> size_t;
auto counter() /*noexcept*/ -> size_t;
private:
std::unique_ptr<bool[]> ptr_;
size_t size_;
size_t counter_;
};
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0){}
auto bitset::set(size_t index)->void {
if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; }
else throw("bad_index");
}
auto bitset::reset(size_t index)->void {
if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; }
else throw("bad_index");
}
auto bitset::test(size_t index)->bool {
if (index >= 0 && index < size_) return !ptr_[index];
else throw("bad_index");
}
auto bitset::size()->size_t{ return size_; }
auto bitset::counter()->size_t{ return counter_; }
template <typename T>
class allocator{
public:
explicit allocator(std::size_t size = 0) /*strong*/;
allocator(allocator const & other) /*strong*/;
auto operator =(allocator const & other)->allocator & = delete;
~allocator();
auto resize() /*strong*/ -> void;
auto construct(T * ptr, T const & value) /*strong*/ -> void;
auto destroy(T * ptr) /*noexcept*/ -> void;
auto get() /*noexcept*/ -> T *;
auto get() const /*noexcept*/ -> T const *;
auto count() const /*noexcept*/ -> size_t;
auto full() const /*noexcept*/ -> bool;
auto empty() const /*noexcept*/ -> bool;
auto swap(allocator & other) /*noexcept*/ -> void;
private:
auto destroy(T * first, T * last) /*noexcept*/ -> void;
size_t count_;
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template<typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size)), count_(0) {}
template<typename T>
allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) {
for (size_t i = 0; i < other.count_; i++) if(map_->test(i)) construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator(){
if (this->count() > 0) {
destroy(ptr_, ptr_ + size_);
}
operator delete(ptr_);
}
template<typename T>
auto allocator<T>::resize()->void{
allocator<T> al(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; ++i) if (al.map_->test(i)) al.construct(al.get() + i, ptr_[i]);
al.swap(*this);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void{
if (ptr >= ptr_&&ptr < ptr_ + size_){
new(ptr)T(value);
map_->set(ptr - ptr_);
++count_;
}
else { throw("error"); }
}
template<typename T>
auto allocator<T>::destroy(T* ptr)->void{
if (!map_->test(ptr - ptr_) && ptr >= ptr_&&ptr <= ptr_ + this->count())
{
ptr->~T();
map_->reset(ptr - ptr_);
--count_;
}
}
template<typename T>
auto allocator<T>::get()-> T* { return ptr_; }
template<typename T>
auto allocator<T>::get() const -> T const * { return ptr_; }
template<typename T>
auto allocator<T>::count() const -> size_t{ return count_; }
template<typename T>
auto allocator<T>::full() const -> bool { return (map_->counter() == size_); }
template<typename T>
auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); }
template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void{
if (first >= ptr_&&last <= ptr_ + this->count())
for (; first != last; ++first) {
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::swap(allocator & other)->void{
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
std::swap(count_, other.count_);
}
template <typename T>
class stack {
public:
explicit stack(size_t size = 0);
stack(stack const & other); /*strong*/
auto operator =(stack const & other) /*strong*/ -> stack &;
auto empty() const /*noexcept*/ -> bool;
auto count() const /*noexcept*/ -> size_t;
auto push(T const & value) /*strong*/ -> void;
auto pop() /*strong*/ -> std::shared_ptr<T>;
//auto top()const -> const T&;
private:
allocator<T> allocator_;
auto throw_is_empty()/*strong*/ const -> void;
mutable std::mutex m;
};
template <typename T>
stack<T>::stack(size_t size) : allocator_(size), m() {};
template <typename T>
stack<T>::stack(stack const & other) : allocator_(0), m()
{
std::lock_guard<std::mutex> locker(other.m);
allocator_.swap(allocator<T>(other.allocator_));
}
template <typename T>
auto stack<T>::operator=(const stack &other)->stack&
{
if (this != &other)
{
std::lock(m, other.m);
std::lock_guard<std::mutex> locker1(m, std::adopt_lock);
std::lock_guard<std::mutex> locker2(other.m, std::adopt_lock);
(allocator<T>(other.allocator_)).swap(allocator_);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const->bool
{
std::lock_guard<std::mutex> locker(m);
return (allocator_.count() == 0);
}
template <typename T>
auto stack<T>::count() const ->size_t
{
std::lock_guard<std::mutex> locker(m);
return allocator_.count();
}
template <typename T>
auto stack<T>::push(T const &val)->void
{
std::lock_guard<std::mutex> locker(m);
if (allocator_.full())
{
allocator_.resize();
}
allocator_.construct(allocator_.get() + allocator_.count(), val);
}
template <typename T>
auto stack<T>::pop()->std::shared_ptr<T>
{
std::lock_guard<std::mutex> locker(m);
if (allocator_.count() == 0) throw_is_empty();
std::shared_ptr<T> top_(std::make_shared<T>(std::move(allocator_.get()[allocator_.count() - 1])));
allocator_.destroy(allocator_.get() + allocator_.count() - 1);
return top_;
}
template <typename T>
auto stack<T>::throw_is_empty()const->void
{
std::lock_guard<std::mutex> locker(m);
throw("EMPTY!");
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <stdexcept>
template <typename T>
class stack
{
public:
stack() noexcept;
~stack() noexcept;
stack(stack<T> const&)/*no safety*/;
stack& operator=(stack<T> const&)/*no safety*/;
size_t count()const noexcept;
void push(T const&)/*no safety*/;
void pop()/*no safety*/;
T top()const /*no safety*/;
void print(std::ostream&stream)const /*strong*/;
void swap(stack<T>&)noexcept;
bool empty()const noexcept;
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
array_size_ = other.array_size_;
count_ = other.count_;
std::copy(other.array_, other.array_ + count_, array_);
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
if (&other != this)
stack(other).swap(*this);
return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
if (empty())
{
array_size_ = 1;
array_ = new T[array_size_]();
}
else if (array_size_ == count_)
{
array_size_ *= 2;
T * new_array = new T[array_size_]();
std::copy(array_, array_ + count_, new_array);
delete[] array_;
array_ = new_array;
}
array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw std::logic_error("Stack is empty");
--count_;
}
template <typename T>
T stack<T>::top()const
{
if (empty())
throw std::logic_error("Stack is empty");
else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const
{
if(!empty())
{
for (unsigned int i = 0; i < count_; ++i)
stream << array_[i] << " ";
stream << std::endl;
}
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
std::swap(array_, other.array_);
std::swap(array_size_, other.array_size_);
std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
return (count_ == 0);
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
#include <algorithm>
#include <stdexcept>
template <typename T>
class stack
{
public:
stack() noexcept;
~stack() noexcept;
stack(stack<T> const&)/*no safety*/;
stack& operator=(stack<T> const&)/*no safety*/;
size_t count()const noexcept;
void push(T const&)/*no safety*/;
void pop()/*no safety*/;
T top()const /*no safety*/;
void print(std::ostream&stream)const /*strong*/;
void swap(stack<T>&)noexcept;
bool empty()const noexcept;
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T> noexcept
stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
array_size_ = other.array_size_;
count_ = other.count_;
std::copy(other.array_, other.array_ + count_, array_);
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
if (&other != this)
stack(other).swap(*this);
return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
if (empty())
{
array_size_ = 1;
array_ = new T[array_size_]();
}
else if (array_size_ == count_)
{
array_size_ *= 2;
T * new_array = new T[array_size_]();
std::copy(array_, array_ + count_, new_array);
delete[] array_;
array_ = new_array;
}
array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw std::logic_error("Stack is empty");
--count_;
}
template <typename T>
T stack<T>::top()const
{
if (empty())
throw std::logic_error("Stack is empty");
else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const
{
if(!empty())
{
for (unsigned int i = 0; i < count_; ++i)
stream << array_[i] << " ";
stream << std::endl;
}
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
std::swap(array_, other.array_);
std::swap(array_size_, other.array_size_);
std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
return (count_ == 0);
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();/*noexept*/
stack(const stack<T> &);/*strong*/
size_t count() const; /*noexcept*/
void print()const;/*noexcept*/
void push(T const &); /*strong*/
void swap(stack<T>&); /*noexcept*/
void pop(); /*strong*/
T top(); /*strong*/
bool empty() const; /*noexcept*/
stack<T>& operator=(stack<T> &); /*noexcept*/
~stack();/*noexcept*/
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
if (count_ > 0) {
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T[count_];
std::copy(copy.array_, copy.array_ + copy.count_, array_);
}else{
array_ = nullptr;
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template <typename T>
bool stack<T>::empty() const
{
return (count_ == 0);
}
template<typename T>
void stack<T>::swap(stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
T stack<T>::top()
{
if (empty())
{
throw "Stack is empty!";
}
return array_[count_ - 1];
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
if (array_size_ > 0) {
array_size_ = array_size_ * 2;
T *s1 = new T[array_size_];
std::copy(array_, array_ + count_, s1);
delete[] array_;
array_ = s1;
}
}
array_[count_] = value;
count_++;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw "Stack is empty" ;
count_--;
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(stack<T> & other)
{
if (this != &other)
{
stack<T> tmp(other);
tmp.swap(*this);
}
return *this;
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();/*noexept*/
stack(const stack<T> &);/*strong*/
size_t count() const; /*noexcept*/
void print()const;/*noexcept*/
void push(T const &); /*strong*/
void swap(stack<T>&); /*noexcept*/
void pop(); /*strong*/
T top(); /*strong*/
bool empty() const; /*noexcept*/
stack<T>& operator=(stack<T> &); /*noexcept*/
~stack();/*noexcept*/
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
if (count_ > 0) {
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T[count_];
std::copy(copy.array_, copy.array_ + copy.count_, array_);
}else{
array_ = nullptr;
}
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template <typename T>
bool stack<T>::empty() const
{
return (count_ == 0);
}
template<typename T>
void stack<T>::swap(stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
T stack<T>::top()
{
if (empty())
{
throw "Stack is empty!";
}
return array_[count_ - 1];
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
if (array_size_ > 0) {
array_size_ = array_size_ * 2;
T *s1 = new T[array_size_];
std::copy(array_, array_ + count_, s1);
delete[] array_;
array_ = s1;
}
}
array_[count_] = value;
count_++;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw "Stack is empty" ;
count_--;
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(stack<T> & other)
{
if (this != &other)
{
stack<T> tmp(other);
tmp.swap(*this);
}
return *this;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <new>
template <typename T>
class stack
{
public:
stack() noexcept;
~stack() noexcept;
stack(stack<T> const&)/*strong*/;
stack& operator=(stack<T> const&)/*strong*/;
size_t count()const noexcept;
void push(T const&)/*strong*/;
void pop()/*strong*/;
T top()const /*strong*/;
void print(std::ostream&stream)const /*strong*/;
bool empty()const noexcept;
private:
void swap(stack<T>&)noexcept;
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
T new_array = new T [other.array_size_];
array_size_ = other.array_size_;
count_ = other.count_;
array_ = new_array;
std::copy(other.array_, other.array_ + count_, array_);
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
if (&other != this)
stack(other).swap(*this);
return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
if (empty())
{
array_size_ = 1;
array_ = new T[array_size_]();
}
else if (array_size_ == count_)
{
try
{
array_size_ *= 2;
T * new_array = new T[array_size_]();
std::copy(array_, array_ + count_, new_array);
delete[] array_;
array_ = new_array;
}
catch(std::bad_alloc)
{
std::cerr << "bad_alloc caught" << std::endl;
}
}
array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw std::logic_error("Stack is empty");
--count_;
}
template <typename T>
T stack<T>::top()const
{
if (empty())
throw std::logic_error("Stack is empty");
else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const
{
if(!empty())
{
for (unsigned int i = 0; i < count_; ++i)
stream << array_[i] << " ";
stream << std::endl;
}
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
std::swap(array_, other.array_);
std::swap(array_size_, other.array_size_);
std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
return (count_ == 0);
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <new>
template <typename T>
class stack
{
public:
stack() noexcept;
~stack() noexcept;
stack(stack<T> const&)/*strong*/;
stack& operator=(stack<T> const&)/*strong*/;
size_t count()const noexcept;
void push(T const&)/*strong*/;
void pop()/*strong*/;
T top()const /*strong*/;
void print(std::ostream&stream)const /*strong*/;
bool empty()const noexcept;
private:
void swap(stack<T>&)noexcept;
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() noexcept : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {}
template <typename T>
stack<T>::~stack()noexcept
{
delete[] array_;
}
template <typename T>
stack<T>::stack(stack<T> const& other)
{
T new_array = new T [other.array_size_];
array_size_ = other.array_size_;
count_ = other.count_;
array_ = new_array;
try
{
std::copy(other.array_, other.array_ + count_, array_);
}
catch( ... )
{
std::cerr << "ERROR" << std::endl;
delete[] array_;
}
}
template <typename T>
stack<T>& stack<T>::operator=(stack<T> const & other)
{
if (&other != this)
stack(other).swap(*this);
return *this;
}
template <typename T>
size_t stack<T>::count()const noexcept
{
return count_;
}
template <typename T>
void stack<T>::push(T const & value)
{
if (empty())
{
array_size_ = 1;
array_ = new T[array_size_]();
}
else if (array_size_ == count_)
{
try
{
array_size_ *= 2;
T * new_array = new T[array_size_]();
std::copy(array_, array_ + count_, new_array);
delete[] array_;
array_ = new_array;
}
catch(std::bad_alloc)
{
std::cerr << "bad_alloc caught" << std::endl;
}
}
array_[count_++] = value;
}
template <typename T>
void stack<T>::pop()
{
if (empty())
throw std::logic_error("Stack is empty");
--count_;
}
template <typename T>
T stack<T>::top()const
{
if (empty())
throw std::logic_error("Stack is empty");
else return array_[count_ - 1];
}
template <typename T>
void stack<T>::print(std::ostream&stream)const
{
if(!empty())
{
for (unsigned int i = 0; i < count_; ++i)
stream << array_[i] << " ";
stream << std::endl;
}
}
template <typename T>
void stack<T>::swap(stack<T>& other)noexcept
{
std::swap(array_, other.array_);
std::swap(array_size_, other.array_size_);
std::swap(count_, other.count_);
}
template <typename T>
bool stack<T>::empty()const noexcept
{
return (count_ == 0);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/fake_encoder.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/sleep.h"
namespace webrtc {
namespace test {
FakeEncoder::FakeEncoder(Clock* clock)
: clock_(clock),
callback_(NULL),
target_bitrate_kbps_(0),
max_target_bitrate_kbps_(-1),
last_encode_time_ms_(0) {
// Generate some arbitrary not-all-zero data
for (size_t i = 0; i < sizeof(encoded_buffer_); ++i) {
encoded_buffer_[i] = static_cast<uint8_t>(i);
}
}
FakeEncoder::~FakeEncoder() {}
void FakeEncoder::SetMaxBitrate(int max_kbps) {
assert(max_kbps >= -1); // max_kbps == -1 disables it.
max_target_bitrate_kbps_ = max_kbps;
}
int32_t FakeEncoder::InitEncode(const VideoCodec* config,
int32_t number_of_cores,
size_t max_payload_size) {
config_ = *config;
target_bitrate_kbps_ = config_.startBitrate;
return 0;
}
int32_t FakeEncoder::Encode(
const I420VideoFrame& input_image,
const CodecSpecificInfo* codec_specific_info,
const std::vector<VideoFrameType>* frame_types) {
assert(config_.maxFramerate > 0);
int64_t time_since_last_encode_ms = 1000 / config_.maxFramerate;
int64_t time_now_ms = clock_->TimeInMilliseconds();
const bool first_encode = last_encode_time_ms_ == 0;
if (!first_encode) {
// For all frames but the first we can estimate the display time by looking
// at the display time of the previous frame.
time_since_last_encode_ms = time_now_ms - last_encode_time_ms_;
}
size_t bits_available =
static_cast<size_t>(target_bitrate_kbps_ * time_since_last_encode_ms);
size_t min_bits = static_cast<size_t>(
config_.simulcastStream[0].minBitrate * time_since_last_encode_ms);
if (bits_available < min_bits)
bits_available = min_bits;
size_t max_bits =
static_cast<size_t>(max_target_bitrate_kbps_ * time_since_last_encode_ms);
if (max_bits > 0 && max_bits < bits_available)
bits_available = max_bits;
last_encode_time_ms_ = time_now_ms;
assert(config_.numberOfSimulcastStreams > 0);
for (unsigned char i = 0; i < config_.numberOfSimulcastStreams; ++i) {
CodecSpecificInfo specifics;
memset(&specifics, 0, sizeof(specifics));
specifics.codecType = kVideoCodecGeneric;
specifics.codecSpecific.generic.simulcast_idx = i;
size_t min_stream_bits = static_cast<size_t>(
config_.simulcastStream[i].minBitrate * time_since_last_encode_ms);
size_t max_stream_bits = static_cast<size_t>(
config_.simulcastStream[i].maxBitrate * time_since_last_encode_ms);
size_t stream_bits = (bits_available > max_stream_bits) ? max_stream_bits :
bits_available;
size_t stream_bytes = (stream_bits + 7) / 8;
if (first_encode) {
// The first frame is a key frame and should be larger.
// TODO(holmer): The FakeEncoder should store the bits_available between
// encodes so that it can compensate for oversized frames.
stream_bytes *= 10;
}
if (stream_bytes > sizeof(encoded_buffer_))
stream_bytes = sizeof(encoded_buffer_);
EncodedImage encoded(
encoded_buffer_, stream_bytes, sizeof(encoded_buffer_));
encoded._timeStamp = input_image.timestamp();
encoded.capture_time_ms_ = input_image.render_time_ms();
encoded._frameType = (*frame_types)[i];
// Always encode something on the first frame.
if (min_stream_bits > bits_available && i > 0) {
encoded._length = 0;
encoded._frameType = kSkipFrame;
}
assert(callback_ != NULL);
if (callback_->Encoded(encoded, &specifics, NULL) != 0)
return -1;
bits_available -= std::min(encoded._length * 8, bits_available);
}
return 0;
}
int32_t FakeEncoder::RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) {
callback_ = callback;
return 0;
}
int32_t FakeEncoder::Release() { return 0; }
int32_t FakeEncoder::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
return 0;
}
int32_t FakeEncoder::SetRates(uint32_t new_target_bitrate, uint32_t framerate) {
target_bitrate_kbps_ = new_target_bitrate;
return 0;
}
FakeH264Encoder::FakeH264Encoder(Clock* clock)
: FakeEncoder(clock), callback_(NULL), idr_counter_(0) {
FakeEncoder::RegisterEncodeCompleteCallback(this);
}
int32_t FakeH264Encoder::RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) {
callback_ = callback;
return 0;
}
int32_t FakeH264Encoder::Encoded(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragments) {
const size_t kSpsSize = 8;
const size_t kPpsSize = 11;
const int kIdrFrequency = 10;
RTPFragmentationHeader fragmentation;
if (idr_counter_++ % kIdrFrequency == 0 &&
encoded_image._length > kSpsSize + kPpsSize + 1) {
const size_t kNumSlices = 3;
fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
fragmentation.fragmentationOffset[0] = 0;
fragmentation.fragmentationLength[0] = kSpsSize;
fragmentation.fragmentationOffset[1] = kSpsSize;
fragmentation.fragmentationLength[1] = kPpsSize;
fragmentation.fragmentationOffset[2] = kSpsSize + kPpsSize;
fragmentation.fragmentationLength[2] =
encoded_image._length - (kSpsSize + kPpsSize);
const size_t kSpsNalHeader = 0x37;
const size_t kPpsNalHeader = 0x38;
const size_t kIdrNalHeader = 0x15;
encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kSpsNalHeader;
encoded_image._buffer[fragmentation.fragmentationOffset[1]] = kPpsNalHeader;
encoded_image._buffer[fragmentation.fragmentationOffset[2]] = kIdrNalHeader;
} else {
const size_t kNumSlices = 1;
fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
fragmentation.fragmentationOffset[0] = 0;
fragmentation.fragmentationLength[0] = encoded_image._length;
const size_t kNalHeader = 0x11;
encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kNalHeader;
}
uint8_t value = 0;
int fragment_counter = 0;
for (size_t i = 0; i < encoded_image._length; ++i) {
if (fragment_counter == fragmentation.fragmentationVectorSize ||
i != fragmentation.fragmentationOffset[fragment_counter]) {
encoded_image._buffer[i] = value++;
} else {
++fragment_counter;
}
}
return callback_->Encoded(encoded_image, NULL, &fragmentation);
}
DelayedEncoder::DelayedEncoder(Clock* clock, int delay_ms)
: test::FakeEncoder(clock),
delay_ms_(delay_ms) {}
int32_t DelayedEncoder::Encode(const I420VideoFrame& input_image,
const CodecSpecificInfo* codec_specific_info,
const std::vector<VideoFrameType>* frame_types) {
SleepMs(delay_ms_);
return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
}
} // namespace test
} // namespace webrtc
<commit_msg>Fix the value of the first byte of nal unit generated by fake H.264 encoder.<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/fake_encoder.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/sleep.h"
namespace webrtc {
namespace test {
FakeEncoder::FakeEncoder(Clock* clock)
: clock_(clock),
callback_(NULL),
target_bitrate_kbps_(0),
max_target_bitrate_kbps_(-1),
last_encode_time_ms_(0) {
// Generate some arbitrary not-all-zero data
for (size_t i = 0; i < sizeof(encoded_buffer_); ++i) {
encoded_buffer_[i] = static_cast<uint8_t>(i);
}
}
FakeEncoder::~FakeEncoder() {}
void FakeEncoder::SetMaxBitrate(int max_kbps) {
assert(max_kbps >= -1); // max_kbps == -1 disables it.
max_target_bitrate_kbps_ = max_kbps;
}
int32_t FakeEncoder::InitEncode(const VideoCodec* config,
int32_t number_of_cores,
size_t max_payload_size) {
config_ = *config;
target_bitrate_kbps_ = config_.startBitrate;
return 0;
}
int32_t FakeEncoder::Encode(
const I420VideoFrame& input_image,
const CodecSpecificInfo* codec_specific_info,
const std::vector<VideoFrameType>* frame_types) {
assert(config_.maxFramerate > 0);
int64_t time_since_last_encode_ms = 1000 / config_.maxFramerate;
int64_t time_now_ms = clock_->TimeInMilliseconds();
const bool first_encode = last_encode_time_ms_ == 0;
if (!first_encode) {
// For all frames but the first we can estimate the display time by looking
// at the display time of the previous frame.
time_since_last_encode_ms = time_now_ms - last_encode_time_ms_;
}
size_t bits_available =
static_cast<size_t>(target_bitrate_kbps_ * time_since_last_encode_ms);
size_t min_bits = static_cast<size_t>(
config_.simulcastStream[0].minBitrate * time_since_last_encode_ms);
if (bits_available < min_bits)
bits_available = min_bits;
size_t max_bits =
static_cast<size_t>(max_target_bitrate_kbps_ * time_since_last_encode_ms);
if (max_bits > 0 && max_bits < bits_available)
bits_available = max_bits;
last_encode_time_ms_ = time_now_ms;
assert(config_.numberOfSimulcastStreams > 0);
for (unsigned char i = 0; i < config_.numberOfSimulcastStreams; ++i) {
CodecSpecificInfo specifics;
memset(&specifics, 0, sizeof(specifics));
specifics.codecType = kVideoCodecGeneric;
specifics.codecSpecific.generic.simulcast_idx = i;
size_t min_stream_bits = static_cast<size_t>(
config_.simulcastStream[i].minBitrate * time_since_last_encode_ms);
size_t max_stream_bits = static_cast<size_t>(
config_.simulcastStream[i].maxBitrate * time_since_last_encode_ms);
size_t stream_bits = (bits_available > max_stream_bits) ? max_stream_bits :
bits_available;
size_t stream_bytes = (stream_bits + 7) / 8;
if (first_encode) {
// The first frame is a key frame and should be larger.
// TODO(holmer): The FakeEncoder should store the bits_available between
// encodes so that it can compensate for oversized frames.
stream_bytes *= 10;
}
if (stream_bytes > sizeof(encoded_buffer_))
stream_bytes = sizeof(encoded_buffer_);
EncodedImage encoded(
encoded_buffer_, stream_bytes, sizeof(encoded_buffer_));
encoded._timeStamp = input_image.timestamp();
encoded.capture_time_ms_ = input_image.render_time_ms();
encoded._frameType = (*frame_types)[i];
// Always encode something on the first frame.
if (min_stream_bits > bits_available && i > 0) {
encoded._length = 0;
encoded._frameType = kSkipFrame;
}
assert(callback_ != NULL);
if (callback_->Encoded(encoded, &specifics, NULL) != 0)
return -1;
bits_available -= std::min(encoded._length * 8, bits_available);
}
return 0;
}
int32_t FakeEncoder::RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) {
callback_ = callback;
return 0;
}
int32_t FakeEncoder::Release() { return 0; }
int32_t FakeEncoder::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
return 0;
}
int32_t FakeEncoder::SetRates(uint32_t new_target_bitrate, uint32_t framerate) {
target_bitrate_kbps_ = new_target_bitrate;
return 0;
}
FakeH264Encoder::FakeH264Encoder(Clock* clock)
: FakeEncoder(clock), callback_(NULL), idr_counter_(0) {
FakeEncoder::RegisterEncodeCompleteCallback(this);
}
int32_t FakeH264Encoder::RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) {
callback_ = callback;
return 0;
}
int32_t FakeH264Encoder::Encoded(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragments) {
const size_t kSpsSize = 8;
const size_t kPpsSize = 11;
const int kIdrFrequency = 10;
RTPFragmentationHeader fragmentation;
if (idr_counter_++ % kIdrFrequency == 0 &&
encoded_image._length > kSpsSize + kPpsSize + 1) {
const size_t kNumSlices = 3;
fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
fragmentation.fragmentationOffset[0] = 0;
fragmentation.fragmentationLength[0] = kSpsSize;
fragmentation.fragmentationOffset[1] = kSpsSize;
fragmentation.fragmentationLength[1] = kPpsSize;
fragmentation.fragmentationOffset[2] = kSpsSize + kPpsSize;
fragmentation.fragmentationLength[2] =
encoded_image._length - (kSpsSize + kPpsSize);
const size_t kSpsNalHeader = 0x67;
const size_t kPpsNalHeader = 0x68;
const size_t kIdrNalHeader = 0x65;
encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kSpsNalHeader;
encoded_image._buffer[fragmentation.fragmentationOffset[1]] = kPpsNalHeader;
encoded_image._buffer[fragmentation.fragmentationOffset[2]] = kIdrNalHeader;
} else {
const size_t kNumSlices = 1;
fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
fragmentation.fragmentationOffset[0] = 0;
fragmentation.fragmentationLength[0] = encoded_image._length;
const size_t kNalHeader = 0x41;
encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kNalHeader;
}
uint8_t value = 0;
int fragment_counter = 0;
for (size_t i = 0; i < encoded_image._length; ++i) {
if (fragment_counter == fragmentation.fragmentationVectorSize ||
i != fragmentation.fragmentationOffset[fragment_counter]) {
encoded_image._buffer[i] = value++;
} else {
++fragment_counter;
}
}
return callback_->Encoded(encoded_image, NULL, &fragmentation);
}
DelayedEncoder::DelayedEncoder(Clock* clock, int delay_ms)
: test::FakeEncoder(clock),
delay_ms_(delay_ms) {}
int32_t DelayedEncoder::Encode(const I420VideoFrame& input_image,
const CodecSpecificInfo* codec_specific_info,
const std::vector<VideoFrameType>* frame_types) {
SleepMs(delay_ms_);
return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* param.cpp
*
*/
#include "param.h"
using namespace himan;
using namespace std;
param::~param() {}
param::param()
: itsId(kHPMissingInt),
itsName("XX-X"),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(theUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase,
HPInterpolationMethod theInterpolationMethod)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(theScale),
itsBase(theBase),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(theInterpolationMethod),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory,
long theGribParameter)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(theGribParameter),
itsGribCategory(theGribCategory),
itsGribDiscipline(theGribDiscipline),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const map<string, string>& databaseInfo) : param()
{
if (!databaseInfo.empty())
{
itsId = stoi(databaseInfo.at("id"));
itsName = databaseInfo.at("name");
itsVersion = stoi(databaseInfo.at("version"));
try
{
itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number"));
itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline"));
itsGribCategory = stoi(databaseInfo.at("grib2_category"));
itsGribParameter = stoi(databaseInfo.at("grib2_number"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsPrecision = stoi(databaseInfo.at("precision"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsUnivId = stoi(databaseInfo.at("univ_id"));
itsScale = stod(databaseInfo.at("scale"));
itsBase = stod(databaseInfo.at("base"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
}
}
param::param(const param& other)
: itsId(other.itsId),
itsName(other.itsName),
itsScale(other.itsScale),
itsBase(other.itsBase),
itsUnivId(other.itsUnivId),
itsGribParameter(other.itsGribParameter),
itsGribCategory(other.itsGribCategory),
itsGribDiscipline(other.itsGribDiscipline),
itsGribTableVersion(other.itsGribTableVersion),
itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter),
itsVersion(other.itsVersion),
itsInterpolationMethod(other.itsInterpolationMethod),
itsUnit(other.itsUnit),
itsAggregation(other.itsAggregation),
itsPrecision(other.itsPrecision)
{
}
param& param::operator=(const param& other)
{
itsId = other.itsId;
itsName = other.itsName;
itsScale = other.itsScale;
itsBase = other.itsBase;
itsUnivId = other.itsUnivId;
itsGribParameter = other.itsGribParameter;
itsGribCategory = other.itsGribCategory;
itsGribDiscipline = other.itsGribDiscipline;
itsGribTableVersion = other.itsGribTableVersion;
itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter;
itsVersion = other.itsVersion;
itsInterpolationMethod = other.itsInterpolationMethod;
itsUnit = other.itsUnit;
itsAggregation = other.itsAggregation;
itsPrecision = other.itsPrecision;
return *this;
}
bool param::operator==(const param& other) const
{
if (this == &other)
{
return true;
}
if (itsId != other.itsId)
{
return false;
}
if (itsName != other.itsName)
{
return false;
}
if (UnivId() != static_cast<unsigned int>(kHPMissingInt) &&
other.UnivId() != static_cast<unsigned int>(kHPMissingInt) && UnivId() != other.UnivId())
{
return false;
}
// Grib 1
if (itsGribTableVersion != kHPMissingInt && other.GribTableVersion() != kHPMissingInt &&
itsGribTableVersion != other.GribTableVersion())
{
return false;
}
if (itsGribIndicatorOfParameter != kHPMissingInt && other.GribIndicatorOfParameter() != kHPMissingInt &&
itsGribIndicatorOfParameter != other.GribIndicatorOfParameter())
{
return false;
}
// Grib 2
if (itsGribDiscipline != kHPMissingInt && other.GribDiscipline() != kHPMissingInt &&
itsGribDiscipline != other.GribDiscipline())
{
return false;
}
if (itsGribCategory != kHPMissingInt && other.GribCategory() != kHPMissingInt &&
itsGribCategory != other.GribCategory())
{
return false;
}
if (itsGribParameter != kHPMissingInt && other.GribParameter() != kHPMissingInt &&
itsGribParameter != other.GribParameter())
{
return false;
}
if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType &&
itsAggregation != other.itsAggregation)
{
return false;
}
if (itsVersion != other.itsVersion)
{
return false;
}
return true;
}
bool param::operator!=(const param& other) const { return !(*this == other); }
void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; }
long param::GribParameter() const { return itsGribParameter; }
void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; }
long param::GribDiscipline() const { return itsGribDiscipline; }
void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; }
long param::GribCategory() const { return itsGribCategory; }
void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter)
{
itsGribIndicatorOfParameter = theGribIndicatorOfParameter;
}
long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; }
unsigned long param::UnivId() const { return itsUnivId; }
void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; }
string param::Name() const { return itsName; }
void param::Name(const string& theName) { itsName = theName; }
HPParameterUnit param::Unit() const { return itsUnit; }
void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; }
void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; }
long param::GribTableVersion() const { return itsGribTableVersion; }
const aggregation& param::Aggregation() const { return itsAggregation; }
void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; }
double param::Base() const { return itsBase; }
void param::Base(double theBase) { itsBase = theBase; }
double param::Scale() const { return itsScale; }
void param::Scale(double theScale) { itsScale = theScale; }
long param::Id() const { return itsId; }
void param::Id(long theId) { itsId = theId; }
HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; }
void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod)
{
itsInterpolationMethod = theInterpolationMethod;
}
int param::Precision() const { return itsPrecision; }
void param::Precision(int thePrecision) { itsPrecision = thePrecision; }
ostream& param::Write(ostream& file) const
{
file << "<" << ClassName() << ">" << endl;
file << "__itsName__ " << itsName << endl;
file << "__itsScale__ " << itsScale << endl;
file << "__itsBase__ " << itsBase << endl;
file << "__itsUnivId__ " << itsUnivId << endl;
file << "__itsGribParameter__ " << itsGribParameter << endl;
file << "__itsGribCategory__ " << itsGribCategory << endl;
file << "__itsGribDiscipline__ " << itsGribDiscipline << endl;
file << "__itsGribTableVersion__ " << itsGribTableVersion << endl;
file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl;
file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl;
file << "__itsVersion__ " << itsVersion << endl;
file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl;
file << "__itsPrecision__" << itsPrecision << endl;
file << itsAggregation;
return file;
}
<commit_msg>Remove comparison of output file numbers for param.<commit_after>/*
* param.cpp
*
*/
#include "param.h"
using namespace himan;
using namespace std;
param::~param() {}
param::param()
: itsId(kHPMissingInt),
itsName("XX-X"),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(theUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase,
HPInterpolationMethod theInterpolationMethod)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(theScale),
itsBase(theBase),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(theInterpolationMethod),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory,
long theGribParameter)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(theGribParameter),
itsGribCategory(theGribCategory),
itsGribDiscipline(theGribDiscipline),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const map<string, string>& databaseInfo) : param()
{
if (!databaseInfo.empty())
{
itsId = stoi(databaseInfo.at("id"));
itsName = databaseInfo.at("name");
itsVersion = stoi(databaseInfo.at("version"));
try
{
itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number"));
itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline"));
itsGribCategory = stoi(databaseInfo.at("grib2_category"));
itsGribParameter = stoi(databaseInfo.at("grib2_number"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsPrecision = stoi(databaseInfo.at("precision"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsUnivId = stoi(databaseInfo.at("univ_id"));
itsScale = stod(databaseInfo.at("scale"));
itsBase = stod(databaseInfo.at("base"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
}
}
param::param(const param& other)
: itsId(other.itsId),
itsName(other.itsName),
itsScale(other.itsScale),
itsBase(other.itsBase),
itsUnivId(other.itsUnivId),
itsGribParameter(other.itsGribParameter),
itsGribCategory(other.itsGribCategory),
itsGribDiscipline(other.itsGribDiscipline),
itsGribTableVersion(other.itsGribTableVersion),
itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter),
itsVersion(other.itsVersion),
itsInterpolationMethod(other.itsInterpolationMethod),
itsUnit(other.itsUnit),
itsAggregation(other.itsAggregation),
itsPrecision(other.itsPrecision)
{
}
param& param::operator=(const param& other)
{
itsId = other.itsId;
itsName = other.itsName;
itsScale = other.itsScale;
itsBase = other.itsBase;
itsUnivId = other.itsUnivId;
itsGribParameter = other.itsGribParameter;
itsGribCategory = other.itsGribCategory;
itsGribDiscipline = other.itsGribDiscipline;
itsGribTableVersion = other.itsGribTableVersion;
itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter;
itsVersion = other.itsVersion;
itsInterpolationMethod = other.itsInterpolationMethod;
itsUnit = other.itsUnit;
itsAggregation = other.itsAggregation;
itsPrecision = other.itsPrecision;
return *this;
}
bool param::operator==(const param& other) const
{
if (this == &other)
{
return true;
}
if (itsName != other.itsName)
{
return false;
}
if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType &&
itsAggregation != other.itsAggregation)
{
return false;
}
if (itsVersion != other.itsVersion)
{
return false;
}
return true;
}
bool param::operator!=(const param& other) const { return !(*this == other); }
void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; }
long param::GribParameter() const { return itsGribParameter; }
void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; }
long param::GribDiscipline() const { return itsGribDiscipline; }
void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; }
long param::GribCategory() const { return itsGribCategory; }
void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter)
{
itsGribIndicatorOfParameter = theGribIndicatorOfParameter;
}
long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; }
unsigned long param::UnivId() const { return itsUnivId; }
void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; }
string param::Name() const { return itsName; }
void param::Name(const string& theName) { itsName = theName; }
HPParameterUnit param::Unit() const { return itsUnit; }
void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; }
void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; }
long param::GribTableVersion() const { return itsGribTableVersion; }
const aggregation& param::Aggregation() const { return itsAggregation; }
void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; }
double param::Base() const { return itsBase; }
void param::Base(double theBase) { itsBase = theBase; }
double param::Scale() const { return itsScale; }
void param::Scale(double theScale) { itsScale = theScale; }
long param::Id() const { return itsId; }
void param::Id(long theId) { itsId = theId; }
HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; }
void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod)
{
itsInterpolationMethod = theInterpolationMethod;
}
int param::Precision() const { return itsPrecision; }
void param::Precision(int thePrecision) { itsPrecision = thePrecision; }
ostream& param::Write(ostream& file) const
{
file << "<" << ClassName() << ">" << endl;
file << "__itsName__ " << itsName << endl;
file << "__itsScale__ " << itsScale << endl;
file << "__itsBase__ " << itsBase << endl;
file << "__itsUnivId__ " << itsUnivId << endl;
file << "__itsGribParameter__ " << itsGribParameter << endl;
file << "__itsGribCategory__ " << itsGribCategory << endl;
file << "__itsGribDiscipline__ " << itsGribDiscipline << endl;
file << "__itsGribTableVersion__ " << itsGribTableVersion << endl;
file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl;
file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl;
file << "__itsVersion__ " << itsVersion << endl;
file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl;
file << "__itsPrecision__" << itsPrecision << endl;
file << itsAggregation;
return file;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NavigatorChildWindow.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-12-12 16:57:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "NavigatorChildWindow.hxx"
#ifndef SD_NAVIGATOR_HXX
#include "navigatr.hxx"
#endif
#include "app.hrc"
#include "navigatr.hrc"
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
namespace sd {
SFX_IMPL_CHILDWINDOWCONTEXT(NavigatorChildWindow, SID_NAVIGATOR)
NavigatorChildWindow::NavigatorChildWindow (
::Window* pParent,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* )
: SfxChildWindowContext( nId )
{
SdNavigatorWin* pNavWin = new SdNavigatorWin( pParent, this,
SdResId( FLT_NAVIGATOR ), pBindings );
SetWindow( pNavWin );
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.5.298); FILE MERGED 2008/04/01 15:34:15 thb 1.5.298.3: #i85898# Stripping all external header guards 2008/04/01 12:38:39 thb 1.5.298.2: #i85898# Stripping all external header guards 2008/03/31 13:57:44 rt 1.5.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NavigatorChildWindow.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "NavigatorChildWindow.hxx"
#include "navigatr.hxx"
#include "app.hrc"
#include "navigatr.hrc"
#include <sfx2/app.hxx>
namespace sd {
SFX_IMPL_CHILDWINDOWCONTEXT(NavigatorChildWindow, SID_NAVIGATOR)
NavigatorChildWindow::NavigatorChildWindow (
::Window* pParent,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* )
: SfxChildWindowContext( nId )
{
SdNavigatorWin* pNavWin = new SdNavigatorWin( pParent, this,
SdResId( FLT_NAVIGATOR ), pBindings );
SetWindow( pNavWin );
}
} // end of namespace sd
<|endoftext|> |
<commit_before>// source_facility.cc
// Implements the SourceFacility class
#include "source_facility.h"
#include <sstream>
#include <limits>
#include <boost/lexical_cast.hpp>
#include "cyc_limits.h"
#include "context.h"
#include "error.h"
#include "generic_resource.h"
#include "logger.h"
#include "market_model.h"
#include "query_engine.h"
namespace cycamore {
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SourceFacility::SourceFacility(cyclus::Context* ctx)
: cyclus::FacilityModel(ctx),
out_commod_(""),
recipe_name_(""),
commod_price_(0),
capacity_(std::numeric_limits<double>::max()) {
using std::deque;
using std::numeric_limits;
ordersWaiting_ = deque<cyclus::Message::Ptr>();
inventory_ = cyclus::MatBuff();
SetMaxInventorySize(numeric_limits<double>::max());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SourceFacility::~SourceFacility() {}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::InitModuleMembers(cyclus::QueryEngine* qe) {
using std::string;
using std::numeric_limits;
using boost::lexical_cast;
cyclus::QueryEngine* output = qe->QueryElement("output");
SetRecipe(output->GetElementContent("recipe"));
string data = output->GetElementContent("outcommodity");
SetCommodity(data);
cyclus::Commodity commod(data);
cyclus::supply_demand::CommodityProducer::AddCommodity(commod);
double capacity =
cyclus::GetOptionalQuery<double>(qe,
"inventorysize",
numeric_limits<double>::max());
cyclus::supply_demand::CommodityProducer::SetCapacity(commod, capacity);
SetCapacity(capacity);
double size =
cyclus::GetOptionalQuery<double>(qe,
"inventorysize",
numeric_limits<double>::max());
SetMaxInventorySize(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::str() {
std::stringstream ss;
ss << cyclus::FacilityModel::str()
<< " supplies commodity '"
<< out_commod_ << "' with recipe '"
<< recipe_name_ << "' at a capacity of "
<< capacity_ << " kg per time step "
<< " with max inventory of " << inventory_.capacity() << " kg.";
return "" + ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::CloneModuleMembersFrom(cyclus::FacilityModel*
sourceModel) {
SourceFacility* source = dynamic_cast<SourceFacility*>(sourceModel);
SetCommodity(source->commodity());
SetCapacity(source->capacity());
SetRecipe(source->recipe());
SetMaxInventorySize(source->MaxInventorySize());
CopyProducedCommoditiesFrom(source);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::HandleTick(int time) {
LOG(cyclus::LEV_INFO3, "SrcFac") << FacName() << " is ticking {";
GenerateMaterial();
cyclus::Transaction trans = BuildTransaction();
LOG(cyclus::LEV_INFO4, "SrcFac") << "offers " << trans.resource()->quantity() <<
" kg of "
<< out_commod_ << ".";
SendOffer(trans);
LOG(cyclus::LEV_INFO3, "SrcFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::HandleTock(int time) {
LOG(cyclus::LEV_INFO3, "SrcFac") << FacName() << " is tocking {";
// check what orders are waiting,
// send material if you have it now
while (!ordersWaiting_.empty()) {
cyclus::Transaction order = ordersWaiting_.front()->trans();
LOG(cyclus::LEV_INFO3, "SrcFac") << "Order is for: " <<
order.resource()->quantity();
LOG(cyclus::LEV_INFO3, "SrcFac") << "Inventory is: " << inventory_.quantity();
if (order.resource()->quantity() - inventory_.quantity() > cyclus::eps()) {
LOG(cyclus::LEV_INFO3, "SrcFac") <<
"Not enough inventory. Waitlisting remaining orders.";
break;
} else {
LOG(cyclus::LEV_INFO3, "SrcFac") << "Satisfying order.";
order.ApproveTransfer();
ordersWaiting_.pop_front();
}
}
// For now, lets just print out what we have at each timestep.
LOG(cyclus::LEV_INFO4, "SrcFac") << "SourceFacility " << this->ID()
<< " is holding " << this->inventory_.quantity()
<< " units of material at the close of month " << time
<< ".";
LOG(cyclus::LEV_INFO3, "SrcFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::ReceiveMessage(cyclus::Message::Ptr msg) {
if (msg->trans().supplier() == this) {
// file the order
ordersWaiting_.push_front(msg);
LOG(cyclus::LEV_INFO5, "SrcFac") << name() << " just received an order.";
LOG(cyclus::LEV_INFO5, "SrcFac") << "for " <<
msg->trans().resource()->quantity()
<< " of " << msg->trans().commod();
} else {
throw cyclus::Error("SourceFacility is not the supplier of this msg.");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<cyclus::Resource::Ptr> SourceFacility::RemoveResource(
cyclus::Transaction order) {
return cyclus::MatBuff::ToRes(inventory_.PopQty(order.resource()->quantity()));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetCommodity(std::string name) {
out_commod_ = name;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::commodity() {
return out_commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetCapacity(double capacity) {
capacity_ = capacity;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::capacity() {
return capacity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetRecipe(std::string name) {
recipe_name_ = name;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::recipe() {
return recipe_name_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetMaxInventorySize(double size) {
inventory_.SetCapacity(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::MaxInventorySize() {
return inventory_.capacity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::InventorySize() {
return inventory_.quantity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::GenerateMaterial() {
using cyclus::Model;
using cyclus::Material;
double empty_space = inventory_.space();
if (empty_space < cyclus::eps()) {
return; // no room
}
Material::Ptr newMat;
double amt = capacity_;
cyclus::Context* ctx = Model::context();
if (amt <= empty_space) {
newMat = Material::Create(ctx, amt, ctx->GetRecipe(recipe_name_));
} else {
newMat = Material::Create(ctx, empty_space, ctx->GetRecipe(recipe_name_));
}
inventory_.PushOne(newMat);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Transaction SourceFacility::BuildTransaction() {
using cyclus::Model;
using cyclus::Material;
// there is no minimum amount a source facility may send
double min_amt = 0;
double offer_amt = inventory_.quantity();
cyclus::Context* ctx = Model::context();
Material::Ptr trade_res = Material::Create(ctx,
offer_amt,
ctx->GetRecipe(recipe()));
cyclus::Transaction trans(this, cyclus::OFFER);
trans.SetCommod(out_commod_);
trans.SetMinFrac(min_amt / offer_amt);
trans.SetPrice(commod_price_);
trans.SetResource(trade_res);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SendOffer(cyclus::Transaction trans) {
cyclus::MarketModel* market = cyclus::MarketModel::MarketForCommod(out_commod_);
Communicator* recipient = dynamic_cast<Communicator*>(market);
cyclus::Message::Ptr msg(new cyclus::Message(this, recipient, trans));
msg->SendOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Model* ConstructSourceFacility(cyclus::Context* ctx) {
return new SourceFacility(ctx);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" void DestructSourceFacility(cyclus::Model* model) {
delete model;
}
} // namespace cycamore
<commit_msg>fixed source facility typo<commit_after>// source_facility.cc
// Implements the SourceFacility class
#include "source_facility.h"
#include <sstream>
#include <limits>
#include <boost/lexical_cast.hpp>
#include "cyc_limits.h"
#include "context.h"
#include "error.h"
#include "generic_resource.h"
#include "logger.h"
#include "market_model.h"
#include "query_engine.h"
namespace cycamore {
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SourceFacility::SourceFacility(cyclus::Context* ctx)
: cyclus::FacilityModel(ctx),
out_commod_(""),
recipe_name_(""),
commod_price_(0),
capacity_(std::numeric_limits<double>::max()) {
using std::deque;
using std::numeric_limits;
ordersWaiting_ = deque<cyclus::Message::Ptr>();
inventory_ = cyclus::MatBuff();
SetMaxInventorySize(numeric_limits<double>::max());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SourceFacility::~SourceFacility() {}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::InitModuleMembers(cyclus::QueryEngine* qe) {
using std::string;
using std::numeric_limits;
using boost::lexical_cast;
cyclus::QueryEngine* output = qe->QueryElement("output");
SetRecipe(output->GetElementContent("recipe"));
string data = output->GetElementContent("outcommodity");
SetCommodity(data);
cyclus::Commodity commod(data);
cyclus::supply_demand::CommodityProducer::AddCommodity(commod);
double capacity =
cyclus::GetOptionalQuery<double>(output,
"output_inventorysize",
numeric_limits<double>::max());
cyclus::supply_demand::CommodityProducer::SetCapacity(commod, capacity);
SetCapacity(capacity);
double size =
cyclus::GetOptionalQuery<double>(output,
"inventorysize",
numeric_limits<double>::max());
SetMaxInventorySize(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::str() {
std::stringstream ss;
ss << cyclus::FacilityModel::str()
<< " supplies commodity '"
<< out_commod_ << "' with recipe '"
<< recipe_name_ << "' at a capacity of "
<< capacity_ << " kg per time step "
<< " with max inventory of " << inventory_.capacity() << " kg.";
return "" + ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::CloneModuleMembersFrom(cyclus::FacilityModel*
sourceModel) {
SourceFacility* source = dynamic_cast<SourceFacility*>(sourceModel);
SetCommodity(source->commodity());
SetCapacity(source->capacity());
SetRecipe(source->recipe());
SetMaxInventorySize(source->MaxInventorySize());
CopyProducedCommoditiesFrom(source);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::HandleTick(int time) {
LOG(cyclus::LEV_INFO3, "SrcFac") << FacName() << " is ticking {";
GenerateMaterial();
cyclus::Transaction trans = BuildTransaction();
LOG(cyclus::LEV_INFO4, "SrcFac") << "offers " << trans.resource()->quantity() <<
" kg of "
<< out_commod_ << ".";
SendOffer(trans);
LOG(cyclus::LEV_INFO3, "SrcFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::HandleTock(int time) {
LOG(cyclus::LEV_INFO3, "SrcFac") << FacName() << " is tocking {";
// check what orders are waiting,
// send material if you have it now
while (!ordersWaiting_.empty()) {
cyclus::Transaction order = ordersWaiting_.front()->trans();
LOG(cyclus::LEV_INFO3, "SrcFac") << "Order is for: " <<
order.resource()->quantity();
LOG(cyclus::LEV_INFO3, "SrcFac") << "Inventory is: " << inventory_.quantity();
if (order.resource()->quantity() - inventory_.quantity() > cyclus::eps()) {
LOG(cyclus::LEV_INFO3, "SrcFac") <<
"Not enough inventory. Waitlisting remaining orders.";
break;
} else {
LOG(cyclus::LEV_INFO3, "SrcFac") << "Satisfying order.";
order.ApproveTransfer();
ordersWaiting_.pop_front();
}
}
// For now, lets just print out what we have at each timestep.
LOG(cyclus::LEV_INFO4, "SrcFac") << "SourceFacility " << this->ID()
<< " is holding " << this->inventory_.quantity()
<< " units of material at the close of month " << time
<< ".";
LOG(cyclus::LEV_INFO3, "SrcFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::ReceiveMessage(cyclus::Message::Ptr msg) {
if (msg->trans().supplier() == this) {
// file the order
ordersWaiting_.push_front(msg);
LOG(cyclus::LEV_INFO5, "SrcFac") << name() << " just received an order.";
LOG(cyclus::LEV_INFO5, "SrcFac") << "for " <<
msg->trans().resource()->quantity()
<< " of " << msg->trans().commod();
} else {
throw cyclus::Error("SourceFacility is not the supplier of this msg.");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<cyclus::Resource::Ptr> SourceFacility::RemoveResource(
cyclus::Transaction order) {
return cyclus::MatBuff::ToRes(inventory_.PopQty(order.resource()->quantity()));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetCommodity(std::string name) {
out_commod_ = name;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::commodity() {
return out_commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetCapacity(double capacity) {
capacity_ = capacity;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::capacity() {
return capacity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetRecipe(std::string name) {
recipe_name_ = name;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SourceFacility::recipe() {
return recipe_name_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SetMaxInventorySize(double size) {
inventory_.SetCapacity(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::MaxInventorySize() {
return inventory_.capacity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SourceFacility::InventorySize() {
return inventory_.quantity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::GenerateMaterial() {
using cyclus::Model;
using cyclus::Material;
double empty_space = inventory_.space();
if (empty_space < cyclus::eps()) {
return; // no room
}
Material::Ptr newMat;
double amt = capacity_;
cyclus::Context* ctx = Model::context();
if (amt <= empty_space) {
newMat = Material::Create(ctx, amt, ctx->GetRecipe(recipe_name_));
} else {
newMat = Material::Create(ctx, empty_space, ctx->GetRecipe(recipe_name_));
}
inventory_.PushOne(newMat);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Transaction SourceFacility::BuildTransaction() {
using cyclus::Model;
using cyclus::Material;
// there is no minimum amount a source facility may send
double min_amt = 0;
double offer_amt = inventory_.quantity();
cyclus::Context* ctx = Model::context();
Material::Ptr trade_res = Material::Create(ctx,
offer_amt,
ctx->GetRecipe(recipe()));
cyclus::Transaction trans(this, cyclus::OFFER);
trans.SetCommod(out_commod_);
trans.SetMinFrac(min_amt / offer_amt);
trans.SetPrice(commod_price_);
trans.SetResource(trade_res);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SourceFacility::SendOffer(cyclus::Transaction trans) {
cyclus::MarketModel* market = cyclus::MarketModel::MarketForCommod(out_commod_);
Communicator* recipient = dynamic_cast<Communicator*>(market);
cyclus::Message::Ptr msg(new cyclus::Message(this, recipient, trans));
msg->SendOn();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Model* ConstructSourceFacility(cyclus::Context* ctx) {
return new SourceFacility(ctx);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" void DestructSourceFacility(cyclus::Model* model) {
delete model;
}
} // namespace cycamore
<|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) 2016 Scylladb, Ltd.
*/
#include "lz4_compressor.hh"
#include "core/byteorder.hh"
namespace rpc {
const sstring lz4_compressor::factory::_name = "LZ4";
sstring lz4_compressor::compress(size_t head_space, sstring data) {
head_space += 4;
sstring dst(sstring::initialized_later(), head_space + LZ4_compressBound(data.size()));
auto size = LZ4_compress_default(data.begin(), dst.begin() + head_space, data.size(), dst.size() - head_space);
dst.resize(size + head_space);
*unaligned_cast<uint32_t*>(dst.data() + 4) = cpu_to_le(data.size());
return dst;
}
temporary_buffer<char> lz4_compressor::decompress(temporary_buffer<char> data) {
if (data.size() < 4) {
return temporary_buffer<char>();
} else {
auto size = le_to_cpu(*unaligned_cast<uint32_t*>(data.begin()));
if (size) {
temporary_buffer<char> dst(size);
LZ4_decompress_fast(data.begin() + 4, dst.get_write(), dst.size());
return dst;
} else {
// special case: if uncompressed size is zero it means that data was not compressed
// compress side still not use this but we want to be ready for the future
data.trim_front(4);
return std::move(data);
}
}
}
}
<commit_msg>rpc: adjust lz4 compression for older lz4.h<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) 2016 Scylladb, Ltd.
*/
#include "lz4_compressor.hh"
#include "core/byteorder.hh"
namespace rpc {
const sstring lz4_compressor::factory::_name = "LZ4";
sstring lz4_compressor::compress(size_t head_space, sstring data) {
head_space += 4;
sstring dst(sstring::initialized_later(), head_space + LZ4_compressBound(data.size()));
// Can't use LZ4_compress_default() since it's too new.
// Safe since output buffer is sized properly.
auto size = LZ4_compress(data.begin(), dst.begin() + head_space, data.size());
dst.resize(size + head_space);
*unaligned_cast<uint32_t*>(dst.data() + 4) = cpu_to_le(data.size());
return dst;
}
temporary_buffer<char> lz4_compressor::decompress(temporary_buffer<char> data) {
if (data.size() < 4) {
return temporary_buffer<char>();
} else {
auto size = le_to_cpu(*unaligned_cast<uint32_t*>(data.begin()));
if (size) {
temporary_buffer<char> dst(size);
LZ4_decompress_fast(data.begin() + 4, dst.get_write(), dst.size());
return dst;
} else {
// special case: if uncompressed size is zero it means that data was not compressed
// compress side still not use this but we want to be ready for the future
data.trim_front(4);
return std::move(data);
}
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: SpatialObjectTransforms.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// \index{itk::SpatialObjectTransforms}
// This example describes the different transformations associated with a SpatialObject.
//
// Software Guide : EndLatex
#include "itkSpatialObject.h"
int main( int argc, char *argv[] )
{
// Software Guide : BeginLatex
//
// Like the previous example, we create two SpatialObjects and give
// them the names "First Object"
// and "Second Object" respectively.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::SpatialObject<2> SpatialObjectType;
typedef SpatialObjectType::TransformType TransformType;
SpatialObjectType::Pointer object1 = SpatialObjectType ::New();
object1->GetProperty()->SetName("First Object");
SpatialObjectType::Pointer object2 = SpatialObjectType ::New();
object2->GetProperty()->SetName("Second Object");
object1->AddSpatialObject(object2);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// SpatialObject keeps three transformations internally:
// the IndexToObjectTransform, the ObjectToParentTransform and the
// ObjectToWorldTransform. To simplify, the global transformation
// IndexToWorldTransform and its inverse, WorldToIndexTransform, are also kept
// internally.
//
// The two main transformations, IndexToObjectTransform and ObjectToParentTransform, are applied
// successively. ObjectToParentTransform is applied to children.
//
// The IndexToObjectTransform transforms points from the internal data coordinate
// system of the object (typically the indices of the image from which
// the object was defined) to ``physical" space (which accounts
// for the spacing, orientation, and offset of the indices).
//
// The ObjectToParentTransform transforms points from the object-specific
// ``physical" space to the ``physical" space of its parent object.
//
// The ObjectToWorldTransformation transforms points from the global coordinate
// frame. This is useful when the position of the object is known only in the global
// coordinate frame. Note that by setting this transform, the ObjectToParent transform is recomputed.
//
// These transformations use \doxygen{FixedCenterOfRotationAffineTransform}. They are created in
// the constructor of the spatial \doxygen{SpatialObject}
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// First we define an index scaling factor of 2 for the object2.
// This is done by setting the ScaleComponent of the IndexToObjectTransform.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double scale[2];
scale[0]=2;
scale[1]=2;
object2->GetIndexToObjectTransform()->SetScaleComponent(scale);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Next, we apply an offset on the ObjectToParentTransform of the child object
// Therefore, object2 is now translated by a vector [4,3] regarding to its
// parent.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OffsetType Object2ToObject1Offset;
Object2ToObject1Offset[0] = 4;
Object2ToObject1Offset[1] = 3;
object2->GetObjectToParentTransform()->SetOffset(Object2ToObject1Offset);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// To make the previous modification on the transformations effective, we should
// invoke the ComputeObjectToWorldTransform() which recomputes all dependent
// transformations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
object2->ComputeObjectToWorldTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now display the ObjectToWorldTransform for both objects.
// One should notice that the \doxygen{FixedCenterOfRotationAffineTransform} derives
// from \doxygen{AffineTransform} and therefore the only valid data for the transformation
// is the Matrix and the Offset. For instance, when we set the ScaleComponent() value
// the internal Matrix is recomputed to reflect the new ScaleComponent.
//
// The \doxygen{FixedCenterOfRotationAffineTransform} performs the following computation
//
// \begin{equation}
// X' = R \cdot \left( S \cdot X - C \right) + C + V
// \end{equation}
//
// Where $R$ is the rotation matrix, $S$ is a scaling factor, $C$ is the center
// of rotation and $V$ is a translation vector or offset.
// Therefore the affine matrix $M$ and the affine offset $T$ are defined as:
//
// \begin{equation}
// M = R \cdot S
// \end{equation}
// \begin{equation}
// T = C + V - R \cdot C
// \end{equation}
//
// This means that \code{GetScaleComponent()} and \code{GetOffsetComponent()}
// as well as the \code{GetMatrixComponent()} might not be set to the expected
// value, especially if the transformation results from a composition with
// another transformation since the composition is done using the Matrix and
// the Offset of the affine transformation.
//
// Next, we show the two affine transformations corresponding to the two objects
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "object2 IndexToObject Matrix: " << std::endl;
std::cout << object2->GetIndexToObjectTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToObject Offset: ";
std::cout << object2->GetIndexToObjectTransform()->GetOffset() << std::endl;
std::cout << "object2 IndexToWorld Matrix: " << std::endl;
std::cout << object2->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToWorld Offset: ";
std::cout << object2->GetIndexToWorldTransform()->GetOffset() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, we decide to translate the first object which is the parent of the second
// by a vector [3,3]. This is still done by setting the offset of the ObjectToParentTransform.
// This can also be done by setting the ObjectToWorldTransform because the first object
// does not have any parent and therefore is attached to the world coordinate frame.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OffsetType Object1ToWorldOffset;
Object1ToWorldOffset[0] = 3;
Object1ToWorldOffset[1] = 3;
object1->GetObjectToParentTransform()->SetOffset(Object1ToWorldOffset);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we should invoke \code{ComputeObjectToWorldTransform()} on the modified
// object. This will propagate the transformation through all the children.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
object1->ComputeObjectToWorldTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
//
// \begin{figure} \center
// \includegraphics[width=\textwidth]{SpatialObjectTransforms.eps}
// \itkcaption[SpatialObject Transform Computations]{Physical positions of the
// two objects in the world frame. (shapes are merely for illustration
// purposes)}
// \label{fig:SpatialObjectTransforms}
// \end{figure}
//
// Figure~\ref{fig:SpatialObjectTransforms} shows our set of transformations.
//
// Finally, we display the resulting affine transformations.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "object1 IndexToWorld Matrix: " << std::endl;
std::cout << object1->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object1 IndexToWorld Offset: ";
std::cout << object1->GetIndexToWorldTransform()->GetOffset() << std::endl;
std::cout << "object2 IndexToWorld Matrix: " << std::endl;
std::cout << object2->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToWorld Offset: ";
std::cout << object2->GetIndexToWorldTransform()->GetOffset() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of this second example looks like the following:
//object2 IndexToObject Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToObject Offset: 0 0
//
//object2 IndexToWorld Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToWorld Offset: 4 3
//
//object1 IndexToWorld Matrix:
//
//1 0
//
//0 1
//
//object1 IndexToWorld Offset: 3 3
//
//object2 IndexToWorld Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToWorld Offset: 7 6
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>ENH: figure size fixed.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: SpatialObjectTransforms.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// \index{itk::SpatialObjectTransforms}
// This example describes the different transformations associated with a SpatialObject.
//
// Software Guide : EndLatex
#include "itkSpatialObject.h"
int main( int argc, char *argv[] )
{
// Software Guide : BeginLatex
//
// Like the previous example, we create two SpatialObjects and give
// them the names "First Object"
// and "Second Object" respectively.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::SpatialObject<2> SpatialObjectType;
typedef SpatialObjectType::TransformType TransformType;
SpatialObjectType::Pointer object1 = SpatialObjectType ::New();
object1->GetProperty()->SetName("First Object");
SpatialObjectType::Pointer object2 = SpatialObjectType ::New();
object2->GetProperty()->SetName("Second Object");
object1->AddSpatialObject(object2);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// SpatialObject keeps three transformations internally:
// the IndexToObjectTransform, the ObjectToParentTransform and the
// ObjectToWorldTransform. To simplify, the global transformation
// IndexToWorldTransform and its inverse, WorldToIndexTransform, are also kept
// internally.
//
// The two main transformations, IndexToObjectTransform and ObjectToParentTransform, are applied
// successively. ObjectToParentTransform is applied to children.
//
// The IndexToObjectTransform transforms points from the internal data coordinate
// system of the object (typically the indices of the image from which
// the object was defined) to ``physical" space (which accounts
// for the spacing, orientation, and offset of the indices).
//
// The ObjectToParentTransform transforms points from the object-specific
// ``physical" space to the ``physical" space of its parent object.
//
// The ObjectToWorldTransformation transforms points from the global coordinate
// frame. This is useful when the position of the object is known only in the global
// coordinate frame. Note that by setting this transform, the ObjectToParent transform is recomputed.
//
// These transformations use \doxygen{FixedCenterOfRotationAffineTransform}. They are created in
// the constructor of the spatial \doxygen{SpatialObject}
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// First we define an index scaling factor of 2 for the object2.
// This is done by setting the ScaleComponent of the IndexToObjectTransform.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double scale[2];
scale[0]=2;
scale[1]=2;
object2->GetIndexToObjectTransform()->SetScaleComponent(scale);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Next, we apply an offset on the ObjectToParentTransform of the child object
// Therefore, object2 is now translated by a vector [4,3] regarding to its
// parent.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OffsetType Object2ToObject1Offset;
Object2ToObject1Offset[0] = 4;
Object2ToObject1Offset[1] = 3;
object2->GetObjectToParentTransform()->SetOffset(Object2ToObject1Offset);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// To make the previous modification on the transformations effective, we should
// invoke the ComputeObjectToWorldTransform() which recomputes all dependent
// transformations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
object2->ComputeObjectToWorldTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now display the ObjectToWorldTransform for both objects.
// One should notice that the \doxygen{FixedCenterOfRotationAffineTransform} derives
// from \doxygen{AffineTransform} and therefore the only valid data for the transformation
// is the Matrix and the Offset. For instance, when we set the ScaleComponent() value
// the internal Matrix is recomputed to reflect the new ScaleComponent.
//
// The \doxygen{FixedCenterOfRotationAffineTransform} performs the following computation
//
// \begin{equation}
// X' = R \cdot \left( S \cdot X - C \right) + C + V
// \end{equation}
//
// Where $R$ is the rotation matrix, $S$ is a scaling factor, $C$ is the center
// of rotation and $V$ is a translation vector or offset.
// Therefore the affine matrix $M$ and the affine offset $T$ are defined as:
//
// \begin{equation}
// M = R \cdot S
// \end{equation}
// \begin{equation}
// T = C + V - R \cdot C
// \end{equation}
//
// This means that \code{GetScaleComponent()} and \code{GetOffsetComponent()}
// as well as the \code{GetMatrixComponent()} might not be set to the expected
// value, especially if the transformation results from a composition with
// another transformation since the composition is done using the Matrix and
// the Offset of the affine transformation.
//
// Next, we show the two affine transformations corresponding to the two objects
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "object2 IndexToObject Matrix: " << std::endl;
std::cout << object2->GetIndexToObjectTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToObject Offset: ";
std::cout << object2->GetIndexToObjectTransform()->GetOffset() << std::endl;
std::cout << "object2 IndexToWorld Matrix: " << std::endl;
std::cout << object2->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToWorld Offset: ";
std::cout << object2->GetIndexToWorldTransform()->GetOffset() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, we decide to translate the first object which is the parent of the second
// by a vector [3,3]. This is still done by setting the offset of the ObjectToParentTransform.
// This can also be done by setting the ObjectToWorldTransform because the first object
// does not have any parent and therefore is attached to the world coordinate frame.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OffsetType Object1ToWorldOffset;
Object1ToWorldOffset[0] = 3;
Object1ToWorldOffset[1] = 3;
object1->GetObjectToParentTransform()->SetOffset(Object1ToWorldOffset);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we should invoke \code{ComputeObjectToWorldTransform()} on the modified
// object. This will propagate the transformation through all the children.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
object1->ComputeObjectToWorldTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
//
// \begin{figure} \center
// \includegraphics[width=0.5\textwidth]{SpatialObjectTransforms.eps}
// \itkcaption[SpatialObject Transform Computations]{Physical positions of the
// two objects in the world frame. (shapes are merely for illustration
// purposes)}
// \label{fig:SpatialObjectTransforms}
// \end{figure}
//
// Figure~\ref{fig:SpatialObjectTransforms} shows our set of transformations.
//
// Finally, we display the resulting affine transformations.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "object1 IndexToWorld Matrix: " << std::endl;
std::cout << object1->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object1 IndexToWorld Offset: ";
std::cout << object1->GetIndexToWorldTransform()->GetOffset() << std::endl;
std::cout << "object2 IndexToWorld Matrix: " << std::endl;
std::cout << object2->GetIndexToWorldTransform()->GetMatrix() << std::endl;
std::cout << "object2 IndexToWorld Offset: ";
std::cout << object2->GetIndexToWorldTransform()->GetOffset() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of this second example looks like the following:
//object2 IndexToObject Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToObject Offset: 0 0
//
//object2 IndexToWorld Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToWorld Offset: 4 3
//
//object1 IndexToWorld Matrix:
//
//1 0
//
//0 1
//
//object1 IndexToWorld Offset: 3 3
//
//object2 IndexToWorld Matrix:
//
//2 0
//
//0 2
//
//object2 IndexToWorld Offset: 7 6
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
//
// ChronoParallel unit test for MPR collision detection
// =============================================================================
#include <stdio.h>
#include <vector>
#include <cmath>
#include "unit_testing.h"
#include "chrono_parallel/physics/MPMUtils.h"
using namespace chrono;
int main(int argc, char* argv[]) {
real3 min_bounding_point(-1, -1, -1);
real3 max_bounding_point(1, 1, 1);
real radius = 0.25;
max_bounding_point = real3(Max(Ceil(max_bounding_point.x), Ceil(max_bounding_point.x + radius * 6)),
Max(Ceil(max_bounding_point.y), Ceil(max_bounding_point.y + radius * 6)),
Max(Ceil(max_bounding_point.z), Ceil(max_bounding_point.z + radius * 6)));
min_bounding_point = real3(Min(Floor(min_bounding_point.x), Floor(min_bounding_point.x - radius * 6)),
Min(Floor(min_bounding_point.y), Floor(min_bounding_point.y - radius * 6)),
Min(Floor(min_bounding_point.z), Floor(min_bounding_point.z - radius * 6)));
real3 diag = max_bounding_point - min_bounding_point;
vec3 bins_per_axis = vec3(diag / (radius * 2));
real3 point_a = real3(0.44236, 0.65093, 0.24482);
real3 point_b = real3(0.63257, 0.83347, 0.74071);
real3 point_c = real3(0.82623, 0.92491, 0.92109);
const real bin_edge = radius * 2;
const real inv_bin_edge = real(1) / bin_edge;
printf("bins_per_axis [%d %d %d]\n", bins_per_axis.x, bins_per_axis.y, bins_per_axis.z);
printf("max_bounding_point [%f %f %f]\n", max_bounding_point.x, max_bounding_point.y, max_bounding_point.z);
printf("min_bounding_point [%f %f %f]\n", min_bounding_point.x, min_bounding_point.y, min_bounding_point.z);
{
printf("Grid Coord\n");
int x = GridCoord(point_a.x, inv_bin_edge, min_bounding_point.x);
int y = GridCoord(point_a.y, inv_bin_edge, min_bounding_point.y);
int z = GridCoord(point_a.z, inv_bin_edge, min_bounding_point.z);
WeakEqual(x, 7);
WeakEqual(y, 7);
WeakEqual(z, 6);
}
{
printf("Current Node\n");
WeakEqual(NodeLocation(5, 5, 4, bin_edge, min_bounding_point), real3(-.5, -.5, -1));
WeakEqual(NodeLocation(9, 9, 8, bin_edge, min_bounding_point), real3(1.5, 1.5, 1));
}
{
printf("N\n");
WeakEqual(N(point_a - NodeLocation(5, 5, 4, bin_edge, min_bounding_point), inv_bin_edge), 0);
WeakEqual(N(point_a - NodeLocation(7, 7, 7, bin_edge, min_bounding_point), inv_bin_edge), 0.1822061256, 1e-10);
}
{ // Each node should have 125 surrounding nodes
int ind = 0;
real3 xi = point_a;
printf("Grid Hash Count\n");
LOOPOVERNODES(real3 p = point_a - current_node_location;
// printf("[%d %d %d][%d %d] N:%f\n", i, j, k, current_node, ind, N(p, inv_bin_edge)); //
ind++; //
)
WeakEqual(ind, 125);
}
real youngs_modulus = (real)1.4e5;
real poissons_ratio = (real).2;
real theta_c = (real)2.5e-2;
real theta_s = (real)7.5e-3;
real lambda =
youngs_modulus * poissons_ratio / (((real)1. + poissons_ratio) * ((real)1. - (real)2. * poissons_ratio));
real mu = youngs_modulus / ((real)2. * ((real)1. + poissons_ratio));
real initial_density = (real)4e2;
real alpha = (real).95;
real hardening_coefficient = (real)10.;
{
const Mat33 FE = Mat33(0.8147, 0.9058, 0.1270, 0.9134, 0.6324, .0975, 0.2785, 0.5469, 0.9575) * 100;
const Mat33 FP = Mat33(1, 0, 5, 2, 1, 6, 3, 4, 0) * (.001);
Mat33 PED = Potential_Energy_Derivative(FE, FP, mu, lambda, hardening_coefficient);
// Print(PED, "PED");
}
{
const Mat33 FE = Mat33(0.8147, 0.9058, 0.1270, 0.9134, 0.6324, .0975, 0.2785, 0.5469, 0.9575);
const Mat33 FP = Mat33(1, 0, 5, 2, 1, 6, 3, 4, 0);
Mat33 RD = Rotational_Derivative(FE, FP);
// Print(RD, "RD");
WeakEqual(RD, Mat33(-0.4388320607360907121829996, -2.5644905725011524211254255, 2.6523953516380869288582289,
3.3403002881859262807040523, -0.3555579545919572703738254, -0.1151537247848418710205465,
-1.6067063031830095543028847, 0.5767590099191256536315109, -0.3543936405970238290308316),
1e-6);
}
}
<commit_msg>update mpm unit tests<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
//
// ChronoParallel unit test for MPR collision detection
// =============================================================================
#include <stdio.h>
#include <vector>
#include <cmath>
#include "unit_testing.h"
#include "chrono_parallel/physics/MPMUtils.h"
using namespace chrono;
int main(int argc, char* argv[]) {
real3 min_bounding_point(-1, -1, -1);
real3 max_bounding_point(1, 1, 1);
real radius = 0.25;
max_bounding_point = real3(Max(Ceil(max_bounding_point.x), Ceil(max_bounding_point.x + radius * 6)),
Max(Ceil(max_bounding_point.y), Ceil(max_bounding_point.y + radius * 6)),
Max(Ceil(max_bounding_point.z), Ceil(max_bounding_point.z + radius * 6)));
min_bounding_point = real3(Min(Floor(min_bounding_point.x), Floor(min_bounding_point.x - radius * 6)),
Min(Floor(min_bounding_point.y), Floor(min_bounding_point.y - radius * 6)),
Min(Floor(min_bounding_point.z), Floor(min_bounding_point.z - radius * 6)));
real3 diag = max_bounding_point - min_bounding_point;
vec3 bins_per_axis = vec3(diag / (radius * 2));
real3 point_a = real3(0.44236, 0.65093, 0.24482);
real3 point_b = real3(0.63257, 0.83347, 0.74071);
real3 point_c = real3(0.82623, 0.92491, 0.92109);
const real bin_edge = radius * 2;
const real inv_bin_edge = real(1) / bin_edge;
printf("bins_per_axis [%d %d %d]\n", bins_per_axis.x, bins_per_axis.y, bins_per_axis.z);
printf("max_bounding_point [%f %f %f]\n", max_bounding_point.x, max_bounding_point.y, max_bounding_point.z);
printf("min_bounding_point [%f %f %f]\n", min_bounding_point.x, min_bounding_point.y, min_bounding_point.z);
{
printf("Grid Coord\n");
int x = GridCoord(point_a.x, inv_bin_edge, min_bounding_point.x);
int y = GridCoord(point_a.y, inv_bin_edge, min_bounding_point.y);
int z = GridCoord(point_a.z, inv_bin_edge, min_bounding_point.z);
WeakEqual(x, 7);
WeakEqual(y, 7);
WeakEqual(z, 6);
}
{
printf("Current Node\n");
WeakEqual(NodeLocation(5, 5, 4, bin_edge, min_bounding_point), real3(-.5, -.5, -1));
WeakEqual(NodeLocation(9, 9, 8, bin_edge, min_bounding_point), real3(1.5, 1.5, 1));
}
{
printf("N\n");
WeakEqual(N(point_a - NodeLocation(5, 5, 4, bin_edge, min_bounding_point), inv_bin_edge), 0);
WeakEqual(N(point_a - NodeLocation(7, 7, 7, bin_edge, min_bounding_point), inv_bin_edge), 0.1822061256, C_EPSILON);
}
{ // Each node should have 125 surrounding nodes
int ind = 0;
real3 xi = point_a;
printf("Grid Hash Count\n");
LOOPOVERNODES(real3 p = point_a - current_node_location;
// printf("[%d %d %d][%d %d] N:%f\n", i, j, k, current_node, ind, N(p, inv_bin_edge)); //
ind++; //
)
WeakEqual(ind, 125);
}
real youngs_modulus = (real)1.4e5;
real poissons_ratio = (real).2;
real theta_c = (real)2.5e-2;
real theta_s = (real)7.5e-3;
real lambda =
youngs_modulus * poissons_ratio / (((real)1. + poissons_ratio) * ((real)1. - (real)2. * poissons_ratio));
real mu = youngs_modulus / ((real)2. * ((real)1. + poissons_ratio));
real initial_density = (real)4e2;
real alpha = (real).95;
real hardening_coefficient = (real)10.;
{
printf("Potential_Energy_Derivative\n");
const Mat33 FE = Mat33(0.8147, 0.9058, 0.1270, 0.9134, 0.6324, .0975, 0.2785, 0.5469, 0.9575) * 100;
const Mat33 FP = Mat33(1, 0, 5, 2, 1, 6, 3, 4, 0) * (.001);
Mat33 PED = Potential_Energy_Derivative(FE, FP, mu, lambda, hardening_coefficient);
// Print(PED, "PED");
}
{
printf("Rotational_Derivative\n");
const Mat33 FE = Mat33(0.8147, 0.9058, 0.1270, 0.9134, 0.6324, .0975, 0.2785, 0.5469, 0.9575);
const Mat33 FP = Mat33(1, 0, 5, 2, 1, 6, 3, 4, 0);
Mat33 RD = Rotational_Derivative(FE, FP);
// Print(RD, "RD");
WeakEqual(RD, Mat33(-0.4388320607360907121829996, -2.5644905725011524211254255, 2.6523953516380869288582289,
3.3403002881859262807040523, -0.3555579545919572703738254, -0.1151537247848418710205465,
-1.6067063031830095543028847, 0.5767590099191256536315109, -0.3543936405970238290308316),
1e-6);
}
{
printf("Rotational_Derivative_Simple\n");
const Mat33 FE = Mat33(0.8147, 0.9058, 0.1270, 0.9134, 0.6324, .0975, 0.2785, 0.5469, 0.9575);
const Mat33 FP = Mat33(1, 0, 5, 2, 1, 6, 3, 4, 0);
Mat33 U, V, R, S, W;
real3 E;
SVD(FE, U, E, V);
// Perform polar decomposition F = R*S
R = MultTranspose(U, V);
S = V * MultTranspose(Mat33(E), V);
// See tech report end of page 2
W = TransposeMult(R, FP);
Mat33 RD1 = Rotational_Derivative_Simple(R, S, FP);
Mat33 RD2 = Rotational_Derivative(FE, FP);
// Print(RD1,"RD1");
// Print(RD2,"RD2");
WeakEqual(RD1, RD2, 1e-6);
}
}
<|endoftext|> |
<commit_before>#include <sequanto/qtautomationeventfilter.h>
#include <cassert>
using namespace sequanto::automation;
const int QtAutomationMoveEvent::ID = QEvent::registerEventType();
QtAutomationMoveEvent::QtAutomationMoveEvent ( int _x, int _y )
: QEvent( (QEvent::Type) ID),
m_position(_x, _y)
{
}
const QPoint & QtAutomationMoveEvent::position()
{
return m_position;
}
QtAutomationMoveEvent::~QtAutomationMoveEvent()
{
}
const int QtAutomationResizeEvent::ID = QEvent::registerEventType();
QtAutomationResizeEvent::QtAutomationResizeEvent ( int _width, int _height )
: QEvent( (QEvent::Type) ID),
m_size(_width, _height)
{
}
const QSize & QtAutomationResizeEvent::size()
{
return m_size;
}
QtAutomationResizeEvent::~QtAutomationResizeEvent()
{
}
QtAutomationEventFilter::QtAutomationEventFilter ( ListNode * _node, QObject * _parent )
: QObject(_parent),
m_node ( _node )
{
}
bool QtAutomationEventFilter::eventFilter ( QObject * _object, QEvent * _event )
{
switch ( _event->type() )
{
case QEvent::ChildAdded:
case QEvent::ChildRemoved:
m_node->SendUpdate();
break;
case QEvent::Move:
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_X) )->SendUpdate();
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_Y) )->SendUpdate();
break;
case QEvent::Resize:
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_WIDTH) )->SendUpdate();
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_HEIGHT) )->SendUpdate();
break;
case QEvent::Destroy:
break;
}
if ( _event->type() == QtAutomationMoveEvent::ID )
{
QPoint position = dynamic_cast<QtAutomationMoveEvent*>(_event)->position();
qobject_cast<QWidget*> ( _object )->move ( position );
return true;
}
else if ( _event->type() == QtAutomationResizeEvent::ID )
{
QSize size = dynamic_cast<QtAutomationResizeEvent*>(_event)->size();
qobject_cast<QWidget*> ( _object )->resize ( size );
return true;
}
else
{
return QObject::eventFilter(_object, _event );
}
}
QtAutomationEventFilter::~QtAutomationEventFilter ()
{
}
<commit_msg>Update issue 13<commit_after>#include <sequanto/qtautomationeventfilter.h>
#include <sequanto/ui.h>
#include <cassert>
using namespace sequanto::automation;
const int QtAutomationMoveEvent::ID = QEvent::registerEventType();
QtAutomationMoveEvent::QtAutomationMoveEvent ( int _x, int _y )
: QEvent( (QEvent::Type) ID),
m_position(_x, _y)
{
}
const QPoint & QtAutomationMoveEvent::position()
{
return m_position;
}
QtAutomationMoveEvent::~QtAutomationMoveEvent()
{
}
const int QtAutomationResizeEvent::ID = QEvent::registerEventType();
QtAutomationResizeEvent::QtAutomationResizeEvent ( int _width, int _height )
: QEvent( (QEvent::Type) ID),
m_size(_width, _height)
{
}
const QSize & QtAutomationResizeEvent::size()
{
return m_size;
}
QtAutomationResizeEvent::~QtAutomationResizeEvent()
{
}
QtAutomationEventFilter::QtAutomationEventFilter ( ListNode * _node, QObject * _parent )
: QObject(_parent),
m_node ( _node )
{
}
bool QtAutomationEventFilter::eventFilter ( QObject * _object, QEvent * _event )
{
switch ( _event->type() )
{
case QEvent::ChildAdded:
case QEvent::ChildRemoved:
m_node->SendUpdate();
break;
case QEvent::Move:
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_X) )->SendUpdate();
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_Y) )->SendUpdate();
break;
case QEvent::Resize:
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_WIDTH) )->SendUpdate();
dynamic_cast<IntegerPropertyNode*> ( m_node->FindChild(SQ_UI_NODE_HEIGHT) )->SendUpdate();
break;
case QEvent::Destroy:
break;
}
if ( _event->type() == QtAutomationMoveEvent::ID )
{
QPoint position = dynamic_cast<QtAutomationMoveEvent*>(_event)->position();
qobject_cast<QWidget*> ( _object )->move ( position );
return true;
}
else if ( _event->type() == QtAutomationResizeEvent::ID )
{
QSize size = dynamic_cast<QtAutomationResizeEvent*>(_event)->size();
qobject_cast<QWidget*> ( _object )->resize ( size );
return true;
}
else
{
return QObject::eventFilter(_object, _event );
}
}
QtAutomationEventFilter::~QtAutomationEventFilter ()
{
}
<|endoftext|> |
<commit_before>// residual.cpp: example program to show exact residual calucation using the quire
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <ostream>
#include <limits>
#include <numeric> // nextafter
// select the number systems we would like to compare
#include <universal/integer/integer>
#include <universal/fixpnt/fixpnt>
#include <universal/areal/areal>
#include <universal/posit/posit>
#include <universal/lns/lns>
#include <universal/blas/blas>
#include <universal/blas/generators/frank.hpp>
template<typename Scalar>
void FrankMatrixTest(int N) {
using namespace std;
using Vector = sw::unum::blas::vector<Scalar>;
using Matrix = sw::unum::blas::matrix<Scalar>;
Matrix A = sw::unum::blas::frank<Scalar>(N);
cout << "Frank matrix order " << N << endl;
Vector b(N), x(N);
x = Scalar(1);
b = A * x;
// cout << "right hand side [" << b << "]\n";
x = solve(A, b);
// cout << "solution vector [" << x << "]\n";
Vector e = A * x - b;
cout << "1-norm of error vector: " << norm1(e) << endl;
}
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
cout << "Residual calculations\n";
streamsize precision = cout.precision();
vector<int> sizes = { 5, 15, 45, 95 };
for (auto N : sizes) {
FrankMatrixTest<float>(N);
FrankMatrixTest<posit<32, 2>>(N);
}
cout << setprecision(precision);
cout << endl;
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<commit_msg>implementing quire-enabled exact residual calculation<commit_after>// residual.cpp: example program to show exact residual calucation using the quire
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <ostream>
#include <limits>
#include <numeric> // nextafter
// select the number systems we would like to compare
#include <universal/integer/integer>
#include <universal/fixpnt/fixpnt>
#include <universal/areal/areal>
#include <universal/posit/posit>
#include <universal/lns/lns>
#include <universal/blas/blas>
#include <universal/blas/generators/frank.hpp>
/*
template<typename Scalar>
sw::unum::blas::vector<Scalar> residual(const sw::unum::blas::matrix<Scalar>& A, const sw::unum::blas::vector<Scalar>& x, const sw::unum::blas::vector<Scalar>& b) {
using namespace sw::unum;
using namespace sw::unum::blas;
using Vector = sw::unum::blas::vector<Scalar>;
size_t M = num_rows(A);
size_t N = num_cols(A);
Vector r(M);
for (size_t i = 0; i < M; ++i) {
quire<Scalar> q(-b);
for (size_t j = 0; j < N; ++j) {
q += quire_mul(A(i, j), x(j));
}
r(i) = q.to_value();
}
return r;
}
*/
template<size_t nbits, size_t es, size_t capacity = 10>
sw::unum::blas::vector<sw::unum::posit<nbits, es>> residual(const sw::unum::blas::matrix<sw::unum::posit<nbits, es>>& A, const sw::unum::blas::vector<sw::unum::posit<nbits, es>>& x, const sw::unum::blas::vector<sw::unum::posit<nbits, es>>& b) {
using namespace sw::unum;
using namespace sw::unum::blas;
using Scalar = sw::unum::posit<nbits, es>;
using Vector = sw::unum::blas::vector<Scalar>;
size_t M = num_rows(A);
size_t N = num_cols(A);
Vector r(M);
for (size_t i = 0; i < M; ++i) {
quire<nbits, es, capacity> q(-b(i));
for (size_t j = 0; j < N; ++j) {
q += quire_mul(A(i, j), x(j));
}
convert(q.to_value(), r(i));
}
return r;
}
template<typename Scalar>
void FrankMatrixTest(int N) {
using namespace std;
using Vector = sw::unum::blas::vector<Scalar>;
using Matrix = sw::unum::blas::matrix<Scalar>;
Matrix A = sw::unum::blas::frank<Scalar>(N);
cout << "Frank matrix order " << N << endl;
Vector b(N), x(N);
x = Scalar(1);
b = A * x;
// cout << "right hand side [" << b << "]\n";
x = solve(A, b);
// cout << "solution vector [" << x << "]\n";
Vector e = A * x - b;
cout << "1-norm of error vector: " << norm1(e) << endl;
}
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
cout << "Residual calculations\n";
streamsize precision = cout.precision();
/*
sw::unum::blas::vector<int> sizes = { 5, 15, 45, 95 };
for (auto N : sizes) {
FrankMatrixTest<float>(N);
FrankMatrixTest<posit<32, 2>>(N);
}
*/
using Scalar = posit<32, 2>;
using Vector = sw::unum::blas::vector<Scalar>;
using Matrix = sw::unum::blas::matrix<Scalar>;
constexpr int N = 5;
Matrix A = sw::unum::blas::frank<Scalar>(N);
Matrix LU(A);
cout << "Frank matrix order " << N << endl;
Vector b(N), x(N);
x = Scalar(1);
b = A * x;
cout << "right hand side [" << b << "]\n";
sw::unum::blas::vector<size_t> indx(N);
auto error = ludcmp(LU, indx);
x = lubksb(LU, indx, b);
cout << "solution vector [" << x << "]\n";
Vector e = A * x - b;
Vector r = residual(A, x, b);
cout << "Residual (non-quire) : " << e << endl;
cout << "Residual (quire) : " << r << endl;
Vector minposRef(N);
Scalar mp;
minpos<32, 2>(mp);
minposRef = mp;
cout << "Minpos reference : " << minposRef << endl;
cout << setprecision(precision);
cout << endl;
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#ifndef _LIB_NODETEXT_HPP__
#define _LIB_NODETEXT_HPP__
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <string>
#include <vector>
#include "renderizable.hpp"
namespace lib
{
namespace draw
{
class NodeText : public lib::draw::Renderizable
{
public:
enum Style
{
Regular = 0,
Bold = 1 << 0,
Italic = 1 << 1,
Underlined = 1 << 2,
StrikeThrough = 1 << 3
};
NodeText(const std::string &name);
NodeText(const std::string &name, const sf::String& string, const sf::Font& font, u32 characterSize = 30);
virtual ~NodeText();
void setString(const std::string &string);
void setFont(const sf::Font& font);
void setCharacterSize(u32 size);
void setStyle(u32 style);
void setColor(const Color& color);
const std::string &getString() const;
const sf::Font* getFont() const;
u32 getCharacterSize() const;
u32 getStyle() const;
const Color& getColor() const;
vector2df findCharacterPos(u32 index) const;
Rectf32 getLocalBounds() const;
Rectf32 getGlobalBounds() const;
private:
virtual u32 draw(lib::core::Window *window, RenderStates &states) override;
void ensureGeometryUpdate() const;
std::string m_string;
const sf::Font* m_font;
u32 m_characterSize;
u32 m_style;
Color m_color;
mutable VertexArray m_vertices;
mutable Rectf32 m_bounds;
mutable bool m_geometryNeedUpdate;
};
}
}
#endif
<commit_msg>Deleted unused headers<commit_after>#ifndef _LIB_NODETEXT_HPP__
#define _LIB_NODETEXT_HPP__
#include <SFML/Graphics/Font.hpp>
#include <string>
#include <vector>
#include "renderizable.hpp"
namespace lib
{
namespace draw
{
class NodeText : public lib::draw::Renderizable
{
public:
enum Style
{
Regular = 0,
Bold = 1 << 0,
Italic = 1 << 1,
Underlined = 1 << 2,
StrikeThrough = 1 << 3
};
NodeText(const std::string &name);
NodeText(const std::string &name, const sf::String& string, const sf::Font& font, u32 characterSize = 30);
virtual ~NodeText();
void setString(const std::string &string);
void setFont(const sf::Font& font);
void setCharacterSize(u32 size);
void setStyle(u32 style);
void setColor(const Color& color);
const std::string &getString() const;
const sf::Font* getFont() const;
u32 getCharacterSize() const;
u32 getStyle() const;
const Color& getColor() const;
vector2df findCharacterPos(u32 index) const;
Rectf32 getLocalBounds() const;
Rectf32 getGlobalBounds() const;
private:
virtual u32 draw(lib::core::Window *window, RenderStates &states) override;
void ensureGeometryUpdate() const;
std::string m_string;
const sf::Font* m_font;
u32 m_characterSize;
u32 m_style;
Color m_color;
mutable VertexArray m_vertices;
mutable Rectf32 m_bounds;
mutable bool m_geometryNeedUpdate;
};
}
}
#endif
<|endoftext|> |
<commit_before>#include "memcache_client_pool.h"
#include "vbucket_config.h"
#include "evpp/event_loop_thread_pool.h"
#include "likely.h"
namespace evmc {
#define GET_FILTER_KEY_POS(name, key) \
name = key.find(key_filter_); \
if (name == std::string::npos) { \
name = key.size() - 1; \
}
MemcacheClientPool::~MemcacheClientPool() {
}
void MemcacheClientPool::Stop(bool wait_thread_exit) {
loop_pool_.Stop(wait_thread_exit);
MemcacheClientBase::Stop();
}
bool MemcacheClientPool::Start() {
bool ok = loop_pool_.Start(true);
if (UNLIKELY(!ok)) {
LOG_ERROR << "loop pool start failed";
return false;
}
if (!MemcacheClientBase::Start(true)) {
loop_pool_.Stop(true);
LOG_ERROR << "vbucket init failed";
return false;
}
auto server_list = vbucket_config()->server_list();
// 须先构造memc_client_map_数组,再各个元素取地址,否则地址不稳定,可能崩溃
for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) {
memc_client_map_.emplace_back(MemcClientMap());
evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i);
for (size_t svr = 0; svr < server_list.size(); ++svr) {
auto & client_map = memc_client_map_.back();
BuilderMemClient(loop, server_list[svr], client_map, timeout_ms_);
}
}
for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) {
evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i);
loop->set_context(evpp::Any(&memc_client_map_[i]));
}
return ok;
}
void MemcacheClientPool::Set(evpp::EventLoop* caller_loop, const std::string& key, const std::string& value, uint32_t flags,
uint32_t expire, SetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<SetCommand>(caller_loop, vbucket, key, value, flags, expire, callback);
LaunchCommand(command);
}
void MemcacheClientPool::Remove(evpp::EventLoop* caller_loop, const std::string& key, RemoveCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<RemoveCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::Get(evpp::EventLoop* caller_loop, const std::string& key, GetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<GetCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::PrefixGet(evpp::EventLoop* caller_loop, const std::string& key, PrefixGetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<PrefixGetCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::MultiGet(evpp::EventLoop* caller_loop, const std::vector<std::string>& keys, MultiGetCallback callback) {
if (UNLIKELY(keys.size() <= 0)) {
MultiGetResult result;
caller_loop->RunInLoop(std::bind(callback, std::move(result)));
return;
}
const std::size_t size = keys.size();
std::map<uint16_t, std::vector<std::string> > vbucket_keys;
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = 0;
MultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<MultiGetResult, MultiGetCallback> > (callback);
auto& result = handler->get_result();
std::size_t pos = 0;
for (size_t i = 0; i < size; ++i) {
auto &key = keys[i];
GET_FILTER_KEY_POS(pos, key)
vbucket = vbconf->GetVbucketByKey(key.c_str(), pos);
vbucket_keys[vbucket].emplace_back(key);
result.emplace(key, GetResult());
}
handler->set_vbucket_keys(vbucket_keys);
auto & vbucket_keys_d = handler->get_vbucket_keys();
for(auto& it : vbucket_keys_d) {
vbucket = it.first;
CommandPtr command = std::make_shared<MultiGetCommand>(caller_loop, vbucket, handler);
LaunchCommand(command);
}
}
void MemcacheClientPool::PrefixMultiGet(evpp::EventLoop* caller_loop, const std::vector<std::string>& keys, PrefixMultiGetCallback callback) {
if (UNLIKELY(keys.size() <= 0)) {
PrefixMultiGetResult result;
caller_loop->RunInLoop(std::bind(callback, std::move(result)));
return;
}
const std::size_t size = keys.size();
std::map<uint16_t, std::vector<std::string> > vbucket_keys;
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = 0;
PrefixMultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<PrefixMultiGetResult, PrefixMultiGetCallback> >(callback);
auto& result = handler->get_result();
std::size_t pos = 0;
for (size_t i = 0; i < size; ++i) {
auto& key = keys[i];
GET_FILTER_KEY_POS(pos, key)
vbucket = vbconf->GetVbucketByKey(key.c_str(), pos);
vbucket_keys[vbucket].emplace_back(key);
result.emplace(key, std::make_shared<PrefixGetResult>());
}
handler->set_vbucket_keys(vbucket_keys);
auto & vbucket_keys_d = handler->get_vbucket_keys();
for(auto& it : vbucket_keys_d) {
vbucket = it.first;
CommandPtr command = std::make_shared<PrefixMultiGetCommand>(caller_loop, vbucket, handler);
LaunchCommand(command);
}
}
void MemcacheClientPool::LaunchCommand(CommandPtr& command) {
const uint32_t thread_hash = next_thread_++;
auto loop = loop_pool_.GetNextLoopWithHash(thread_hash);
loop->RunInLoop(
std::bind(&MemcacheClientPool::DoLaunchCommand, this, loop, command));
}
void MemcacheClientPool::DoLaunchCommand(evpp::EventLoop * loop, CommandPtr command) {
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = command->vbucket_id();
uint16_t server_id = vbconf->SelectServerId(vbucket, command->server_id());
if (UNLIKELY(server_id == BAD_SERVER_ID)) {
LOG_ERROR << "bad server id";
command->OnError(ERR_CODE_DISCONNECT);
return;
}
command->set_server_id(server_id);
std::string server_addr = vbconf->GetServerAddrById(server_id);
MemcClientMap* client_map = GetMemcClientMap(loop);
if (UNLIKELY(client_map == NULL)) {
command->OnError(ERR_CODE_DISCONNECT);
LOG_INFO << "DoLaunchCommand thread pool empty";
return;
}
auto it = client_map->find(server_addr);
if (UNLIKELY(it == client_map->end())) {
BuilderMemClient(loop, server_addr, *client_map, timeout_ms_);
auto client = client_map->find(server_addr);
client->second->PushWaitingCommand(command);
return;
}
if (LIKELY(it->second->conn() && it->second->conn()->IsConnected())) {
it->second->PushRunningCommand(command);
command->Launch(it->second);
return;
}
if (!it->second->conn() || it->second->conn()->status() == evpp::TCPConn::kConnecting) {
it->second->PushWaitingCommand(command);
} else {
if (command->ShouldRetry()) {
LOG_INFO << "OnClientConnection disconnect retry";
LaunchCommand(command);
} else {
command->OnError(ERR_CODE_DISCONNECT);
}
}
}
}
<commit_msg>change cal pos<commit_after>#include "memcache_client_pool.h"
#include "vbucket_config.h"
#include "evpp/event_loop_thread_pool.h"
#include "likely.h"
namespace evmc {
#define GET_FILTER_KEY_POS(name, key) \
name = key.find(key_filter_); \
if (name == std::string::npos) { \
name = key.size(); \
}
MemcacheClientPool::~MemcacheClientPool() {
}
void MemcacheClientPool::Stop(bool wait_thread_exit) {
loop_pool_.Stop(wait_thread_exit);
MemcacheClientBase::Stop();
}
bool MemcacheClientPool::Start() {
bool ok = loop_pool_.Start(true);
if (UNLIKELY(!ok)) {
LOG_ERROR << "loop pool start failed";
return false;
}
if (!MemcacheClientBase::Start(true)) {
loop_pool_.Stop(true);
LOG_ERROR << "vbucket init failed";
return false;
}
auto server_list = vbucket_config()->server_list();
// 须先构造memc_client_map_数组,再各个元素取地址,否则地址不稳定,可能崩溃
for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) {
memc_client_map_.emplace_back(MemcClientMap());
evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i);
for (size_t svr = 0; svr < server_list.size(); ++svr) {
auto & client_map = memc_client_map_.back();
BuilderMemClient(loop, server_list[svr], client_map, timeout_ms_);
}
}
for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) {
evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i);
loop->set_context(evpp::Any(&memc_client_map_[i]));
}
return ok;
}
void MemcacheClientPool::Set(evpp::EventLoop* caller_loop, const std::string& key, const std::string& value, uint32_t flags,
uint32_t expire, SetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<SetCommand>(caller_loop, vbucket, key, value, flags, expire, callback);
LaunchCommand(command);
}
void MemcacheClientPool::Remove(evpp::EventLoop* caller_loop, const std::string& key, RemoveCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<RemoveCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::Get(evpp::EventLoop* caller_loop, const std::string& key, GetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<GetCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::PrefixGet(evpp::EventLoop* caller_loop, const std::string& key, PrefixGetCallback callback) {
std::size_t pos = 0;
GET_FILTER_KEY_POS(pos, key)
const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos);
CommandPtr command = std::make_shared<PrefixGetCommand>(caller_loop, vbucket, key, callback);
LaunchCommand(command);
}
void MemcacheClientPool::MultiGet(evpp::EventLoop* caller_loop, const std::vector<std::string>& keys, MultiGetCallback callback) {
if (UNLIKELY(keys.size() <= 0)) {
MultiGetResult result;
caller_loop->RunInLoop(std::bind(callback, std::move(result)));
return;
}
const std::size_t size = keys.size();
std::map<uint16_t, std::vector<std::string> > vbucket_keys;
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = 0;
MultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<MultiGetResult, MultiGetCallback> > (callback);
auto& result = handler->get_result();
std::size_t pos = 0;
for (size_t i = 0; i < size; ++i) {
auto &key = keys[i];
GET_FILTER_KEY_POS(pos, key)
vbucket = vbconf->GetVbucketByKey(key.c_str(), pos);
vbucket_keys[vbucket].emplace_back(key);
result.emplace(key, GetResult());
}
handler->set_vbucket_keys(vbucket_keys);
auto & vbucket_keys_d = handler->get_vbucket_keys();
for(auto& it : vbucket_keys_d) {
vbucket = it.first;
CommandPtr command = std::make_shared<MultiGetCommand>(caller_loop, vbucket, handler);
LaunchCommand(command);
}
}
void MemcacheClientPool::PrefixMultiGet(evpp::EventLoop* caller_loop, const std::vector<std::string>& keys, PrefixMultiGetCallback callback) {
if (UNLIKELY(keys.size() <= 0)) {
PrefixMultiGetResult result;
caller_loop->RunInLoop(std::bind(callback, std::move(result)));
return;
}
const std::size_t size = keys.size();
std::map<uint16_t, std::vector<std::string> > vbucket_keys;
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = 0;
PrefixMultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<PrefixMultiGetResult, PrefixMultiGetCallback> >(callback);
auto& result = handler->get_result();
std::size_t pos = 0;
for (size_t i = 0; i < size; ++i) {
auto& key = keys[i];
GET_FILTER_KEY_POS(pos, key)
vbucket = vbconf->GetVbucketByKey(key.c_str(), pos);
vbucket_keys[vbucket].emplace_back(key);
result.emplace(key, std::make_shared<PrefixGetResult>());
}
handler->set_vbucket_keys(vbucket_keys);
auto & vbucket_keys_d = handler->get_vbucket_keys();
for(auto& it : vbucket_keys_d) {
vbucket = it.first;
CommandPtr command = std::make_shared<PrefixMultiGetCommand>(caller_loop, vbucket, handler);
LaunchCommand(command);
}
}
void MemcacheClientPool::LaunchCommand(CommandPtr& command) {
const uint32_t thread_hash = next_thread_++;
auto loop = loop_pool_.GetNextLoopWithHash(thread_hash);
loop->RunInLoop(
std::bind(&MemcacheClientPool::DoLaunchCommand, this, loop, command));
}
void MemcacheClientPool::DoLaunchCommand(evpp::EventLoop * loop, CommandPtr command) {
MultiModeVbucketConfig* vbconf = vbucket_config();
uint16_t vbucket = command->vbucket_id();
uint16_t server_id = vbconf->SelectServerId(vbucket, command->server_id());
if (UNLIKELY(server_id == BAD_SERVER_ID)) {
LOG_ERROR << "bad server id";
command->OnError(ERR_CODE_DISCONNECT);
return;
}
command->set_server_id(server_id);
std::string server_addr = vbconf->GetServerAddrById(server_id);
MemcClientMap* client_map = GetMemcClientMap(loop);
if (UNLIKELY(client_map == NULL)) {
command->OnError(ERR_CODE_DISCONNECT);
LOG_INFO << "DoLaunchCommand thread pool empty";
return;
}
auto it = client_map->find(server_addr);
if (UNLIKELY(it == client_map->end())) {
BuilderMemClient(loop, server_addr, *client_map, timeout_ms_);
auto client = client_map->find(server_addr);
client->second->PushWaitingCommand(command);
return;
}
if (LIKELY(it->second->conn() && it->second->conn()->IsConnected())) {
it->second->PushRunningCommand(command);
command->Launch(it->second);
return;
}
if (!it->second->conn() || it->second->conn()->status() == evpp::TCPConn::kConnecting) {
it->second->PushWaitingCommand(command);
} else {
if (command->ShouldRetry()) {
LOG_INFO << "OnClientConnection disconnect retry";
LaunchCommand(command);
} else {
command->OnError(ERR_CODE_DISCONNECT);
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright 2013 Francisco Jerez
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#ifndef CLOVER_UTIL_FUNCTIONAL_HPP
#define CLOVER_UTIL_FUNCTIONAL_HPP
#include <type_traits>
namespace clover {
struct identity {
template<typename T>
typename std::remove_reference<T>::type
operator()(T &&x) const {
return x;
}
};
struct plus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x + y;
}
};
struct minus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x - y;
}
};
struct negate {
template<typename T>
T
operator()(T x) const {
return -x;
}
};
struct multiplies {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x * y;
}
};
struct divides {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x / y;
}
};
struct modulus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x % y;
}
};
struct minimum {
template<typename T>
T
operator()(T x) const {
return x;
}
template<typename T, typename... Ts>
T
operator()(T x, Ts... xs) const {
T y = minimum()(xs...);
return x < y ? x : y;
}
};
struct maximum {
template<typename T>
T
operator()(T x) const {
return x;
}
template<typename T, typename... Ts>
T
operator()(T x, Ts... xs) const {
T y = maximum()(xs...);
return x < y ? y : x;
}
};
struct preincs {
template<typename T>
T &
operator()(T &x) const {
return ++x;
}
};
struct predecs {
template<typename T>
T &
operator()(T &x) const {
return --x;
}
};
template<typename T>
class multiplies_by_t {
public:
multiplies_by_t(T x) : x(x) {
}
template<typename S>
typename std::common_type<T, S>::type
operator()(S y) const {
return x * y;
}
private:
T x;
};
template<typename T>
multiplies_by_t<T>
multiplies_by(T x) {
return { x };
}
template<typename T>
class preincs_by_t {
public:
preincs_by_t(T n) : n(n) {
}
template<typename S>
S &
operator()(S &x) const {
return x += n;
}
private:
T n;
};
template<typename T>
preincs_by_t<T>
preincs_by(T n) {
return { n };
}
template<typename T>
class predecs_by_t {
public:
predecs_by_t(T n) : n(n) {
}
template<typename S>
S &
operator()(S &x) const {
return x -= n;
}
private:
T n;
};
template<typename T>
predecs_by_t<T>
predecs_by(T n) {
return { n };
}
struct greater {
template<typename T, typename S>
bool
operator()(T x, S y) const {
return x > y;
}
};
struct evals {
template<typename T>
auto
operator()(T &&x) const -> decltype(x()) {
return x();
}
};
struct derefs {
template<typename T>
auto
operator()(T &&x) const -> decltype(*x) {
return *x;
}
};
struct addresses {
template<typename T>
T *
operator()(T &x) const {
return &x;
}
template<typename T>
T *
operator()(std::reference_wrapper<T> x) const {
return &x.get();
}
};
struct begins {
template<typename T>
auto
operator()(T &x) const -> decltype(x.begin()) {
return x.begin();
}
};
struct ends {
template<typename T>
auto
operator()(T &x) const -> decltype(x.end()) {
return x.end();
}
};
struct sizes {
template<typename T>
auto
operator()(T &x) const -> decltype(x.size()) {
return x.size();
}
};
template<typename T>
class advances_by_t {
public:
advances_by_t(T n) : n(n) {
}
template<typename S>
S
operator()(S &&it) const {
std::advance(it, n);
return it;
}
private:
T n;
};
template<typename T>
advances_by_t<T>
advances_by(T n) {
return { n };
}
struct zips {
template<typename... Ts>
std::tuple<Ts...>
operator()(Ts &&... xs) const {
return std::tuple<Ts...>(std::forward<Ts>(xs)...);
}
};
struct is_zero {
template<typename T>
bool
operator()(const T &x) const {
return x == 0;
}
};
struct keys {
template<typename P>
auto
operator()(P &&p) const -> decltype(std::get<0>(std::forward<P>(p))) {
return std::get<0>(std::forward<P>(p));
}
};
struct values {
template<typename P>
auto
operator()(P &&p) const -> decltype(std::get<1>(std::forward<P>(p))) {
return std::get<1>(std::forward<P>(p));
}
};
class name_equals {
public:
name_equals(const std::string &name) : name(name) {
}
template<typename T>
bool
operator()(const T &x) const {
return std::string(x.name.begin(), x.name.end()) == name;
}
private:
const std::string &name;
};
template<typename T>
class key_equals_t {
public:
key_equals_t(T &&x) : x(x) {
}
template<typename S>
bool
operator()(const std::pair<T, S> &p) const {
return p.first == x;
}
private:
T x;
};
template<typename T>
key_equals_t<T>
key_equals(T &&x) {
return { std::forward<T>(x) };
}
template<typename T>
class type_equals_t {
public:
type_equals_t(T type) : type(type) {
}
template<typename S>
bool
operator()(const S &x) const {
return x.type == type;
}
private:
T type;
};
template<typename T>
type_equals_t<T>
type_equals(T x) {
return { x };
}
struct interval_overlaps {
template<typename T>
bool
operator()(T x0, T x1, T y0, T y1) {
return ((x0 <= y0 && y0 < x1) ||
(y0 <= x0 && x0 < y1));
}
};
}
#endif
<commit_msg>clover/util: Allow using key_equals with pair-like objects other than std::pair.<commit_after>//
// Copyright 2013 Francisco Jerez
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#ifndef CLOVER_UTIL_FUNCTIONAL_HPP
#define CLOVER_UTIL_FUNCTIONAL_HPP
#include <type_traits>
namespace clover {
struct identity {
template<typename T>
typename std::remove_reference<T>::type
operator()(T &&x) const {
return x;
}
};
struct plus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x + y;
}
};
struct minus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x - y;
}
};
struct negate {
template<typename T>
T
operator()(T x) const {
return -x;
}
};
struct multiplies {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x * y;
}
};
struct divides {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x / y;
}
};
struct modulus {
template<typename T, typename S>
typename std::common_type<T, S>::type
operator()(T x, S y) const {
return x % y;
}
};
struct minimum {
template<typename T>
T
operator()(T x) const {
return x;
}
template<typename T, typename... Ts>
T
operator()(T x, Ts... xs) const {
T y = minimum()(xs...);
return x < y ? x : y;
}
};
struct maximum {
template<typename T>
T
operator()(T x) const {
return x;
}
template<typename T, typename... Ts>
T
operator()(T x, Ts... xs) const {
T y = maximum()(xs...);
return x < y ? y : x;
}
};
struct preincs {
template<typename T>
T &
operator()(T &x) const {
return ++x;
}
};
struct predecs {
template<typename T>
T &
operator()(T &x) const {
return --x;
}
};
template<typename T>
class multiplies_by_t {
public:
multiplies_by_t(T x) : x(x) {
}
template<typename S>
typename std::common_type<T, S>::type
operator()(S y) const {
return x * y;
}
private:
T x;
};
template<typename T>
multiplies_by_t<T>
multiplies_by(T x) {
return { x };
}
template<typename T>
class preincs_by_t {
public:
preincs_by_t(T n) : n(n) {
}
template<typename S>
S &
operator()(S &x) const {
return x += n;
}
private:
T n;
};
template<typename T>
preincs_by_t<T>
preincs_by(T n) {
return { n };
}
template<typename T>
class predecs_by_t {
public:
predecs_by_t(T n) : n(n) {
}
template<typename S>
S &
operator()(S &x) const {
return x -= n;
}
private:
T n;
};
template<typename T>
predecs_by_t<T>
predecs_by(T n) {
return { n };
}
struct greater {
template<typename T, typename S>
bool
operator()(T x, S y) const {
return x > y;
}
};
struct evals {
template<typename T>
auto
operator()(T &&x) const -> decltype(x()) {
return x();
}
};
struct derefs {
template<typename T>
auto
operator()(T &&x) const -> decltype(*x) {
return *x;
}
};
struct addresses {
template<typename T>
T *
operator()(T &x) const {
return &x;
}
template<typename T>
T *
operator()(std::reference_wrapper<T> x) const {
return &x.get();
}
};
struct begins {
template<typename T>
auto
operator()(T &x) const -> decltype(x.begin()) {
return x.begin();
}
};
struct ends {
template<typename T>
auto
operator()(T &x) const -> decltype(x.end()) {
return x.end();
}
};
struct sizes {
template<typename T>
auto
operator()(T &x) const -> decltype(x.size()) {
return x.size();
}
};
template<typename T>
class advances_by_t {
public:
advances_by_t(T n) : n(n) {
}
template<typename S>
S
operator()(S &&it) const {
std::advance(it, n);
return it;
}
private:
T n;
};
template<typename T>
advances_by_t<T>
advances_by(T n) {
return { n };
}
struct zips {
template<typename... Ts>
std::tuple<Ts...>
operator()(Ts &&... xs) const {
return std::tuple<Ts...>(std::forward<Ts>(xs)...);
}
};
struct is_zero {
template<typename T>
bool
operator()(const T &x) const {
return x == 0;
}
};
struct keys {
template<typename P>
auto
operator()(P &&p) const -> decltype(std::get<0>(std::forward<P>(p))) {
return std::get<0>(std::forward<P>(p));
}
};
struct values {
template<typename P>
auto
operator()(P &&p) const -> decltype(std::get<1>(std::forward<P>(p))) {
return std::get<1>(std::forward<P>(p));
}
};
class name_equals {
public:
name_equals(const std::string &name) : name(name) {
}
template<typename T>
bool
operator()(const T &x) const {
return std::string(x.name.begin(), x.name.end()) == name;
}
private:
const std::string &name;
};
template<typename T>
class key_equals_t {
public:
key_equals_t(T &&x) : x(x) {
}
template<typename P>
bool
operator()(const P &p) const {
return p.first == x;
}
private:
T x;
};
template<typename T>
key_equals_t<T>
key_equals(T &&x) {
return { std::forward<T>(x) };
}
template<typename T>
class type_equals_t {
public:
type_equals_t(T type) : type(type) {
}
template<typename S>
bool
operator()(const S &x) const {
return x.type == type;
}
private:
T type;
};
template<typename T>
type_equals_t<T>
type_equals(T x) {
return { x };
}
struct interval_overlaps {
template<typename T>
bool
operator()(T x0, T x1, T y0, T y1) {
return ((x0 <= y0 && y0 < x1) ||
(y0 <= x0 && x0 < y1));
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <stan/agrad/rev/functions/value_of.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <stan/math/functions/value_of.hpp>
TEST(AgradFwd,value_of) {
using stan::agrad::fvar;
using stan::math::value_of;
using stan::agrad::value_of;
fvar<double> a = 5.0;
EXPECT_FLOAT_EQ(5.0, value_of(a));
EXPECT_FLOAT_EQ(5.0, value_of(5.0)); // make sure all work together
EXPECT_FLOAT_EQ(5.0, value_of(5));
}
TEST(AgradFwd,value_of_nan) {
using stan::agrad::fvar;
using stan::math::value_of;
using stan::agrad::value_of;
double nan = std::numeric_limits<double>::quiet_NaN();
fvar<double> a = nan;
EXPECT_TRUE(boost::math::isnan(value_of(a)));
EXPECT_TRUE(boost::math::isnan(value_of(nan)));
}
<commit_msg>fixed value_of NaN test<commit_after>#include <stan/agrad/fwd/functions/value_of.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <stan/math/functions/value_of.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
TEST(AgradFwd,value_of) {
using stan::agrad::fvar;
using stan::math::value_of;
using stan::agrad::value_of;
fvar<double> a = 5.0;
EXPECT_FLOAT_EQ(5.0, value_of(a));
EXPECT_FLOAT_EQ(5.0, value_of(5.0)); // make sure all work together
EXPECT_FLOAT_EQ(5.0, value_of(5));
}
TEST(AgradFwd,value_of_nan) {
using stan::agrad::fvar;
using stan::math::value_of;
using stan::agrad::value_of;
double nan = std::numeric_limits<double>::quiet_NaN();
fvar<double> a = nan;
EXPECT_TRUE(boost::math::isnan(value_of(a)));
EXPECT_TRUE(boost::math::isnan(value_of(nan)));
}
<|endoftext|> |
<commit_before>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"
#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_ellipsoid.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
//static void sort_desc(tabulator_t& table, size_t column)
//{
// table.sort(column, [] (const string_t& value1, const string_t& value2)
// {
// return text::from_string<scalar_t>(value1) > text::from_string<scalar_t>(value2);
// });
//}
static void sort_asc(tabulator_t& table, size_t column)
{
table.sort(column, [] (const string_t& value1, const string_t& value2)
{
return text::from_string<scalar_t>(value1) < text::from_string<scalar_t>(value2);
});
}
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 4 * 1024;
const scalar_t epsilon = 1e-6;
const size_t trials = 1024;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
// batch_optimizer::GD,
// batch_optimizer::CGD_CD,
// batch_optimizer::CGD_DY,
// batch_optimizer::CGD_FR,
// batch_optimizer::CGD_HS,
// batch_optimizer::CGD_LS,
batch_optimizer::CGD_PRP,
batch_optimizer::CGD_N,
// batch_optimizer::CGD_DYCD,
batch_optimizer::CGD_DYHS,
batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optimize::ls_initializer::unit,
optimize::ls_initializer::quadratic,
optimize::ls_initializer::consistent
};
const auto ls_strategies =
{
// optimize::ls_strategy::backtrack_armijo,
optimize::ls_strategy::backtrack_wolfe,
// optimize::ls_strategy::backtrack_strong_wolfe,
// optimize::ls_strategy::interpolation_bisection,
optimize::ls_strategy::interpolation_cubic,
optimize::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (batch_optimizer optimizer : optimizers)
for (optimize::ls_initializer ls_initializer : ls_initializers)
for (optimize::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(crit > epsilon ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
sort_asc(table, 0);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int argc, char *argv[])
{
using namespace ncv;
// // Sphere function
// check_problems(ncv::make_sphere_funcs(16));
// // Ellipsoid function
// check_problems(ncv::make_ellipsoid_funcs(16));
// // Rotated ellipsoid function
// check_problems(ncv::make_rotated_ellipsoid_funcs(1024));
// Rosenbrock function
check_problems(ncv::make_rosenbrock_funcs(7));
// Beale function
check_problems(ncv::make_beale_funcs());
// Goldstein-Price function
check_problems(ncv::make_goldstein_price_funcs());
// Booth function
check_problems(ncv::make_booth_funcs());
// Matyas function
check_problems(ncv::make_matyas_funcs());
// Himmelblau function
check_problems(ncv::make_himmelblau_funcs());
// 3Hump camel function
check_problems(ncv::make_3hump_camel_funcs());
// McCormick function
check_problems(ncv::make_mccormick_funcs());
// show global statistics
tabulator_t table("optimizer");
table.header() << "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
sort_asc(table, 2);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<commit_msg>improve quality assement of optimizers<commit_after>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"
#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_ellipsoid.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
const size_t trials = 1024;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
//static void sort_desc(tabulator_t& table, size_t column)
//{
// table.sort(column, [] (const string_t& value1, const string_t& value2)
// {
// return text::from_string<scalar_t>(value1) > text::from_string<scalar_t>(value2);
// });
//}
static void sort_asc(tabulator_t& table, size_t column)
{
table.sort(column, [] (const string_t& value1, const string_t& value2)
{
return text::from_string<scalar_t>(value1) < text::from_string<scalar_t>(value2);
});
}
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 1024;
const scalar_t epsilon = 1e-6;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
batch_optimizer::GD,
batch_optimizer::CGD_CD,
batch_optimizer::CGD_DY,
batch_optimizer::CGD_FR,
batch_optimizer::CGD_HS,
batch_optimizer::CGD_LS,
batch_optimizer::CGD_PRP,
batch_optimizer::CGD_N,
batch_optimizer::CGD_DYCD,
batch_optimizer::CGD_DYHS,
batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optimize::ls_initializer::unit,
optimize::ls_initializer::quadratic,
optimize::ls_initializer::consistent
};
const auto ls_strategies =
{
optimize::ls_strategy::backtrack_armijo,
optimize::ls_strategy::backtrack_wolfe,
optimize::ls_strategy::backtrack_strong_wolfe,
optimize::ls_strategy::interpolation_bisection,
optimize::ls_strategy::interpolation_cubic,
optimize::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (batch_optimizer optimizer : optimizers)
for (optimize::ls_initializer ls_initializer : ls_initializers)
for (optimize::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(crit > epsilon ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
sort_asc(table, 0);
sort_asc(table, 3);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int argc, char *argv[])
{
using namespace ncv;
// // Sphere function
// check_problems(ncv::make_sphere_funcs(16));
// // Ellipsoid function
// check_problems(ncv::make_ellipsoid_funcs(16));
// // Rotated ellipsoid function
// check_problems(ncv::make_rotated_ellipsoid_funcs(1024));
// Rosenbrock function
check_problems(ncv::make_rosenbrock_funcs(7));
// // Beale function
// check_problems(ncv::make_beale_funcs());
// // Goldstein-Price function
// check_problems(ncv::make_goldstein_price_funcs());
// Booth function
check_problems(ncv::make_booth_funcs());
// Matyas function
check_problems(ncv::make_matyas_funcs());
// Himmelblau function
check_problems(ncv::make_himmelblau_funcs());
// 3Hump camel function
check_problems(ncv::make_3hump_camel_funcs());
// McCormick function
check_problems(ncv::make_mccormick_funcs());
// show global statistics
tabulator_t table("optimizer");
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum())
<< stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
sort_asc(table, 0);
sort_asc(table, 3);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: kdebecdef.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2006-08-01 10:25:46 $
*
* 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 KDEBACKEND_HXX_
#include "kdebackend.hxx"
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef INCLUDED_VCL_KDE_HEADERS_H
#include <vcl/kde_headers.h>
#endif
#include "uno/current_context.hxx"
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createKDEBackend(const uno::Reference<uno::XComponentContext>& xContext)
{
try {
uno::Reference< uno::XCurrentContext > xCurrentContext(uno::getCurrentContext());
if (xCurrentContext.is())
{
uno::Any aValue = xCurrentContext->getValueByName(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "system.desktop-environment" ) ) );
rtl::OUString aDesktopEnvironment;
if ( (aValue >>= aDesktopEnvironment) && (aDesktopEnvironment.equalsAscii("KDE")) && (KApplication::kApplication() != NULL) )
return * KDEBackend::createInstance(xContext);
}
return uno::Reference<uno::XInterface>();
} catch (uno::RuntimeException e) {
return uno::Reference<uno::XInterface>();
}
}
//==============================================================================
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createKDEBackend,
KDEBackend::getBackendName,
KDEBackend::getBackendServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL, NULL, NULL, NULL, NULL, 0 }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **aEnvTypeName,
uno_Environment **) {
*aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *,
void *pRegistryKey) {
using namespace ::com::sun::star::registry;
if (pRegistryKey)
{
try
{
uno::Reference< XRegistryKey > xImplKey = static_cast< XRegistryKey* >( pRegistryKey )->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + KDEBackend::getBackendName()
);
// Register associated service names
uno::Reference< XRegistryKey > xServicesKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES") )
);
uno::Sequence<rtl::OUString> sServiceNames = KDEBackend::getBackendServiceNames();
for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i)
xServicesKey->createKey(sServiceNames[i]);
// Register supported components
uno::Reference<XRegistryKey> xComponentKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/DATA/SupportedComponents") )
);
xComponentKey->setAsciiListValue( KDEBackend::getSupportedComponents() );
return sal_True;
}
catch( InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "InvalidRegistryException caught");
}
}
return sal_False;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(
aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS kdesettings3 (1.4.12); FILE MERGED 2006/07/21 12:53:51 kendy 1.4.12.1: #i66204# Don't link with KDE libraries in Gnome (and v.v.)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: kdebecdef.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2006-08-04 12:31:00 $
*
* 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 KDEBACKEND_HXX_
#include "kdebackend.hxx"
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef INCLUDED_VCL_KDE_HEADERS_H
#include <vcl/kde_headers.h>
#endif
#include "uno/current_context.hxx"
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createKDEBackend(const uno::Reference<uno::XComponentContext>& xContext)
{
try {
uno::Reference< uno::XCurrentContext > xCurrentContext(uno::getCurrentContext());
if (xCurrentContext.is())
{
uno::Any aValue = xCurrentContext->getValueByName(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "system.desktop-environment" ) ) );
rtl::OUString aDesktopEnvironment;
if ( (aValue >>= aDesktopEnvironment) && (aDesktopEnvironment.equalsAscii("KDE")) && (KApplication::kApplication() != NULL) )
return * KDEBackend::createInstance(xContext);
}
return uno::Reference<uno::XInterface>();
} catch (uno::RuntimeException e) {
return uno::Reference<uno::XInterface>();
}
}
//==============================================================================
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createKDEBackend,
KDEBackend::getBackendName,
KDEBackend::getBackendServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL, NULL, NULL, NULL, NULL, 0 }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **aEnvTypeName,
uno_Environment **) {
*aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *,
void *pRegistryKey) {
using namespace ::com::sun::star::registry;
if (pRegistryKey)
{
try
{
uno::Reference< XRegistryKey > xImplKey = static_cast< XRegistryKey* >( pRegistryKey )->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + KDEBackend::getBackendName()
);
// Register associated service names
uno::Reference< XRegistryKey > xServicesKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES") )
);
uno::Sequence<rtl::OUString> sServiceNames = KDEBackend::getBackendServiceNames();
for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i)
xServicesKey->createKey(sServiceNames[i]);
return sal_True;
}
catch( InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "InvalidRegistryException caught");
}
}
return sal_False;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(
aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "importconfigurationcommand.hpp"
using namespace kdb;
ImportConfigurationCommand::ImportConfigurationCommand(TreeViewModel* model, const QString keyName, const QString format, const QString file, const QString mergeStrategy, QUndoCommand* parent)
: QUndoCommand(parent)
, m_model(model)
, m_name(keyName)
, m_format(format)
, m_file(file)
, m_mergeStrategy(mergeStrategy)
{
setText("import");
m_kdb.get(m_set, "");
}
void ImportConfigurationCommand::undo()
{
m_model->setKeySet(m_set);
m_model->populateModel();
m_model->synchronize();
}
void ImportConfigurationCommand::redo()
{
m_model->importConfiguration(m_name, m_format, m_file, m_mergeStrategy);
}
<commit_msg>fix get in import command<commit_after>#include "importconfigurationcommand.hpp"
using namespace kdb;
ImportConfigurationCommand::ImportConfigurationCommand(TreeViewModel* model, const QString keyName, const QString format, const QString file, const QString mergeStrategy, QUndoCommand* parent)
: QUndoCommand(parent)
, m_model(model)
, m_name(keyName)
, m_format(format)
, m_file(file)
, m_mergeStrategy(mergeStrategy)
{
setText("import");
m_kdb.get(m_set, "/");
}
void ImportConfigurationCommand::undo()
{
m_model->setKeySet(m_set);
m_model->populateModel();
m_model->synchronize();
}
void ImportConfigurationCommand::redo()
{
m_model->importConfiguration(m_name, m_format, m_file, m_mergeStrategy);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
#include <assert.h>
#include <sstream>
#include <string>
#include <vector>
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_string.h"
#include "native_client/src/trusted/plugin/method_map.h"
#include "native_client/src/trusted/plugin/plugin.h"
#include "native_client/src/trusted/plugin/portable_handle.h"
#include "native_client/src/trusted/plugin/ppapi/browser_interface_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/plugin_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/scriptable_handle_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/var_utils.h"
namespace plugin {
namespace {
pp::Var Error(nacl::string call_name, const char* caller,
const char* error, pp::Var* exception) {
nacl::stringstream error_stream;
error_stream << call_name << ": " << error;
if (!exception->is_void()) {
error_stream << " - " + exception->AsString();
}
const char* e = error_stream.str().c_str();
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (%s)\n", caller, e));
*exception = pp::Var(e);
return pp::Var();
}
} // namespace
ScriptableHandlePpapi* ScriptableHandlePpapi::New(PortableHandle* handle) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::New (portable_handle=%p)\n",
static_cast<void*>(handle)));
if (handle == NULL) {
return NULL;
}
ScriptableHandlePpapi* scriptable_handle =
new(std::nothrow) ScriptableHandlePpapi(handle);
if (scriptable_handle == NULL) {
return NULL;
}
scriptable_handle->set_handle(handle);
PLUGIN_PRINTF(("ScriptableHandlePpapi::New (return %p)\n",
static_cast<void*>(scriptable_handle)));
return scriptable_handle;
}
bool ScriptableHandlePpapi::HasCallType(CallType call_type,
nacl::string call_name,
const char* caller) {
uintptr_t id = handle()->browser_interface()->StringToIdentifier(call_name);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (id=%"NACL_PRIxPTR")\n",
caller, id));
bool status = handle()->plugin()->HasMethod(id, call_type);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (return %d)\n",
caller, status));
return status;
}
bool ScriptableHandlePpapi::HasProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::HasProperty (name=%s)\n",
VarToString(name).c_str()));
assert(name.is_string() || name.is_int());
UNREFERENCED_PARAMETER(exception);
return HasCallType(PROPERTY_GET, NameAsString(name), "HasProperty");
}
bool ScriptableHandlePpapi::HasMethod(const pp::Var& name, pp::Var* exception) {
assert(name.is_string());
PLUGIN_PRINTF(("ScriptableHandlePpapi::HasMethod (name='%s')\n",
name.AsString().c_str()));
UNREFERENCED_PARAMETER(exception);
return HasCallType(METHOD_CALL, name.AsString(), "HasMethod");
}
pp::Var ScriptableHandlePpapi::Invoke(CallType call_type,
nacl::string call_name,
const char* caller,
const std::vector<pp::Var>& args,
pp::Var* exception) {
uintptr_t id =
handle()->browser_interface()->StringToIdentifier(call_name);
// Initialize input/output parameters.
SrpcParams params;
NaClSrpcArg** inputs = params.ins();
NaClSrpcArg** outputs = params.outs();
if (!handle()->InitParams(id, call_type, ¶ms)) {
return Error(call_name, caller,
"srpc parameter initialization failed", exception);
}
uint32_t input_length = params.InputLength();
uint32_t output_length = params.OutputLength();
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (initialized %"NACL_PRIu32" ins, %"
NACL_PRIu32" outs)\n", caller, input_length, output_length));
// Verify input/output parameter list length.
if (args.size() != params.SignatureLength()) {
return Error(call_name, caller,
"incompatible srpc parameter list", exception);
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (verified signature)\n", caller));
// Marshall input parameters.
if (input_length > 0) {
assert(call_type != PROPERTY_GET); // expect no inputs for "get"
for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (inputs[i] != NULL); ++i) {
if (!PPVarToNaClSrpcArg(args[i], inputs[i], exception)) {
return Error(call_name, caller,
"srpc input marshalling failed", exception);
}
}
}
if (call_type == PROPERTY_SET) assert(input_length == 1);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (marshalled inputs)\n", caller));
// Allocate array-typed output parameters.
if (args.size() > input_length) {
for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (outputs[i] != NULL); ++i) {
if (!PPVarToAllocateNaClSrpcArg(args[input_length + i],
outputs[i], exception)) {
return Error(call_name, caller, "srpc output array allocation failed",
exception);
}
}
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (output array allocation done)\n",
caller));
// Invoke.
if (!handle()->Invoke(id, call_type, ¶ms)) {
nacl::string err = nacl::string(caller) + "('" + call_name + "') failed\n";
if (params.exception_string() != NULL) {
err = params.exception_string();
}
*exception = pp::Var(err.c_str());
return Error(call_name, caller, "invocation failed", exception);
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (invocation done)\n", caller));
// Marshall output parameters.
pp::Var retvar;
if (output_length > 0) {
assert(call_type != PROPERTY_SET); // expect no outputs for "set"
retvar = NaClSrpcArgToPPVar(
outputs[0], static_cast<PluginPpapi*>(handle()->plugin()), exception);
if (output_length > 1) { // TODO(polina): use an array for multiple outputs
NACL_UNIMPLEMENTED();
}
if (!exception->is_void()) {
return Error(call_name, caller, "srpc output marshalling failed",
exception);
}
}
if (call_type == PROPERTY_GET) assert(output_length == 1);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (return %s)\n",
caller, VarToString(retvar).c_str()));
return retvar;
}
pp::Var ScriptableHandlePpapi::GetProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetProperty (name=%s)\n",
VarToString(name).c_str()));
return Invoke(PROPERTY_GET, NameAsString(name), "GetProperty",
std::vector<pp::Var>(), exception);
}
void ScriptableHandlePpapi::SetProperty(const pp::Var& name,
const pp::Var& value,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::SetProperty (name=%s, value=%s)\n",
VarToString(name).c_str(), VarToString(value).c_str()));
std::vector<pp::Var> args;
args.push_back(pp::Var(pp::Var::DontManage(), value.pp_var()));
Invoke(PROPERTY_SET, NameAsString(name), "SetProperty", args, exception);
}
void ScriptableHandlePpapi::RemoveProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::RemoveProperty (name=%s)\n",
VarToString(name).c_str()));
Error(NameAsString(name), "RemoveProperty",
"property removal is not supported", exception);
}
// TODO(polina): should methods also be added?
// This is currently never called and the exact semantics is not clear.
// http://code.google.com/p/chromium/issues/detail?id=51089
void ScriptableHandlePpapi::GetAllPropertyNames(
std::vector<pp::Var>* properties,
pp::Var* exception) {
std::vector<uintptr_t>* ids = handle()->GetPropertyIdentifiers();
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetAllPropertyNames "
"(ids=%"NACL_PRIuS")\n", ids->size()));
for (size_t i = 0; i < ids->size(); ++i) {
nacl::string name =
handle()->browser_interface()->IdentifierToString(ids->at(i));
properties->push_back(pp::Var(name));
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetAllPropertyNames "
"(properties=%"NACL_PRIuS")\n", properties->size()));
UNREFERENCED_PARAMETER(exception);
}
pp::Var ScriptableHandlePpapi::Call(const pp::Var& name,
const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::Call (name=%s, %"NACL_PRIuS
" args)\n", VarToString(name).c_str(), args.size()));
if (name.is_void()) // invoke default
return pp::Var();
assert(name.is_string());
return Invoke(METHOD_CALL, name.AsString(), "Call", args, exception);
}
pp::Var ScriptableHandlePpapi::Construct(const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::Construct (%"NACL_PRIuS
" args)\n", args.size()));
return Error("constructor", "Construct", "constructor is not supported",
exception);
}
ScriptableHandlePpapi::ScriptableHandlePpapi(PortableHandle* handle)
: ScriptableHandle(handle) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::ScriptableHandlePpapi (this=%p, "
"handle=%p)\n",
static_cast<void*>(this), static_cast<void*>(handle)));
}
ScriptableHandlePpapi::~ScriptableHandlePpapi() {
PLUGIN_PRINTF(("ScriptableHandlePpapi::~ScriptableHandlePpapi (this=%p)\n",
static_cast<void*>(this)));
}
} // namespace plugin
<commit_msg>PPAPI NaCl Plugin: Represent multiple SRPC outputs as ArrayPpapi.<commit_after>/*
* Copyright 2010 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
#include <assert.h>
#include <sstream>
#include <string>
#include <vector>
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_string.h"
#include "native_client/src/trusted/plugin/method_map.h"
#include "native_client/src/trusted/plugin/plugin.h"
#include "native_client/src/trusted/plugin/portable_handle.h"
#include "native_client/src/trusted/plugin/ppapi/array_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/browser_interface_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/plugin_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/scriptable_handle_ppapi.h"
#include "native_client/src/trusted/plugin/ppapi/var_utils.h"
namespace plugin {
namespace {
pp::Var Error(nacl::string call_name, const char* caller,
const char* error, pp::Var* exception) {
nacl::stringstream error_stream;
error_stream << call_name << ": " << error;
if (!exception->is_void()) {
error_stream << " - " + exception->AsString();
}
const char* e = error_stream.str().c_str();
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (%s)\n", caller, e));
*exception = pp::Var(e);
return pp::Var();
}
} // namespace
ScriptableHandlePpapi* ScriptableHandlePpapi::New(PortableHandle* handle) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::New (portable_handle=%p)\n",
static_cast<void*>(handle)));
if (handle == NULL) {
return NULL;
}
ScriptableHandlePpapi* scriptable_handle =
new(std::nothrow) ScriptableHandlePpapi(handle);
if (scriptable_handle == NULL) {
return NULL;
}
scriptable_handle->set_handle(handle);
PLUGIN_PRINTF(("ScriptableHandlePpapi::New (return %p)\n",
static_cast<void*>(scriptable_handle)));
return scriptable_handle;
}
bool ScriptableHandlePpapi::HasCallType(CallType call_type,
nacl::string call_name,
const char* caller) {
uintptr_t id = handle()->browser_interface()->StringToIdentifier(call_name);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (id=%"NACL_PRIxPTR")\n",
caller, id));
bool status = handle()->plugin()->HasMethod(id, call_type);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (return %d)\n",
caller, status));
return status;
}
bool ScriptableHandlePpapi::HasProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::HasProperty (name=%s)\n",
VarToString(name).c_str()));
assert(name.is_string() || name.is_int());
UNREFERENCED_PARAMETER(exception);
return HasCallType(PROPERTY_GET, NameAsString(name), "HasProperty");
}
bool ScriptableHandlePpapi::HasMethod(const pp::Var& name, pp::Var* exception) {
assert(name.is_string());
PLUGIN_PRINTF(("ScriptableHandlePpapi::HasMethod (name='%s')\n",
name.AsString().c_str()));
UNREFERENCED_PARAMETER(exception);
return HasCallType(METHOD_CALL, name.AsString(), "HasMethod");
}
pp::Var ScriptableHandlePpapi::Invoke(CallType call_type,
nacl::string call_name,
const char* caller,
const std::vector<pp::Var>& args,
pp::Var* exception) {
uintptr_t id =
handle()->browser_interface()->StringToIdentifier(call_name);
// Initialize input/output parameters.
SrpcParams params;
NaClSrpcArg** inputs = params.ins();
NaClSrpcArg** outputs = params.outs();
if (!handle()->InitParams(id, call_type, ¶ms)) {
return Error(call_name, caller,
"srpc parameter initialization failed", exception);
}
uint32_t input_length = params.InputLength();
int32_t output_length = params.OutputLength();
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (initialized %"NACL_PRIu32" ins, %"
NACL_PRIu32" outs)\n", caller, input_length, output_length));
// Verify input/output parameter list length.
if (args.size() != params.SignatureLength()) {
return Error(call_name, caller,
"incompatible srpc parameter list", exception);
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (verified signature)\n", caller));
// Marshall input parameters.
if (input_length > 0) {
assert(call_type != PROPERTY_GET); // expect no inputs for "get"
for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (inputs[i] != NULL); ++i) {
if (!PPVarToNaClSrpcArg(args[i], inputs[i], exception)) {
return Error(call_name, caller,
"srpc input marshalling failed", exception);
}
}
}
if (call_type == PROPERTY_SET) assert(input_length == 1);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (marshalled inputs)\n", caller));
// Allocate array-typed output parameters.
if (args.size() > input_length) {
for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (outputs[i] != NULL); ++i) {
if (!PPVarToAllocateNaClSrpcArg(args[input_length + i],
outputs[i], exception)) {
return Error(call_name, caller, "srpc output array allocation failed",
exception);
}
}
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (output array allocation done)\n",
caller));
// Invoke.
if (!handle()->Invoke(id, call_type, ¶ms)) {
nacl::string err = nacl::string(caller) + "('" + call_name + "') failed\n";
if (params.exception_string() != NULL) {
err = params.exception_string();
}
*exception = pp::Var(err.c_str());
return Error(call_name, caller, "invocation failed", exception);
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (invocation done)\n", caller));
// Marshall output parameters.
pp::Var retvar;
PluginPpapi* plugin_ppapi = static_cast<PluginPpapi*>(handle()->plugin());
if (output_length > 0) {
assert(call_type != PROPERTY_SET); // expect no outputs for "set"
retvar = NaClSrpcArgToPPVar(outputs[0], plugin_ppapi, exception);
if (output_length > 1) {
ArrayPpapi* array = new(std::nothrow) ArrayPpapi(plugin_ppapi);
if (array == NULL) {
*exception = pp::Var("failed to allocate output array");
} else {
array->SetProperty(pp::Var(0), retvar, exception);
for (int32_t i = 1; i < output_length; ++i) {
pp::Var v = NaClSrpcArgToPPVar(outputs[i], plugin_ppapi, exception);
array->SetProperty(pp::Var(i), v, exception);
}
}
retvar = pp::Var(array);
}
if (!exception->is_void()) {
return Error(call_name, caller, "srpc output marshalling failed",
exception);
}
}
if (call_type == PROPERTY_GET) assert(output_length == 1);
PLUGIN_PRINTF(("ScriptableHandlePpapi::%s (return %s)\n",
caller, VarToString(retvar).c_str()));
return retvar;
}
pp::Var ScriptableHandlePpapi::GetProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetProperty (name=%s)\n",
VarToString(name).c_str()));
return Invoke(PROPERTY_GET, NameAsString(name), "GetProperty",
std::vector<pp::Var>(), exception);
}
void ScriptableHandlePpapi::SetProperty(const pp::Var& name,
const pp::Var& value,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::SetProperty (name=%s, value=%s)\n",
VarToString(name).c_str(), VarToString(value).c_str()));
std::vector<pp::Var> args;
args.push_back(pp::Var(pp::Var::DontManage(), value.pp_var()));
Invoke(PROPERTY_SET, NameAsString(name), "SetProperty", args, exception);
}
void ScriptableHandlePpapi::RemoveProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::RemoveProperty (name=%s)\n",
VarToString(name).c_str()));
Error(NameAsString(name), "RemoveProperty",
"property removal is not supported", exception);
}
// TODO(polina): should methods also be added?
// This is currently never called and the exact semantics is not clear.
// http://code.google.com/p/chromium/issues/detail?id=51089
void ScriptableHandlePpapi::GetAllPropertyNames(
std::vector<pp::Var>* properties,
pp::Var* exception) {
std::vector<uintptr_t>* ids = handle()->GetPropertyIdentifiers();
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetAllPropertyNames "
"(ids=%"NACL_PRIuS")\n", ids->size()));
for (size_t i = 0; i < ids->size(); ++i) {
nacl::string name =
handle()->browser_interface()->IdentifierToString(ids->at(i));
properties->push_back(pp::Var(name));
}
PLUGIN_PRINTF(("ScriptableHandlePpapi::GetAllPropertyNames "
"(properties=%"NACL_PRIuS")\n", properties->size()));
UNREFERENCED_PARAMETER(exception);
}
pp::Var ScriptableHandlePpapi::Call(const pp::Var& name,
const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::Call (name=%s, %"NACL_PRIuS
" args)\n", VarToString(name).c_str(), args.size()));
if (name.is_void()) // invoke default
return pp::Var();
assert(name.is_string());
return Invoke(METHOD_CALL, name.AsString(), "Call", args, exception);
}
pp::Var ScriptableHandlePpapi::Construct(const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::Construct (%"NACL_PRIuS
" args)\n", args.size()));
return Error("constructor", "Construct", "constructor is not supported",
exception);
}
ScriptableHandlePpapi::ScriptableHandlePpapi(PortableHandle* handle)
: ScriptableHandle(handle) {
PLUGIN_PRINTF(("ScriptableHandlePpapi::ScriptableHandlePpapi (this=%p, "
"handle=%p)\n",
static_cast<void*>(this), static_cast<void*>(handle)));
}
ScriptableHandlePpapi::~ScriptableHandlePpapi() {
PLUGIN_PRINTF(("ScriptableHandlePpapi::~ScriptableHandlePpapi (this=%p)\n",
static_cast<void*>(this)));
}
} // namespace plugin
<|endoftext|> |
<commit_before>#include "pvalue.h"
#include "gtest/gtest.h"
// compare with Table 1 from paper
TEST(pvalue_test, paper)
{
constexpr double alpha = 0.001;
EXPECT_NEAR(runs_pvalue(15.5, 5), alpha, 0.00002);
EXPECT_NEAR(runs_pvalue(23.8, 50), alpha, 0.00002);
// from MC have larger error
EXPECT_NEAR(runs_pvalue(25.6, 100), alpha, 0.00008);
}
TEST(pvalue_test, mathematica)
{
constexpr unsigned n = 20;
auto T = {2., 5., 10., 20., 50.};
auto P = {0.8936721808595665, 0.42457437866154357, 0.06934906413527009,
0.0014159488909252227, 9.575188641974819e-9};
auto eps = {1e-15, 1e-15, 1e-15, 1e-15, 1e-15};
for (auto t = T.begin(), p = P.begin(), e=eps.begin(); t != T.end(); ++t, ++p, ++e)
EXPECT_NEAR(runs_pvalue(*t, n), *p, *e);
}
<commit_msg>[pvalue] Compute critical values<commit_after>#include "pvalue.h"
#include "gtest/gtest.h"
// compare with Table 1 from paper
TEST(pvalue_test, paper)
{
constexpr double alpha = 0.001;
EXPECT_NEAR(runs_pvalue(15.5, 5), alpha, 0.00002);
EXPECT_NEAR(runs_pvalue(23.8, 50), alpha, 0.00002);
// from MC have larger error
EXPECT_NEAR(runs_pvalue(25.6, 100), alpha, 0.00008);
}
TEST(pvalue_test, mathematica)
{
constexpr unsigned n = 20;
auto T = {2., 5., 10., 20., 50.};
auto P = {0.8936721808595665, 0.42457437866154357, 0.06934906413527009,
0.0014159488909252227, 9.575188641974819e-9};
auto eps = {1e-15, 1e-15, 1e-15, 1e-15, 1e-15};
for (auto t = T.begin(), p = P.begin(), e=eps.begin(); t != T.end(); ++t, ++p, ++e)
EXPECT_NEAR(runs_pvalue(*t, n), *p, *e);
}
TEST(pvalue_test, critical)
{
constexpr double alpha = 0.001;
constexpr unsigned N = 50;
// EXPECT_NEAR(runs_pvalue(23.758, N), alpha, 1e-10);
// EXPECT_NEAR(runs_pvalue(25.753, 2*N), alpha, 1e-10);
EXPECT_NEAR(runs_pvalue(19.645, 2*N), 0.01, 3e-5);
EXPECT_NEAR(runs_pvalue(15.34, 2*N), 0.05, 1e-4);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
* Copyright (c) 2011 Giulio Camuffo <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "uimanagercomponent.h"
#include <core/debughelper.h>
#include <graphics/item.h>
#include <graphics/engine.h>
#include <graphics/item.h>
#include <graphics/material.h>
#include <graphics/mesh.h>
#include <graphics/renderwidget.h>
#include <graphics/materialinstance.h>
#include <engine/gameobject.h>
#include <engine/asset.h>
#include <QtCore/QMimeData>
#include <QtCore/QVariant>
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsWidget>
#include <QtGui/QPixmap>
#include <QtOpenGL/QGLFramebufferObject>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeExpression>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/qdeclarative.h>
#include <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValueIterator>
#include <texture.h>
#include <game.h>
#include "uiasset.h"
#include "engineaccess.h"
REGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )
using namespace GluonEngine;
using namespace GluonGraphics;
template <typename Tp>
QScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)
{
return engine->newQObject( qobject );
}
template <typename Tp>
void scriptValueToQObject(const QScriptValue &value, Tp &qobject)
{
qobject = qobject_cast<Tp>( value.toQObject() );
}
template <typename Tp>
int qScriptRegisterQObjectMetaType( QScriptEngine *engine )
{
return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject );
}
class UiManagerComponent::UiManagerComponentPrivate
{
public:
UiManagerComponentPrivate()
: view(new QGraphicsView())
, scene(new QGraphicsScene())
, ui(0)
, fbo(0)
, mouse(0)
{
}
QPixmap pixmap;
QGraphicsView* view;
QGraphicsScene* scene;
UiAsset *ui;
QSizeF size;
Item *item;
QGLFramebufferObject* fbo;
GLuint texture;
Component* mouse;
EngineAccess* engineAccess;
};
UiManagerComponent::UiManagerComponent( QObject* parent )
: Component( parent )
, d( new UiManagerComponentPrivate )
{
}
UiManagerComponent::UiManagerComponent( const UiManagerComponent& other )
: Component( other )
, d( other.d )
{
}
UiManagerComponent::~UiManagerComponent()
{
delete d->fbo;
delete d;
}
QString UiManagerComponent::category() const
{
return QString( "Graphics Rendering" );
}
void UiManagerComponent::initialize()
{
QGLWidget* widget = GluonGraphics::Engine::instance()->renderWidget();
d->texture = 0;
// d->fbo = GluonGraphics::Engine::instance()->fbo();
d->pixmap = QPixmap( widget->size() );
d->pixmap.fill( Qt::transparent );
// d->view->setParent(widget->parentWidget());
// d->view->setAttribute(Qt::WA_TranslucentBackground);
// d->view->setAttribute(Qt::WA_NoSystemBackground);
// d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground);
// d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground);
// d->view->setStyleSheet("border: none");
// QPalette p = d->view->viewport()->palette();
// p.setColor(QPalette::Base, Qt::transparent);
// d->view->viewport()->setPalette(p);
// d->view->setScene(d->scene);
// d->view->setSceneRect(QRectF(0,0,1000,1000));
d->scene->setSceneRect(QRectF(QPointF(0,0), widget->size()));
// d->view->resize(widget->size());
// d->view->show();
// d->scene->setBackgroundBrush(Qt::blue);
// d->texture = widget->bindTexture(d->pixmap);
// widget->update();
// widget->updateGL();
// widget->makeCurrent();
if( d->ui && !d->ui->isLoaded() )
{
qmlRegisterType<GluonEngine::GameObject>("org.kde.gluon", 1, 0, "GameObject" );
qmlRegisterInterface<GluonEngine::GameObject>("gameObject");
d->ui->load();
QDeclarativeEngine* engine = d->ui->engine();
engine->rootContext()->setContextProperty( "GameObject", gameObject() );
d->engineAccess = new EngineAccess(this);
engine->rootContext()->setContextProperty( "__engineAccess", d->engineAccess );
//Glorious hack:steal the engine
QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),
"__engineAccess.setEngine( this )" );
expr->evaluate();
delete expr;
start();
}
}
void UiManagerComponent::setScriptEngine( QScriptValue &value )
{
QScriptEngine* engine = value.engine();
QScriptValue originalGlobalObject = engine->globalObject();
QScriptValue newGlobalObject = engine->newObject();
QString eval = QLatin1String( "eval" );
QString version = QLatin1String( "version" );
QScriptValueIterator iter( originalGlobalObject );
QVector<QString> names;
QVector<QScriptValue> values;
QVector<QScriptValue::PropertyFlags> flags;
while ( iter.hasNext() )
{
iter.next();
QString name = iter.name();
if ( name == version )
{
continue;
}
if ( name != eval )
{
names.append( name );
values.append( iter.value() );
flags.append( iter.flags() | QScriptValue::Undeletable );
}
newGlobalObject.setProperty( iter.scriptName(), iter.value() );
}
engine->setGlobalObject( newGlobalObject );
qScriptRegisterQObjectMetaType<GameObject*>( engine );
qScriptRegisterQObjectMetaType<GluonObject*>( engine );
delete d->engineAccess;
d->ui->engine()->rootContext()->setContextProperty( "__engineAccess", 0 );
}
void UiManagerComponent::start()
{
if( d->ui && d->ui->isLoaded() )
{
d->ui->execute();
QGraphicsWidget* widget = d->ui->widget();
if( widget )
{
d->scene->addItem( widget );
// widget->setGeometry( 0, 0, 100, 100 );
}
}
if( d->mouse )
{
// d->mouse->setEnabled( true );
}
}
void UiManagerComponent::draw( int timeLapse )
{
Q_UNUSED( timeLapse )
RenderWidget* widget = GluonGraphics::Engine::instance()->renderWidget();
d->pixmap.fill( Qt::transparent );
QPainter p( &d->pixmap );
d->scene->render( &p );
widget->setPixmap(d->pixmap);
}
void UiManagerComponent::update( int elapsedMilliseconds )
{
if( d->ui && d->ui->isLoaded() )
{
QDeclarativeExpression *expr = new QDeclarativeExpression( d->ui->engine()->rootContext(),
d->ui->widget(), "update()" );
expr->evaluate();
if( expr->hasError() )
{
debug( expr->error().toString() );
}
delete expr;
}
}
void UiManagerComponent::cleanup()
{
if( !d->ui )
{
return;
}
QGraphicsWidget* widget = d->ui->widget();
if( d->scene && widget && widget->scene() == d->scene )
{
// d->scene->removeItem( widget );
}
}
void UiManagerComponent::setUi(UiAsset* ui)
{
d->ui = ui;
}
UiAsset* UiManagerComponent::ui() const
{
return d->ui;
}
void UiManagerComponent::setSize( const QSizeF& size )
{
d->size = size;
}
QSizeF UiManagerComponent::size() const
{
return d->size;
}
Q_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );
#include "uimanagercomponent.moc"
<commit_msg>Set the properties on the QScriptEngine's global object, this allows to set the wrap options that make the GluonObject.child work.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
* Copyright (c) 2011 Giulio Camuffo <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "uimanagercomponent.h"
#include <core/debughelper.h>
#include <graphics/item.h>
#include <graphics/engine.h>
#include <graphics/item.h>
#include <graphics/material.h>
#include <graphics/mesh.h>
#include <graphics/renderwidget.h>
#include <graphics/materialinstance.h>
#include <engine/gameobject.h>
#include <engine/asset.h>
#include <QtCore/QMimeData>
#include <QtCore/QVariant>
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsWidget>
#include <QtGui/QPixmap>
#include <QtOpenGL/QGLFramebufferObject>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeExpression>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/qdeclarative.h>
#include <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValueIterator>
#include <texture.h>
#include <game.h>
#include "uiasset.h"
#include "engineaccess.h"
REGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )
using namespace GluonEngine;
using namespace GluonGraphics;
template <typename Tp>
QScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)
{
return engine->newQObject( qobject );
}
template <typename Tp>
void scriptValueToQObject(const QScriptValue &value, Tp &qobject)
{
qobject = qobject_cast<Tp>( value.toQObject() );
}
template <typename Tp>
int qScriptRegisterQObjectMetaType( QScriptEngine *engine )
{
return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject );
}
class UiManagerComponent::UiManagerComponentPrivate
{
public:
UiManagerComponentPrivate()
: view(new QGraphicsView())
, scene(new QGraphicsScene())
, ui(0)
, fbo(0)
, mouse(0)
{
}
QPixmap pixmap;
QGraphicsView* view;
QGraphicsScene* scene;
UiAsset *ui;
QSizeF size;
Item *item;
QGLFramebufferObject* fbo;
GLuint texture;
Component* mouse;
EngineAccess* engineAccess;
};
UiManagerComponent::UiManagerComponent( QObject* parent )
: Component( parent )
, d( new UiManagerComponentPrivate )
{
}
UiManagerComponent::UiManagerComponent( const UiManagerComponent& other )
: Component( other )
, d( other.d )
{
}
UiManagerComponent::~UiManagerComponent()
{
delete d->fbo;
delete d;
}
QString UiManagerComponent::category() const
{
return QString( "Graphics Rendering" );
}
void UiManagerComponent::initialize()
{
QGLWidget* widget = GluonGraphics::Engine::instance()->renderWidget();
d->texture = 0;
// d->fbo = GluonGraphics::Engine::instance()->fbo();
d->pixmap = QPixmap( widget->size() );
d->pixmap.fill( Qt::transparent );
// d->view->setParent(widget->parentWidget());
// d->view->setAttribute(Qt::WA_TranslucentBackground);
// d->view->setAttribute(Qt::WA_NoSystemBackground);
// d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground);
// d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground);
// d->view->setStyleSheet("border: none");
// QPalette p = d->view->viewport()->palette();
// p.setColor(QPalette::Base, Qt::transparent);
// d->view->viewport()->setPalette(p);
// d->view->setScene(d->scene);
// d->view->setSceneRect(QRectF(0,0,1000,1000));
d->scene->setSceneRect(QRectF(QPointF(0,0), widget->size()));
// d->view->resize(widget->size());
// d->view->show();
// d->scene->setBackgroundBrush(Qt::blue);
// d->texture = widget->bindTexture(d->pixmap);
// widget->update();
// widget->updateGL();
// widget->makeCurrent();
if( d->ui && !d->ui->isLoaded() )
{
qmlRegisterType<GluonEngine::GameObject>("org.kde.gluon", 1, 0, "GameObject" );
qmlRegisterInterface<GluonEngine::GameObject>("gameObject");
d->ui->load();
QDeclarativeEngine* engine = d->ui->engine();
d->engineAccess = new EngineAccess(this);
engine->rootContext()->setContextProperty( "__engineAccess", d->engineAccess );
//Glorious hack:steal the engine
QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),
"__engineAccess.setEngine( this )" );
expr->evaluate();
delete expr;
start();
}
}
void UiManagerComponent::setScriptEngine( QScriptValue &value )
{
QScriptEngine* engine = value.engine();
QScriptValue originalGlobalObject = engine->globalObject();
QScriptValue newGlobalObject = engine->newObject();
QString eval = QLatin1String( "eval" );
QString version = QLatin1String( "version" );
QScriptValueIterator iter( originalGlobalObject );
QVector<QString> names;
QVector<QScriptValue> values;
QVector<QScriptValue::PropertyFlags> flags;
while ( iter.hasNext() )
{
iter.next();
QString name = iter.name();
if ( name == version )
{
continue;
}
if ( name != eval )
{
names.append( name );
values.append( iter.value() );
flags.append( iter.flags() | QScriptValue::Undeletable );
}
newGlobalObject.setProperty( iter.scriptName(), iter.value() );
}
engine->setGlobalObject( newGlobalObject );
qScriptRegisterQObjectMetaType<GameObject*>( engine );
qScriptRegisterQObjectMetaType<GluonObject*>( engine );
QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;
QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;
QScriptValue gameObj = engine->newQObject( gameObject(), ownership, wrapOptions );
engine->globalObject().setProperty( "GameObject", gameObj );
delete d->engineAccess;
d->ui->engine()->rootContext()->setContextProperty( "__engineAccess", 0 );
}
void UiManagerComponent::start()
{
if( d->ui && d->ui->isLoaded() )
{
d->ui->execute();
QGraphicsWidget* widget = d->ui->widget();
if( widget )
{
d->scene->addItem( widget );
// widget->setGeometry( 0, 0, 100, 100 );
}
}
if( d->mouse )
{
// d->mouse->setEnabled( true );
}
}
void UiManagerComponent::draw( int timeLapse )
{
Q_UNUSED( timeLapse )
RenderWidget* widget = GluonGraphics::Engine::instance()->renderWidget();
d->pixmap.fill( Qt::transparent );
QPainter p( &d->pixmap );
d->scene->render( &p );
widget->setPixmap(d->pixmap);
}
void UiManagerComponent::update( int elapsedMilliseconds )
{
if( d->ui && d->ui->isLoaded() )
{
QDeclarativeExpression *expr = new QDeclarativeExpression( d->ui->engine()->rootContext(),
d->ui->widget(), "update()" );
expr->evaluate();
if( expr->hasError() )
{
debug( expr->error().toString() );
}
delete expr;
}
}
void UiManagerComponent::cleanup()
{
if( !d->ui )
{
return;
}
QGraphicsWidget* widget = d->ui->widget();
if( d->scene && widget && widget->scene() == d->scene )
{
// d->scene->removeItem( widget );
}
}
void UiManagerComponent::setUi(UiAsset* ui)
{
d->ui = ui;
}
UiAsset* UiManagerComponent::ui() const
{
return d->ui;
}
void UiManagerComponent::setSize( const QSizeF& size )
{
d->size = size;
}
QSizeF UiManagerComponent::size() const
{
return d->size;
}
Q_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );
#include "uimanagercomponent.moc"
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include "base/all.h"
#include "rpc/marshal.h"
using namespace rpc;
TEST(marshal, content_size) {
Marshal m;
rpc::i32 a = 4;
EXPECT_EQ(m.content_size(), 0u);
m << a;
EXPECT_EQ(m.content_size(), 4u);
rpc::i32 b = 9;
m >> b;
EXPECT_EQ(m.content_size(), 0u);
EXPECT_EQ(a, b);
}
const i64 g_chunk_size = 1000;
const i64 g_bytes_per_writer = 1000 * 1000 * 1000;
Marshal g_mt_benchmark_marshal;
pthread_mutex_t g_mt_benchmark_mutex = PTHREAD_MUTEX_INITIALIZER;
static void* start_mt_benchmark_writers(void* args) {
char* dummy_data = new char[g_chunk_size];
memset(dummy_data, 0, g_chunk_size);
int n_bytes_written = 0;
while (n_bytes_written < g_bytes_per_writer) {
int n_write = std::min(g_chunk_size, g_bytes_per_writer - n_bytes_written);
Pthread_mutex_lock(&g_mt_benchmark_mutex);
int ret = g_mt_benchmark_marshal.write(dummy_data, n_write);
g_mt_benchmark_marshal.update_read_barrier();
Pthread_mutex_unlock(&g_mt_benchmark_mutex);
verify(ret > 0);
n_bytes_written += ret;
}
delete[] dummy_data;
pthread_exit(nullptr);
return nullptr;
}
// multi-thread benchmark
TEST(marshal, mt_benchmark) {
const int n_writers = 10;
pthread_t th_writers[n_writers];
for (int i = 0; i < n_writers; i++) {
Pthread_create(&th_writers[i], nullptr, start_mt_benchmark_writers, nullptr);
}
io_ratelimit no_rate;
int null_fd = open("/dev/null", O_WRONLY);
i64 n_bytes_read = 0;
double report_time = -1.0;
Timer xfer_timer;
xfer_timer.start();
while (n_bytes_read < n_writers * g_bytes_per_writer) {
Pthread_mutex_lock(&g_mt_benchmark_mutex);
Marshal::read_barrier rb = g_mt_benchmark_marshal.get_read_barrier();
int ret = g_mt_benchmark_marshal.write_to_fd(null_fd, rb, no_rate);
Pthread_mutex_unlock(&g_mt_benchmark_mutex);
verify(ret >= 0);
n_bytes_read += ret;
struct timeval tm;
gettimeofday(&tm, NULL);
double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0;
if (now - report_time > 1) {
Log::info("bytes transferred = %ld (%.2lf%%)", n_bytes_read, n_bytes_read * 100.0 / (n_writers * g_bytes_per_writer));
report_time = now;
}
}
xfer_timer.stop();
Log::info("marshal xfer speed = %.2lf M/s (%d writers, %d bytes per write)",
n_bytes_read / 1024.0 / 1024.0 / xfer_timer.elapsed(), n_writers, g_chunk_size);
close(null_fd);
for (int i = 0; i < n_writers; i++) {
Pthread_join(th_writers[i], nullptr);
}
}
<commit_msg>whitespace<commit_after>#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include "base/all.h"
#include "rpc/marshal.h"
using namespace rpc;
TEST(marshal, content_size) {
Marshal m;
rpc::i32 a = 4;
EXPECT_EQ(m.content_size(), 0u);
m << a;
EXPECT_EQ(m.content_size(), 4u);
rpc::i32 b = 9;
m >> b;
EXPECT_EQ(m.content_size(), 0u);
EXPECT_EQ(a, b);
}
const i64 g_chunk_size = 1000;
const i64 g_bytes_per_writer = 1000 * 1000 * 1000;
Marshal g_mt_benchmark_marshal;
pthread_mutex_t g_mt_benchmark_mutex = PTHREAD_MUTEX_INITIALIZER;
static void* start_mt_benchmark_writers(void* args) {
char* dummy_data = new char[g_chunk_size];
memset(dummy_data, 0, g_chunk_size);
int n_bytes_written = 0;
while (n_bytes_written < g_bytes_per_writer) {
int n_write = std::min(g_chunk_size, g_bytes_per_writer - n_bytes_written);
Pthread_mutex_lock(&g_mt_benchmark_mutex);
int ret = g_mt_benchmark_marshal.write(dummy_data, n_write);
g_mt_benchmark_marshal.update_read_barrier();
Pthread_mutex_unlock(&g_mt_benchmark_mutex);
verify(ret > 0);
n_bytes_written += ret;
}
delete[] dummy_data;
pthread_exit(nullptr);
return nullptr;
}
// multi-thread benchmark
TEST(marshal, mt_benchmark) {
const int n_writers = 10;
pthread_t th_writers[n_writers];
for (int i = 0; i < n_writers; i++) {
Pthread_create(&th_writers[i], nullptr, start_mt_benchmark_writers, nullptr);
}
io_ratelimit no_rate;
int null_fd = open("/dev/null", O_WRONLY);
i64 n_bytes_read = 0;
double report_time = -1.0;
Timer xfer_timer;
xfer_timer.start();
while (n_bytes_read < n_writers * g_bytes_per_writer) {
Pthread_mutex_lock(&g_mt_benchmark_mutex);
Marshal::read_barrier rb = g_mt_benchmark_marshal.get_read_barrier();
int ret = g_mt_benchmark_marshal.write_to_fd(null_fd, rb, no_rate);
Pthread_mutex_unlock(&g_mt_benchmark_mutex);
verify(ret >= 0);
n_bytes_read += ret;
struct timeval tm;
gettimeofday(&tm, NULL);
double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0;
if (now - report_time > 1) {
Log::info("bytes transferred = %ld (%.2lf%%)", n_bytes_read, n_bytes_read * 100.0 / (n_writers * g_bytes_per_writer));
report_time = now;
}
}
xfer_timer.stop();
Log::info("marshal xfer speed = %.2lf M/s (%d writers, %d bytes per write)",
n_bytes_read / 1024.0 / 1024.0 / xfer_timer.elapsed(), n_writers, g_chunk_size);
close(null_fd);
for (int i = 0; i < n_writers; i++) {
Pthread_join(th_writers[i], nullptr);
}
}
<|endoftext|> |
<commit_before>#include <stan/mcmc/mcmc_output.hpp>
#include <gtest/gtest.h>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <boost/math/distributions/students_t.hpp>
#include <stdio.h>
class binormal : public ::testing::Test {
protected:
virtual void SetUp() {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator += fgetc(in);
pclose(in);
model.append("models").append(path_separator);
model.append("basic_distributions").append(path_separator);
model.append("binormal");
output1 = model + "1.csv";
output2 = model + "2.csv";
factory.addFile(output1);
factory.addFile(output2);
expected_y1 = 0.0;
expected_y2 = 0.0;
}
std::string path_separator;
std::string model;
std::string output1;
std::string output2;
stan::mcmc::mcmc_output_factory factory;
double expected_y1;
double expected_y2;
};
TEST_F(binormal,runModel) {
std::string command;
command = model;
command += " --samples=";
command += output1;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
command = model;
command += " --samples=";
command += output2;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
}
TEST_F(binormal, y1) {
stan::mcmc::mcmc_output y1 = factory.create("y.1");
double neff = y1.effectiveSize();
boost::math::students_t t(neff-1.0);
double T = boost::math::quantile(t, 0.975);
EXPECT_NEAR(expected_y1, y1.mean(), T*sqrt(y1.variance()/neff));
}
TEST_F(binormal, y2) {
stan::mcmc::mcmc_output y2 = factory.create("y.2");
double neff = y2.effectiveSize();
boost::math::students_t t(neff-1.0);
double T = boost::math::quantile(t, 0.975);
EXPECT_NEAR(expected_y2, y2.mean(), T*sqrt(y2.variance()/neff));
}
<commit_msg>test-models: comment out tests for binormal model for now<commit_after>#include <stan/mcmc/mcmc_output.hpp>
#include <gtest/gtest.h>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <boost/math/distributions/students_t.hpp>
#include <stdio.h>
class binormal : public ::testing::Test {
protected:
virtual void SetUp() {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator += fgetc(in);
pclose(in);
model.append("models").append(path_separator);
model.append("basic_distributions").append(path_separator);
model.append("binormal");
output1 = model + "1.csv";
output2 = model + "2.csv";
factory.addFile(output1);
factory.addFile(output2);
expected_y1 = 0.0;
expected_y2 = 0.0;
}
std::string path_separator;
std::string model;
std::string output1;
std::string output2;
stan::mcmc::mcmc_output_factory factory;
double expected_y1;
double expected_y2;
};
TEST_F(binormal,runModel) {
std::string command;
command = model;
command += " --samples=";
command += output1;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
command = model;
command += " --samples=";
command += output2;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
}
/*
TEST_F(binormal, y1) {
stan::mcmc::mcmc_output y1 = factory.create("y.1");
double neff = y1.effectiveSize();
boost::math::students_t t(neff-1.0);
double T = boost::math::quantile(t, 0.975);
EXPECT_NEAR(expected_y1, y1.mean(), T*sqrt(y1.variance()/neff));
}
TEST_F(binormal, y2) {
stan::mcmc::mcmc_output y2 = factory.create("y.2");
double neff = y2.effectiveSize();
boost::math::students_t t(neff-1.0);
double T = boost::math::quantile(t, 0.975);
EXPECT_NEAR(expected_y2, y2.mean(), T*sqrt(y2.variance()/neff));
}
*/
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stdexcept>
class Models_BugsExamples_Vol2_Dogs : public ::testing::Test {
protected:
virtual void SetUp() {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator += fgetc(in);
pclose(in);
model.append("models").append(path_separator);
model.append("bugs_examples").append(path_separator);
model.append("vol2").append(path_separator);
model.append("dogs").append(path_separator);
model.append("dogs");
output1 = model + "1.csv";
output2 = model + "2.csv";
data = model + ".Rdata";
}
std::string path_separator;
std::string model;
std::string output1;
std::string output2;
std::string data;
};
TEST_F(Models_BugsExamples_Vol2_Dogs,RunModel) {
std::string command;
command = model;
command += " --samples=";
command += output1;
command += " --data=";
command += data;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
command = model;
command += " --samples=";
command += output2;
command += " --data=";
command += data;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
}
<commit_msg>test-models: removed unused test<commit_after><|endoftext|> |
<commit_before>
#include <cassert>
#include <algorithm>
#include <reflectionzeug/new/PropertyGroup.h>
#include <reflectionzeug/new/AbstractProperty.h>
#include <reflectionzeug/new/AbstractVisitor.h>
#include <reflectionzeug/util.h>
namespace reflectionzeug
{
PropertyGroup2::PropertyGroup2(const std::string & name)
: m_name(name)
, m_ownsProperties(true)
{
}
PropertyGroup2::PropertyGroup2()
: m_ownsProperties(true)
{
}
PropertyGroup2::~PropertyGroup2()
{
// Delete owned properties
if (m_ownsProperties)
{
for (AbstractProperty2 * property : m_properties)
{
delete property;
}
}
}
std::string PropertyGroup2::name() const
{
return m_name;
}
// [TODO]
/*
Variant PropertyGroup2::toVariant() const
{
}
*/
// [TODO]
/*
bool PropertyGroup2::fromVariant(const Variant & value)
{
}
*/
const std::unordered_map<std::string, AbstractProperty2 *> & PropertyGroup2::properties() const
{
return m_propertiesMap;
}
AbstractProperty2 * PropertyGroup2::property(const std::string & path)
{
std::vector<std::string> splittedPath = util::split(path, '/');
return const_cast<AbstractProperty2 *>(findProperty(splittedPath));
}
const AbstractProperty2 * PropertyGroup2::property(const std::string & path) const
{
std::vector<std::string> splittedPath = util::split(path, '/');
return findProperty(splittedPath);
}
AbstractProperty2 * PropertyGroup2::addProperty(AbstractProperty2 * property)
{
// Get property as abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
// Reject properties that have no name or whose name already exists
if (!value || !value->hasName() || this->propertyExists(value->name()))
{
return nullptr;
}
// Invoke callback
beforeAdd(count(), property);
// Add property
m_properties.push_back(property);
m_propertiesMap.insert(std::make_pair(value->name(), property));
// Invoke callback
afterAdd(count(), property);
// Return property
return property;
}
PropertyGroup2 * PropertyGroup2::group(const std::string & path)
{
// Get property by path
AbstractProperty2 * property = this->property(path);
if (!property) {
return nullptr;
}
// Convert into group
return property->as<PropertyGroup2>();
}
const PropertyGroup2 * PropertyGroup2::group(const std::string & path) const
{
// Get property by path
const AbstractProperty2 * property = this->property(path);
if (!property) {
return nullptr;
}
// Convert into group
return property->as<PropertyGroup2>();
}
PropertyGroup2 * PropertyGroup2::addGroup(const std::string & name)
{
// Create group
PropertyGroup2 * group = new PropertyGroup2(name);
if (!this->addProperty(group))
{
// Abort, if group could not be added
delete group;
return nullptr;
}
return group;
}
PropertyGroup2 * PropertyGroup2::ensureGroup(const std::string & path)
{
std::vector<std::string> splittedPath = util::split(path, '/');
return ensureGroup(splittedPath);
}
bool PropertyGroup2::isEmpty() const
{
return m_properties.size() == 0;
}
size_t PropertyGroup2::count() const
{
return m_properties.size();
}
AbstractValue * PropertyGroup2::at(size_t index)
{
// Check if index is valid
if (index >= this->count())
{
return nullptr;
}
// Return property
return m_properties[index]->asValue();
}
const AbstractValue * PropertyGroup2::at(size_t index) const
{
// Check if index is valid
if (index >= this->count())
{
return nullptr;
}
// Return property
return m_properties[index]->asValue();
}
int PropertyGroup2::indexOf(const AbstractValue * value) const
{
// Check input parameter
assert(value);
// Convert into property
const AbstractProperty2 * property = dynamic_cast<const AbstractProperty2 *>(value);
if (!property)
{
return -1;
}
// Check if property exists in the group
if (!this->propertyExists(value->name()))
{
return -1;
}
// Return index of property
return (int)std::distance(m_properties.begin(), std::find(m_properties.begin(), m_properties.end(), property));
}
void PropertyGroup2::forEach(const std::function<void(AbstractValue &)> & callback)
{
// For each property
for (AbstractProperty2 * property : m_properties)
{
// Get abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
if (!value) {
continue;
}
// Invoke callback
callback(*value);
}
}
void PropertyGroup2::forEach(const std::function<void(const AbstractValue &)> & callback) const
{
// For each property
for (AbstractProperty2 * property : m_properties)
{
// Get abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
if (!value) {
continue;
}
// Invoke callback
callback(*value);
}
}
AbstractProperty2 * PropertyGroup2::takeProperty(const std::string & name)
{
// Check if property exists in this group
if (!this->propertyExists(name))
{
return nullptr;
}
// Get property and property index
AbstractProperty2 * property = m_propertiesMap.at(name);
auto it = std::find(m_properties.begin(), m_properties.end(), property);
size_t index = indexOf( (*it)->asValue() );
// Invoke callback
beforeRemove(index);
// Remove property from group
m_properties.erase(it);
m_propertiesMap.erase(name);
// Invoke callback
afterRemove(index);
// Return property
return property;
}
void PropertyGroup2::clear()
{
// Remove all properties
auto it = m_properties.begin();
while (it != m_properties.end())
{
// Get property index
size_t index = std::distance(m_properties.begin(), it);
// Invoke callback
beforeRemove(index);
// Delete property
if (m_ownsProperties)
{
AbstractProperty2 * property = *it;
delete property;
}
// Remove property
m_propertiesMap.erase((*it)->asValue()->name());
it = m_properties.erase(it);
// Invoke callback
afterRemove(index);
}
// Make sure that property list is empty
assert(m_properties.empty());
assert(m_propertiesMap.empty());
}
void PropertyGroup2::setOwnsProperties(bool owns)
{
m_ownsProperties = owns;
}
bool PropertyGroup2::propertyExists(const std::string & name) const
{
return m_propertiesMap.find(name) != m_propertiesMap.end();
}
bool PropertyGroup2::groupExists(const std::string & name) const
{
return this->propertyExists(name) &&
m_propertiesMap.at(name)->as<PropertyGroup2>() != nullptr;
}
void PropertyGroup2::forEach(const std::function<void(AbstractProperty2 &)> & callback)
{
// Visit all properties
for (AbstractProperty2 * property : m_properties)
{
callback(*property);
}
}
void PropertyGroup2::forEach(const std::function<void(const AbstractProperty2 &)> & callback) const
{
// Visit all properties
for (const AbstractProperty2 * property : m_properties)
{
callback(*property);
}
}
void PropertyGroup2::forEachCollection(const std::function<void(AbstractCollection &)> & callback)
{
// Visit all collections
for (AbstractProperty2 * property : m_properties)
{
// Check if property is a collection
AbstractCollection * collection = dynamic_cast<AbstractCollection *>(property);
if (collection) {
callback(*collection);
}
}
}
void PropertyGroup2::forEachCollection(const std::function<void(const AbstractCollection &)> & callback) const
{
// Visit all collections
for (const AbstractProperty2 * property : m_properties)
{
// Check if property is a collection
const AbstractCollection * collection = dynamic_cast<const AbstractCollection *>(property);
if (collection) {
callback(*collection);
}
}
}
void PropertyGroup2::forEachGroup(const std::function<void(PropertyGroup2 &)> & callback)
{
// Visit all groups
for (AbstractProperty2 * property : m_properties)
{
// Check if property is a group
PropertyGroup2 * group = dynamic_cast<PropertyGroup2 *>(property);
if (group) {
callback(*group);
}
}
}
void PropertyGroup2::forEachGroup(const std::function<void(const PropertyGroup2 &)> & callback) const
{
// Visit all groups
for (const AbstractProperty2 * property : m_properties)
{
// Check if property is a group
const PropertyGroup2 * group = dynamic_cast<const PropertyGroup2 *>(property);
if (group) {
callback(*group);
}
}
}
const AbstractProperty2 * PropertyGroup2::findProperty(const std::vector<std::string> & path) const
{
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
// Check if first element of the path exists in this group
if (!propertyExists(path.front())) {
return nullptr;
}
// Get the respective property
AbstractProperty2 * property = m_propertiesMap.at(path.front());
// If there are no more sub-paths, return the found property
if (path.size() == 1) {
return property;
}
// Otherwise, it is an element in the middle of the path, so ensure it is a group
if (!property->isGroup()) {
return nullptr;
}
// Call recursively on subgroup
return property->asGroup()->findProperty({ path.begin() + 1, path.end() });
// [TODO] Use iterative approach rather than recursion
}
PropertyGroup2 * PropertyGroup2::ensureGroup(const std::vector<std::string> & path)
{
// [TODO] Use iterative approach rather than recursion
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
// Check if group exists
PropertyGroup2 * group = nullptr;
if (propertyExists(path.front()))
{
// Get property
AbstractProperty2 * property = m_propertiesMap.at(path.front());
// Abort if this is not a group
if (!property->isGroup()) {
return nullptr;
}
// Get as group
group = property->asGroup();
}
else
{
// Add new group
group = addGroup(path.front());
}
// If there are no more sub-paths, return the group
if (path.size() == 1) {
return group;
}
// Otherwise, call recursively on subgroup
return group->ensureGroup(std::vector<std::string>(path.begin() + 1, path.end()));
}
void PropertyGroup2::accept(AbstractVisitor * visitor)
{
visitor->callVisitor<PropertyGroup2>(this);
visitor->callVisitor<AbstractCollection>(this);
}
} // namespace reflectionzeug
<commit_msg>Move comment<commit_after>
#include <cassert>
#include <algorithm>
#include <reflectionzeug/new/PropertyGroup.h>
#include <reflectionzeug/new/AbstractProperty.h>
#include <reflectionzeug/new/AbstractVisitor.h>
#include <reflectionzeug/util.h>
namespace reflectionzeug
{
PropertyGroup2::PropertyGroup2(const std::string & name)
: m_name(name)
, m_ownsProperties(true)
{
}
PropertyGroup2::PropertyGroup2()
: m_ownsProperties(true)
{
}
PropertyGroup2::~PropertyGroup2()
{
// Delete owned properties
if (m_ownsProperties)
{
for (AbstractProperty2 * property : m_properties)
{
delete property;
}
}
}
std::string PropertyGroup2::name() const
{
return m_name;
}
// [TODO]
/*
Variant PropertyGroup2::toVariant() const
{
}
*/
// [TODO]
/*
bool PropertyGroup2::fromVariant(const Variant & value)
{
}
*/
const std::unordered_map<std::string, AbstractProperty2 *> & PropertyGroup2::properties() const
{
return m_propertiesMap;
}
AbstractProperty2 * PropertyGroup2::property(const std::string & path)
{
std::vector<std::string> splittedPath = util::split(path, '/');
return const_cast<AbstractProperty2 *>(findProperty(splittedPath));
}
const AbstractProperty2 * PropertyGroup2::property(const std::string & path) const
{
std::vector<std::string> splittedPath = util::split(path, '/');
return findProperty(splittedPath);
}
AbstractProperty2 * PropertyGroup2::addProperty(AbstractProperty2 * property)
{
// Get property as abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
// Reject properties that have no name or whose name already exists
if (!value || !value->hasName() || this->propertyExists(value->name()))
{
return nullptr;
}
// Invoke callback
beforeAdd(count(), property);
// Add property
m_properties.push_back(property);
m_propertiesMap.insert(std::make_pair(value->name(), property));
// Invoke callback
afterAdd(count(), property);
// Return property
return property;
}
PropertyGroup2 * PropertyGroup2::group(const std::string & path)
{
// Get property by path
AbstractProperty2 * property = this->property(path);
if (!property) {
return nullptr;
}
// Convert into group
return property->as<PropertyGroup2>();
}
const PropertyGroup2 * PropertyGroup2::group(const std::string & path) const
{
// Get property by path
const AbstractProperty2 * property = this->property(path);
if (!property) {
return nullptr;
}
// Convert into group
return property->as<PropertyGroup2>();
}
PropertyGroup2 * PropertyGroup2::addGroup(const std::string & name)
{
// Create group
PropertyGroup2 * group = new PropertyGroup2(name);
if (!this->addProperty(group))
{
// Abort, if group could not be added
delete group;
return nullptr;
}
return group;
}
PropertyGroup2 * PropertyGroup2::ensureGroup(const std::string & path)
{
std::vector<std::string> splittedPath = util::split(path, '/');
return ensureGroup(splittedPath);
}
bool PropertyGroup2::isEmpty() const
{
return m_properties.size() == 0;
}
size_t PropertyGroup2::count() const
{
return m_properties.size();
}
AbstractValue * PropertyGroup2::at(size_t index)
{
// Check if index is valid
if (index >= this->count())
{
return nullptr;
}
// Return property
return m_properties[index]->asValue();
}
const AbstractValue * PropertyGroup2::at(size_t index) const
{
// Check if index is valid
if (index >= this->count())
{
return nullptr;
}
// Return property
return m_properties[index]->asValue();
}
int PropertyGroup2::indexOf(const AbstractValue * value) const
{
// Check input parameter
assert(value);
// Convert into property
const AbstractProperty2 * property = dynamic_cast<const AbstractProperty2 *>(value);
if (!property)
{
return -1;
}
// Check if property exists in the group
if (!this->propertyExists(value->name()))
{
return -1;
}
// Return index of property
return (int)std::distance(m_properties.begin(), std::find(m_properties.begin(), m_properties.end(), property));
}
void PropertyGroup2::forEach(const std::function<void(AbstractValue &)> & callback)
{
// For each property
for (AbstractProperty2 * property : m_properties)
{
// Get abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
if (!value) {
continue;
}
// Invoke callback
callback(*value);
}
}
void PropertyGroup2::forEach(const std::function<void(const AbstractValue &)> & callback) const
{
// For each property
for (AbstractProperty2 * property : m_properties)
{
// Get abstract value
AbstractValue * value = dynamic_cast<AbstractValue *>(property);
if (!value) {
continue;
}
// Invoke callback
callback(*value);
}
}
AbstractProperty2 * PropertyGroup2::takeProperty(const std::string & name)
{
// Check if property exists in this group
if (!this->propertyExists(name))
{
return nullptr;
}
// Get property and property index
AbstractProperty2 * property = m_propertiesMap.at(name);
auto it = std::find(m_properties.begin(), m_properties.end(), property);
size_t index = indexOf( (*it)->asValue() );
// Invoke callback
beforeRemove(index);
// Remove property from group
m_properties.erase(it);
m_propertiesMap.erase(name);
// Invoke callback
afterRemove(index);
// Return property
return property;
}
void PropertyGroup2::clear()
{
// Remove all properties
auto it = m_properties.begin();
while (it != m_properties.end())
{
// Get property index
size_t index = std::distance(m_properties.begin(), it);
// Invoke callback
beforeRemove(index);
// Delete property
if (m_ownsProperties)
{
AbstractProperty2 * property = *it;
delete property;
}
// Remove property
m_propertiesMap.erase((*it)->asValue()->name());
it = m_properties.erase(it);
// Invoke callback
afterRemove(index);
}
// Make sure that property list is empty
assert(m_properties.empty());
assert(m_propertiesMap.empty());
}
void PropertyGroup2::setOwnsProperties(bool owns)
{
m_ownsProperties = owns;
}
bool PropertyGroup2::propertyExists(const std::string & name) const
{
return m_propertiesMap.find(name) != m_propertiesMap.end();
}
bool PropertyGroup2::groupExists(const std::string & name) const
{
return this->propertyExists(name) &&
m_propertiesMap.at(name)->as<PropertyGroup2>() != nullptr;
}
void PropertyGroup2::forEach(const std::function<void(AbstractProperty2 &)> & callback)
{
// Visit all properties
for (AbstractProperty2 * property : m_properties)
{
callback(*property);
}
}
void PropertyGroup2::forEach(const std::function<void(const AbstractProperty2 &)> & callback) const
{
// Visit all properties
for (const AbstractProperty2 * property : m_properties)
{
callback(*property);
}
}
void PropertyGroup2::forEachCollection(const std::function<void(AbstractCollection &)> & callback)
{
// Visit all collections
for (AbstractProperty2 * property : m_properties)
{
// Check if property is a collection
AbstractCollection * collection = dynamic_cast<AbstractCollection *>(property);
if (collection) {
callback(*collection);
}
}
}
void PropertyGroup2::forEachCollection(const std::function<void(const AbstractCollection &)> & callback) const
{
// Visit all collections
for (const AbstractProperty2 * property : m_properties)
{
// Check if property is a collection
const AbstractCollection * collection = dynamic_cast<const AbstractCollection *>(property);
if (collection) {
callback(*collection);
}
}
}
void PropertyGroup2::forEachGroup(const std::function<void(PropertyGroup2 &)> & callback)
{
// Visit all groups
for (AbstractProperty2 * property : m_properties)
{
// Check if property is a group
PropertyGroup2 * group = dynamic_cast<PropertyGroup2 *>(property);
if (group) {
callback(*group);
}
}
}
void PropertyGroup2::forEachGroup(const std::function<void(const PropertyGroup2 &)> & callback) const
{
// Visit all groups
for (const AbstractProperty2 * property : m_properties)
{
// Check if property is a group
const PropertyGroup2 * group = dynamic_cast<const PropertyGroup2 *>(property);
if (group) {
callback(*group);
}
}
}
const AbstractProperty2 * PropertyGroup2::findProperty(const std::vector<std::string> & path) const
{
// [TODO] Use iterative approach rather than recursion
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
// Check if first element of the path exists in this group
if (!propertyExists(path.front())) {
return nullptr;
}
// Get the respective property
AbstractProperty2 * property = m_propertiesMap.at(path.front());
// If there are no more sub-paths, return the found property
if (path.size() == 1) {
return property;
}
// Otherwise, it is an element in the middle of the path, so ensure it is a group
if (!property->isGroup()) {
return nullptr;
}
// Call recursively on subgroup
return property->asGroup()->findProperty({ path.begin() + 1, path.end() });
}
PropertyGroup2 * PropertyGroup2::ensureGroup(const std::vector<std::string> & path)
{
// [TODO] Use iterative approach rather than recursion
// Check if path is valid
if (path.size() == 0) {
return nullptr;
}
// Check if group exists
PropertyGroup2 * group = nullptr;
if (propertyExists(path.front()))
{
// Get property
AbstractProperty2 * property = m_propertiesMap.at(path.front());
// Abort if this is not a group
if (!property->isGroup()) {
return nullptr;
}
// Get as group
group = property->asGroup();
}
else
{
// Add new group
group = addGroup(path.front());
}
// If there are no more sub-paths, return the group
if (path.size() == 1) {
return group;
}
// Otherwise, call recursively on subgroup
return group->ensureGroup(std::vector<std::string>(path.begin() + 1, path.end()));
}
void PropertyGroup2::accept(AbstractVisitor * visitor)
{
visitor->callVisitor<PropertyGroup2>(this);
visitor->callVisitor<AbstractCollection>(this);
}
} // namespace reflectionzeug
<|endoftext|> |
<commit_before>#include <osg/CameraNode>
#include <osg/io_utils>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include "Matrix.h"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool CameraNode_readLocalData(Object& obj, Input& fr);
bool CameraNode_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraNodeProxy
(
new osg::CameraNode,
"CameraNode",
"Object Node Transform CameraNode Group",
&CameraNode_readLocalData,
&CameraNode_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool CameraNode_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
CameraNode& camera = static_cast<CameraNode&>(obj);
if (fr.matchSequence("clearColor %f %f %f %f"))
{
Vec4 color;
fr[1].getFloat(color[0]);
fr[2].getFloat(color[1]);
fr[3].getFloat(color[2]);
fr[4].getFloat(color[3]);
camera.setClearColor(color);
fr +=5 ;
iteratorAdvanced = true;
};
if (fr.matchSequence("clearMask %i"))
{
unsigned int value;
fr[1].getUInt(value);
camera.setClearMask(value);
fr += 2;
iteratorAdvanced = true;
}
osg::ref_ptr<osg::StateAttribute> attribute;
while((attribute=fr.readStateAttribute())!=NULL)
{
osg::Viewport* viewport = dynamic_cast<osg::Viewport*>(attribute.get());
if (viewport) camera.setViewport(viewport);
else
{
osg::ColorMask* colormask = dynamic_cast<osg::ColorMask*>(attribute.get());
camera.setColorMask(colormask);
}
}
if (fr.matchSequence("transformOrder %w"))
{
if (fr[1].matchWord("PRE_MULTIPLE")) camera.setTransformOrder(osg::CameraNode::PRE_MULTIPLE);
else if (fr[1].matchWord("POST_MULTIPLE")) camera.setTransformOrder(osg::CameraNode::POST_MULTIPLE);
fr += 2;
iteratorAdvanced = true;
}
Matrix matrix;
if (readMatrix(matrix,fr,"ProjectionMatrix"))
{
camera.setProjectionMatrix(matrix);
iteratorAdvanced = true;
}
if (readMatrix(matrix,fr,"ViewMatrix"))
{
camera.setViewMatrix(matrix);
iteratorAdvanced = true;
}
if (fr.matchSequence("renderOrder %w"))
{
if (fr[1].matchWord("PRE_RENDER")) camera.setRenderOrder(osg::CameraNode::PRE_RENDER);
else if (fr[1].matchWord("NESTED_RENDER")) camera.setRenderOrder(osg::CameraNode::NESTED_RENDER);
else if (fr[1].matchWord("POST_RENDER")) camera.setRenderOrder(osg::CameraNode::POST_RENDER);
fr += 2;
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool CameraNode_writeLocalData(const Object& obj, Output& fw)
{
const CameraNode& camera = static_cast<const CameraNode&>(obj);
fw.indent()<<"clearColor "<<camera.getClearColor()<<std::endl;
fw.indent()<<"clearMask 0x"<<std::hex<<camera.getClearMask()<<std::endl;
if (camera.getColorMask())
{
fw.writeObject(*camera.getColorMask());
}
if (camera.getViewport())
{
fw.writeObject(*camera.getViewport());
}
fw.indent()<<"transformOrder ";
switch(camera.getTransformOrder())
{
case(osg::CameraNode::PRE_MULTIPLE): fw <<"PRE_MULTIPLE"<<std::endl; break;
case(osg::CameraNode::POST_MULTIPLE): fw <<"POST_MULTIPLE"<<std::endl; break;
}
writeMatrix(camera.getProjectionMatrix(),fw,"ProjectionMatrix");
writeMatrix(camera.getViewMatrix(),fw,"ViewMatrix");
fw.indent()<<"renderOrder ";
switch(camera.getRenderOrder())
{
case(osg::CameraNode::PRE_RENDER): fw <<"PRE_RENDER"<<std::endl; break;
case(osg::CameraNode::NESTED_RENDER): fw <<"NESTED_RENDER"<<std::endl; break;
case(osg::CameraNode::POST_RENDER): fw <<"POST_RENDER"<<std::endl; break;
}
return true;
}
<commit_msg>Improvements to CameraNode IO support, now handles render to texture.<commit_after>#include <osg/CameraNode>
#include <osg/io_utils>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include "Matrix.h"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool CameraNode_readLocalData(Object& obj, Input& fr);
bool CameraNode_writeLocalData(const Object& obj, Output& fw);
bool CameraNode_matchBufferComponentStr(const char* str,CameraNode::BufferComponent& buffer);
const char* CameraNode_getBufferComponentStr(CameraNode::BufferComponent buffer);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraNodeProxy
(
new osg::CameraNode,
"CameraNode",
"Object Node Transform CameraNode Group",
&CameraNode_readLocalData,
&CameraNode_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool CameraNode_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
CameraNode& camera = static_cast<CameraNode&>(obj);
if (fr.matchSequence("clearColor %f %f %f %f"))
{
Vec4 color;
fr[1].getFloat(color[0]);
fr[2].getFloat(color[1]);
fr[3].getFloat(color[2]);
fr[4].getFloat(color[3]);
camera.setClearColor(color);
fr +=5 ;
iteratorAdvanced = true;
};
if (fr.matchSequence("clearMask %i"))
{
unsigned int value;
fr[1].getUInt(value);
camera.setClearMask(value);
fr += 2;
iteratorAdvanced = true;
}
osg::ref_ptr<osg::StateAttribute> attribute;
while((attribute=fr.readStateAttribute())!=NULL)
{
osg::Viewport* viewport = dynamic_cast<osg::Viewport*>(attribute.get());
if (viewport) camera.setViewport(viewport);
else
{
osg::ColorMask* colormask = dynamic_cast<osg::ColorMask*>(attribute.get());
camera.setColorMask(colormask);
}
}
if (fr.matchSequence("transformOrder %w"))
{
if (fr[1].matchWord("PRE_MULTIPLE")) camera.setTransformOrder(osg::CameraNode::PRE_MULTIPLE);
else if (fr[1].matchWord("POST_MULTIPLE")) camera.setTransformOrder(osg::CameraNode::POST_MULTIPLE);
fr += 2;
iteratorAdvanced = true;
}
Matrix matrix;
if (readMatrix(matrix,fr,"ProjectionMatrix"))
{
camera.setProjectionMatrix(matrix);
iteratorAdvanced = true;
}
if (readMatrix(matrix,fr,"ViewMatrix"))
{
camera.setViewMatrix(matrix);
iteratorAdvanced = true;
}
if (fr.matchSequence("renderOrder %w"))
{
if (fr[1].matchWord("PRE_RENDER")) camera.setRenderOrder(osg::CameraNode::PRE_RENDER);
else if (fr[1].matchWord("NESTED_RENDER")) camera.setRenderOrder(osg::CameraNode::NESTED_RENDER);
else if (fr[1].matchWord("POST_RENDER")) camera.setRenderOrder(osg::CameraNode::POST_RENDER);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::CameraNode::RenderTargetImplementation implementation = osg::CameraNode::FRAME_BUFFER;
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) implementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) implementation = osg::CameraNode::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) implementation = osg::CameraNode::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) implementation = osg::CameraNode::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) implementation = osg::CameraNode::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(implementation);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::CameraNode::RenderTargetImplementation fallback = camera.getRenderTargetFallback();
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) fallback = osg::CameraNode::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) fallback = osg::CameraNode::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) fallback = osg::CameraNode::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) fallback = osg::CameraNode::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) fallback = osg::CameraNode::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(camera.getRenderTargetImplementation(), fallback);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("bufferComponent %w {"))
{
int entry = fr[1].getNoNestedBrackets();
CameraNode::BufferComponent buffer;
CameraNode_matchBufferComponentStr(fr[1].getStr(),buffer);
fr += 3;
CameraNode::Attachment& attachment = camera.getBufferAttachmentMap()[buffer];
// read attachment data.
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
bool localAdvance = false;
if (fr.matchSequence("internalFormat %i"))
{
fr[1].getUInt(attachment._internalFormat);
fr += 2;
localAdvance = true;
}
osg::ref_ptr<osg::Object> attribute;
while((attribute=fr.readObject())!=NULL)
{
localAdvance = true;
osg::Texture* texture = dynamic_cast<osg::Texture*>(attribute.get());
if (texture) attachment._texture = texture;
else
{
osg::Image* image = dynamic_cast<osg::Image*>(attribute.get());
attachment._image = image;
}
}
if (fr.matchSequence("level %i"))
{
fr[1].getUInt(attachment._level);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("face %i"))
{
fr[1].getUInt(attachment._face);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration TRUE"))
{
attachment._mipMapGeneration = true;
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration FALSE"))
{
attachment._mipMapGeneration = false;
fr += 2;
localAdvance = true;
}
if (!localAdvance) ++fr;
}
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool CameraNode_writeLocalData(const Object& obj, Output& fw)
{
const CameraNode& camera = static_cast<const CameraNode&>(obj);
fw.indent()<<"clearColor "<<camera.getClearColor()<<std::endl;
fw.indent()<<"clearMask 0x"<<std::hex<<camera.getClearMask()<<std::endl;
if (camera.getColorMask())
{
fw.writeObject(*camera.getColorMask());
}
if (camera.getViewport())
{
fw.writeObject(*camera.getViewport());
}
fw.indent()<<"transformOrder ";
switch(camera.getTransformOrder())
{
case(osg::CameraNode::PRE_MULTIPLE): fw <<"PRE_MULTIPLE"<<std::endl; break;
case(osg::CameraNode::POST_MULTIPLE): fw <<"POST_MULTIPLE"<<std::endl; break;
}
writeMatrix(camera.getProjectionMatrix(),fw,"ProjectionMatrix");
writeMatrix(camera.getViewMatrix(),fw,"ViewMatrix");
fw.indent()<<"renderOrder ";
switch(camera.getRenderOrder())
{
case(osg::CameraNode::PRE_RENDER): fw <<"PRE_RENDER"<<std::endl; break;
case(osg::CameraNode::NESTED_RENDER): fw <<"NESTED_RENDER"<<std::endl; break;
case(osg::CameraNode::POST_RENDER): fw <<"POST_RENDER"<<std::endl; break;
}
fw.indent()<<"renderTargetImplementation ";
switch(camera.getRenderTargetImplementation())
{
case(osg::CameraNode::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::CameraNode::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::CameraNode::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::CameraNode::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::CameraNode::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"renderTargetFallback ";
switch(camera.getRenderTargetFallback())
{
case(osg::CameraNode::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::CameraNode::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::CameraNode::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::CameraNode::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::CameraNode::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"drawBuffer "<<std::hex<<camera.getDrawBuffer()<<std::endl;
fw.indent()<<"readBuffer "<<std::hex<<camera.getReadBuffer()<<std::endl;
const osg::CameraNode::BufferAttachmentMap& bam = camera.getBufferAttachmentMap();
if (!bam.empty())
{
for(osg::CameraNode::BufferAttachmentMap::const_iterator itr=bam.begin();
itr!=bam.end();
++itr)
{
const osg::CameraNode::Attachment& attachment = itr->second;
fw.indent()<<"bufferComponent "<<CameraNode_getBufferComponentStr(itr->first)<<" {"<<std::endl;
fw.moveIn();
fw.indent()<<"internalFormat "<<attachment._internalFormat<<std::endl;
if (attachment._texture.valid())
{
fw.writeObject(*attachment._texture.get());
}
fw.indent()<<"level "<<attachment._level<<std::endl;
fw.indent()<<"face "<<attachment._face<<std::endl;
fw.indent()<<"mipMapGeneration "<<(attachment._mipMapGeneration ? "TRUE" : "FALSE")<<std::endl;
fw.moveOut();
fw.indent()<<"}"<<std::endl;
}
}
return true;
}
bool CameraNode_matchBufferComponentStr(const char* str,CameraNode::BufferComponent& buffer)
{
if (strcmp(str,"DEPTH_BUFFER")==0) buffer = osg::CameraNode::DEPTH_BUFFER;
else if (strcmp(str,"STENCIL_BUFFER")==0) buffer = osg::CameraNode::STENCIL_BUFFER;
else if (strcmp(str,"COLOR_BUFFER")==0) buffer = osg::CameraNode::COLOR_BUFFER;
else if (strcmp(str,"COLOR_BUFFER0")==0) buffer = osg::CameraNode::COLOR_BUFFER0;
else if (strcmp(str,"COLOR_BUFFER1")==0) buffer = osg::CameraNode::COLOR_BUFFER1;
else if (strcmp(str,"COLOR_BUFFER2")==0) buffer = osg::CameraNode::COLOR_BUFFER2;
else if (strcmp(str,"COLOR_BUFFER3")==0) buffer = osg::CameraNode::COLOR_BUFFER3;
else if (strcmp(str,"COLOR_BUFFER4")==0) buffer = osg::CameraNode::COLOR_BUFFER4;
else if (strcmp(str,"COLOR_BUFFER5")==0) buffer = osg::CameraNode::COLOR_BUFFER5;
else if (strcmp(str,"COLOR_BUFFER6")==0) buffer = osg::CameraNode::COLOR_BUFFER6;
else if (strcmp(str,"COLOR_BUFFER7")==0) buffer = osg::CameraNode::COLOR_BUFFER7;
else return false;
return true;
}
const char* CameraNode_getBufferComponentStr(CameraNode::BufferComponent buffer)
{
switch(buffer)
{
case (osg::CameraNode::DEPTH_BUFFER) : return "DEPTH_BUFFER";
case (osg::CameraNode::STENCIL_BUFFER) : return "STENCIL_BUFFER";
case (osg::CameraNode::COLOR_BUFFER) : return "COLOR_BUFFER";
case (osg::CameraNode::COLOR_BUFFER1) : return "COLOR_BUFFER1";
case (osg::CameraNode::COLOR_BUFFER2) : return "COLOR_BUFFER2";
case (osg::CameraNode::COLOR_BUFFER3) : return "COLOR_BUFFER3";
case (osg::CameraNode::COLOR_BUFFER4) : return "COLOR_BUFFER4";
case (osg::CameraNode::COLOR_BUFFER5) : return "COLOR_BUFFER5";
case (osg::CameraNode::COLOR_BUFFER6) : return "COLOR_BUFFER6";
case (osg::CameraNode::COLOR_BUFFER7) : return "COLOR_BUFFER7";
default : return "UnknownBufferComponent";
}
}
/*
bool CameraNode_matchBufferComponentStr(const char* str,CameraNode::BufferComponent buffer)
{
if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else if (strcmp(str,"")==0) mode = osg::CameraNode::;
else return false;
return true;
}
const char* CameraNode_getBufferComponentStr(CameraNode::BufferComponent buffer)
{
switch(mode)
{
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
case (osg::CameraNode::) : return "";
default : return "UnknownBufferComponent";
}
}
*/
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/IPCRingBuffer.h>
#include "IPCRingBufferResults.h"
#include "IPCRingBufferSharedObjects.h"
#include "SharedMemory.h"
#include "SharedMemoryObjectWithMutex.h"
#include <osvr/Util/ImagingReportTypesC.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <boost/version.hpp>
// Standard includes
#include <stdexcept>
#include <utility>
#include <type_traits>
namespace osvr {
namespace common {
#define OSVR_SHM_VERBOSE(X) OSVR_DEV_VERBOSE("IPCRingBuffer: " << X)
/// @brief the ABI level: this must be bumped if the layout of any
/// shared-memory objects (Bookkeeping, ElementData) changes, if Boost
/// Interprocess changes affect the utilized ABI, or if other changes occur
/// that would interfere with communication.
static IPCRingBuffer::abi_level_type SHM_SOURCE_ABI_LEVEL = 0;
/// Some tests that can be automated for ensuring validity of the ABI level
/// number.
#if (BOOST_VERSION > 105800)
#error \
"Using an untested Boost version - inspect the Boost Interprocess release notes/changelog to see if any ABI breaks affect us."
#endif
#ifdef _WIN32
#if (BOOST_VERSION < 105400)
#error \
"Boost Interprocess pre-1.54 on Win32 is ABI-incompatible with newer Boost due to changed bootstamp function."
#endif
#else // !_WIN32
// No obvious ABI breaks through 1.58 seem to apply to us on non-Windows
// platforms
#endif
static_assert(std::is_same<IPCRingBuffer::BackendType,
ipc::SharedMemoryBackendType>::value,
"The typedefs IPCRingBuffer::BackendType and "
"ipc::SharedMemoryBackendType must remain in sync!");
static_assert(
std::is_same<IPCRingBuffer::value_type, OSVR_ImageBufferElement>::value,
"The ring buffer's individual byte type must match the image buffer "
"element type.");
namespace bip = boost::interprocess;
namespace {
typedef OSVR_ImageBufferElement BufferType;
template <typename T, typename ManagedMemory>
using ipc_deleter_type =
typename ManagedMemory::template deleter<T>::type;
typedef IPCRingBuffer::sequence_type sequence_type;
/// @brief Destroys the "unique_instance" of a given type in a managed
/// memory segment. If there isn't an instance, this is a no-op.
template <typename T, typename ManagedMemory>
inline void destroy_unique_instance(ManagedMemory &shm) {
auto result = shm.template find<T>(bip::unique_instance);
if (result.first) {
shm.template destroy<T>(bip::unique_instance);
}
}
} // namespace
namespace {
static size_t computeRequiredSpace(IPCRingBuffer::Options const &opts) {
size_t alignedEntrySize = opts.getEntrySize() + opts.getAlignment();
size_t dataSize = alignedEntrySize * (opts.getEntries() + 1);
// Give 33% overhead on the raw bookkeeping data
static const size_t BOOKKEEPING_SIZE =
(sizeof(detail::Bookkeeping) +
(sizeof(detail::ElementData) * opts.getEntries())) *
4 / 3;
return dataSize + BOOKKEEPING_SIZE;
}
class SharedMemorySegmentHolder {
public:
SharedMemorySegmentHolder() : m_bookkeeping(nullptr) {}
virtual ~SharedMemorySegmentHolder(){};
detail::Bookkeeping *getBookkeeping() { return m_bookkeeping; }
virtual uint64_t getSize() const = 0;
virtual uint64_t getFreeMemory() const = 0;
protected:
detail::Bookkeeping *m_bookkeeping;
};
template <typename ManagedMemory>
class SegmentHolderBase : public SharedMemorySegmentHolder {
public:
typedef ManagedMemory managed_memory_type;
virtual uint64_t getSize() const { return m_shm->get_size(); }
virtual uint64_t getFreeMemory() const {
return m_shm->get_free_memory();
}
protected:
unique_ptr<managed_memory_type> m_shm;
};
template <typename ManagedMemory>
class ServerSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ServerSharedMemorySegmentHolder(IPCRingBuffer::Options const &opts)
: m_name(opts.getName()) {
OSVR_SHM_VERBOSE("Creating segment, name "
<< opts.getName() << ", size "
<< computeRequiredSpace(opts));
try {
removeSharedMemory();
/// @todo Some shared memory types (specifically, Windows),
/// don't have a remove, so we should re-open.
Base::m_shm.reset(new ManagedMemory(
bip::create_only, opts.getName().c_str(),
computeRequiredSpace(opts)));
} catch (bip::interprocess_exception &e) {
OSVR_SHM_VERBOSE("Failed to create shared memory segment "
<< opts.getName()
<< " with exception: " << e.what());
return;
}
// detail::Bookkeeping::destroy(*Base::m_shm);
Base::m_bookkeeping =
detail::Bookkeeping::construct(*Base::m_shm, opts);
}
virtual ~ServerSharedMemorySegmentHolder() {
detail::Bookkeeping::destroy(*Base::m_shm);
removeSharedMemory();
}
void removeSharedMemory() {
ipc::device_type<ManagedMemory>::remove(m_name.c_str());
}
private:
std::string m_name;
};
template <typename ManagedMemory>
class ClientSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ClientSharedMemorySegmentHolder(
IPCRingBuffer::Options const &opts) {
OSVR_SHM_VERBOSE("Finding segment, name " << opts.getName());
try {
Base::m_shm.reset(new ManagedMemory(
bip::open_only, opts.getName().c_str()));
} catch (bip::interprocess_exception &e) {
OSVR_SHM_VERBOSE("Failed to open shared memory segment "
<< opts.getName()
<< " with exception: " << e.what());
return;
}
Base::m_bookkeeping = detail::Bookkeeping::find(*Base::m_shm);
}
virtual ~ClientSharedMemorySegmentHolder() {}
private:
};
/// @brief Factory function for constructing a memory segment holder.
template <typename ManagedMemory>
inline unique_ptr<SharedMemorySegmentHolder>
constructMemorySegment(IPCRingBuffer::Options const &opts,
bool doCreate) {
unique_ptr<SharedMemorySegmentHolder> ret;
if (doCreate) {
ret.reset(
new ServerSharedMemorySegmentHolder<ManagedMemory>(opts));
} else {
ret.reset(
new ClientSharedMemorySegmentHolder<ManagedMemory>(opts));
}
if (nullptr == ret->getBookkeeping()) {
ret.reset();
} else {
OSVR_SHM_VERBOSE("size: " << ret->getSize() << ", free: "
<< ret->getFreeMemory());
}
return ret;
}
} // namespace
IPCRingBuffer::BufferWriteProxy::BufferWriteProxy(
detail::IPCPutResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::BufferReadProxy::BufferReadProxy(
detail::IPCGetResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (nullptr != m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::smart_pointer_type
IPCRingBuffer::BufferReadProxy::getBufferSmartPointer() const {
return smart_pointer_type(m_data, m_buf);
}
IPCRingBuffer::Options::Options()
: m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name)
: m_name(ipc::make_name_safe(name)),
m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name,
BackendType backend)
: m_name(ipc::make_name_safe(name)), m_shmBackend(backend) {}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setName(std::string const &name) {
m_name = ipc::make_name_safe(name);
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setAlignment(alignment_type alignment) {
/// @todo ensure power of 2
m_alignment = alignment;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntries(entry_count_type entries) {
m_entries = entries;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntrySize(entry_size_type entrySize) {
m_entrySize = entrySize;
return *this;
}
class IPCRingBuffer::Impl {
public:
Impl(unique_ptr<SharedMemorySegmentHolder> &&segment,
Options const &opts)
: m_seg(std::move(segment)), m_bookkeeping(nullptr), m_opts(opts) {
m_bookkeeping = m_seg->getBookkeeping();
m_opts.setEntries(m_bookkeeping->getCapacity());
m_opts.setEntrySize(m_bookkeeping->getBufferLength());
}
detail::IPCPutResultPtr put() {
return m_bookkeeping->produceElement();
}
detail::IPCGetResultPtr get(sequence_type num) {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->getBySequenceNumber(num, boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{buf, std::move(readerLock),
num, nullptr});
}
return ret;
}
detail::IPCGetResultPtr getLatest() {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->back(boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{
buf, std::move(readerLock),
m_bookkeeping->backSequenceNumber(boundsLock), nullptr});
}
return ret;
}
Options const &getOpts() const { return m_opts; }
private:
unique_ptr<SharedMemorySegmentHolder> m_seg;
detail::Bookkeeping *m_bookkeeping;
Options m_opts;
};
IPCRingBufferPtr IPCRingBuffer::m_constructorHelper(Options const &opts,
bool doCreate) {
IPCRingBufferPtr ret;
unique_ptr<SharedMemorySegmentHolder> segment;
switch (opts.getBackend()) {
case ipc::BASIC_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::basic_managed_shm>(opts, doCreate);
break;
#ifdef OSVR_HAVE_WINDOWS_SHM
case ipc::WINDOWS_MANAGED_SHM_ID:
segment = constructMemorySegment<ipc::windows_managed_shm>(
opts, doCreate);
break;
#endif
#ifdef OSVR_HAVE_XSI_SHM
case ipc::SYSV_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::sysv_managed_shm>(opts, doCreate);
break;
#endif
default:
OSVR_SHM_VERBOSE("Unsupported/unrecognized shared memory backend: "
<< int(opts.getBackend()));
break;
}
if (!segment) {
return ret;
}
unique_ptr<Impl> impl(new Impl(std::move(segment), opts));
ret.reset(new IPCRingBuffer(std::move(impl)));
return ret;
}
IPCRingBuffer::abi_level_type IPCRingBuffer::getABILevel() {
return SHM_SOURCE_ABI_LEVEL;
}
IPCRingBufferPtr IPCRingBuffer::create(Options const &opts) {
return m_constructorHelper(opts, true);
}
IPCRingBufferPtr IPCRingBuffer::find(Options const &opts) {
return m_constructorHelper(opts, false);
}
IPCRingBuffer::IPCRingBuffer(unique_ptr<Impl> &&impl)
: m_impl(std::move(impl)) {}
IPCRingBuffer::~IPCRingBuffer() {}
IPCRingBuffer::BackendType IPCRingBuffer::getBackend() const {
return m_impl->getOpts().getBackend();
}
std::string const &IPCRingBuffer::getName() const {
return m_impl->getOpts().getName();
}
uint32_t IPCRingBuffer::getEntrySize() const {
return m_impl->getOpts().getEntrySize();
}
uint16_t IPCRingBuffer::getEntries() const {
return m_impl->getOpts().getEntries();
}
IPCRingBuffer::BufferWriteProxy IPCRingBuffer::put() {
return BufferWriteProxy(m_impl->put(), shared_from_this());
}
IPCRingBuffer::sequence_type IPCRingBuffer::put(pointer_to_const_type data,
size_t len) {
auto proxy = put();
std::memcpy(proxy.get(), data, len);
return proxy.getSequenceNumber();
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::get(sequence_type num) {
return BufferReadProxy(m_impl->get(num), shared_from_this());
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::getLatest() {
return BufferReadProxy(m_impl->getLatest(), shared_from_this());
}
} // namespace common
} // namespace osvr
<commit_msg>Support build with Boost 1.59.0<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/IPCRingBuffer.h>
#include "IPCRingBufferResults.h"
#include "IPCRingBufferSharedObjects.h"
#include "SharedMemory.h"
#include "SharedMemoryObjectWithMutex.h"
#include <osvr/Util/ImagingReportTypesC.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <boost/version.hpp>
// Standard includes
#include <stdexcept>
#include <utility>
#include <type_traits>
namespace osvr {
namespace common {
#define OSVR_SHM_VERBOSE(X) OSVR_DEV_VERBOSE("IPCRingBuffer: " << X)
/// @brief the ABI level: this must be bumped if the layout of any
/// shared-memory objects (Bookkeeping, ElementData) changes, if Boost
/// Interprocess changes affect the utilized ABI, or if other changes occur
/// that would interfere with communication.
static IPCRingBuffer::abi_level_type SHM_SOURCE_ABI_LEVEL = 0;
/// Some tests that can be automated for ensuring validity of the ABI level
/// number.
#if (BOOST_VERSION > 105900)
#error \
"Using an untested Boost version - inspect the Boost Interprocess release notes/changelog to see if any ABI breaks affect us."
#endif
#ifdef _WIN32
#if (BOOST_VERSION < 105400)
#error \
"Boost Interprocess pre-1.54 on Win32 is ABI-incompatible with newer Boost due to changed bootstamp function."
#endif
#else // !_WIN32
// No obvious ABI breaks through 1.58 seem to apply to us on non-Windows
// platforms
#endif
static_assert(std::is_same<IPCRingBuffer::BackendType,
ipc::SharedMemoryBackendType>::value,
"The typedefs IPCRingBuffer::BackendType and "
"ipc::SharedMemoryBackendType must remain in sync!");
static_assert(
std::is_same<IPCRingBuffer::value_type, OSVR_ImageBufferElement>::value,
"The ring buffer's individual byte type must match the image buffer "
"element type.");
namespace bip = boost::interprocess;
namespace {
typedef OSVR_ImageBufferElement BufferType;
template <typename T, typename ManagedMemory>
using ipc_deleter_type =
typename ManagedMemory::template deleter<T>::type;
typedef IPCRingBuffer::sequence_type sequence_type;
/// @brief Destroys the "unique_instance" of a given type in a managed
/// memory segment. If there isn't an instance, this is a no-op.
template <typename T, typename ManagedMemory>
inline void destroy_unique_instance(ManagedMemory &shm) {
auto result = shm.template find<T>(bip::unique_instance);
if (result.first) {
shm.template destroy<T>(bip::unique_instance);
}
}
} // namespace
namespace {
static size_t computeRequiredSpace(IPCRingBuffer::Options const &opts) {
size_t alignedEntrySize = opts.getEntrySize() + opts.getAlignment();
size_t dataSize = alignedEntrySize * (opts.getEntries() + 1);
// Give 33% overhead on the raw bookkeeping data
static const size_t BOOKKEEPING_SIZE =
(sizeof(detail::Bookkeeping) +
(sizeof(detail::ElementData) * opts.getEntries())) *
4 / 3;
return dataSize + BOOKKEEPING_SIZE;
}
class SharedMemorySegmentHolder {
public:
SharedMemorySegmentHolder() : m_bookkeeping(nullptr) {}
virtual ~SharedMemorySegmentHolder(){};
detail::Bookkeeping *getBookkeeping() { return m_bookkeeping; }
virtual uint64_t getSize() const = 0;
virtual uint64_t getFreeMemory() const = 0;
protected:
detail::Bookkeeping *m_bookkeeping;
};
template <typename ManagedMemory>
class SegmentHolderBase : public SharedMemorySegmentHolder {
public:
typedef ManagedMemory managed_memory_type;
virtual uint64_t getSize() const { return m_shm->get_size(); }
virtual uint64_t getFreeMemory() const {
return m_shm->get_free_memory();
}
protected:
unique_ptr<managed_memory_type> m_shm;
};
template <typename ManagedMemory>
class ServerSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ServerSharedMemorySegmentHolder(IPCRingBuffer::Options const &opts)
: m_name(opts.getName()) {
OSVR_SHM_VERBOSE("Creating segment, name "
<< opts.getName() << ", size "
<< computeRequiredSpace(opts));
try {
removeSharedMemory();
/// @todo Some shared memory types (specifically, Windows),
/// don't have a remove, so we should re-open.
Base::m_shm.reset(new ManagedMemory(
bip::create_only, opts.getName().c_str(),
computeRequiredSpace(opts)));
} catch (bip::interprocess_exception &e) {
OSVR_SHM_VERBOSE("Failed to create shared memory segment "
<< opts.getName()
<< " with exception: " << e.what());
return;
}
// detail::Bookkeeping::destroy(*Base::m_shm);
Base::m_bookkeeping =
detail::Bookkeeping::construct(*Base::m_shm, opts);
}
virtual ~ServerSharedMemorySegmentHolder() {
detail::Bookkeeping::destroy(*Base::m_shm);
removeSharedMemory();
}
void removeSharedMemory() {
ipc::device_type<ManagedMemory>::remove(m_name.c_str());
}
private:
std::string m_name;
};
template <typename ManagedMemory>
class ClientSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ClientSharedMemorySegmentHolder(
IPCRingBuffer::Options const &opts) {
OSVR_SHM_VERBOSE("Finding segment, name " << opts.getName());
try {
Base::m_shm.reset(new ManagedMemory(
bip::open_only, opts.getName().c_str()));
} catch (bip::interprocess_exception &e) {
OSVR_SHM_VERBOSE("Failed to open shared memory segment "
<< opts.getName()
<< " with exception: " << e.what());
return;
}
Base::m_bookkeeping = detail::Bookkeeping::find(*Base::m_shm);
}
virtual ~ClientSharedMemorySegmentHolder() {}
private:
};
/// @brief Factory function for constructing a memory segment holder.
template <typename ManagedMemory>
inline unique_ptr<SharedMemorySegmentHolder>
constructMemorySegment(IPCRingBuffer::Options const &opts,
bool doCreate) {
unique_ptr<SharedMemorySegmentHolder> ret;
if (doCreate) {
ret.reset(
new ServerSharedMemorySegmentHolder<ManagedMemory>(opts));
} else {
ret.reset(
new ClientSharedMemorySegmentHolder<ManagedMemory>(opts));
}
if (nullptr == ret->getBookkeeping()) {
ret.reset();
} else {
OSVR_SHM_VERBOSE("size: " << ret->getSize() << ", free: "
<< ret->getFreeMemory());
}
return ret;
}
} // namespace
IPCRingBuffer::BufferWriteProxy::BufferWriteProxy(
detail::IPCPutResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::BufferReadProxy::BufferReadProxy(
detail::IPCGetResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (nullptr != m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::smart_pointer_type
IPCRingBuffer::BufferReadProxy::getBufferSmartPointer() const {
return smart_pointer_type(m_data, m_buf);
}
IPCRingBuffer::Options::Options()
: m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name)
: m_name(ipc::make_name_safe(name)),
m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name,
BackendType backend)
: m_name(ipc::make_name_safe(name)), m_shmBackend(backend) {}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setName(std::string const &name) {
m_name = ipc::make_name_safe(name);
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setAlignment(alignment_type alignment) {
/// @todo ensure power of 2
m_alignment = alignment;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntries(entry_count_type entries) {
m_entries = entries;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntrySize(entry_size_type entrySize) {
m_entrySize = entrySize;
return *this;
}
class IPCRingBuffer::Impl {
public:
Impl(unique_ptr<SharedMemorySegmentHolder> &&segment,
Options const &opts)
: m_seg(std::move(segment)), m_bookkeeping(nullptr), m_opts(opts) {
m_bookkeeping = m_seg->getBookkeeping();
m_opts.setEntries(m_bookkeeping->getCapacity());
m_opts.setEntrySize(m_bookkeeping->getBufferLength());
}
detail::IPCPutResultPtr put() {
return m_bookkeeping->produceElement();
}
detail::IPCGetResultPtr get(sequence_type num) {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->getBySequenceNumber(num, boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{buf, std::move(readerLock),
num, nullptr});
}
return ret;
}
detail::IPCGetResultPtr getLatest() {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->back(boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{
buf, std::move(readerLock),
m_bookkeeping->backSequenceNumber(boundsLock), nullptr});
}
return ret;
}
Options const &getOpts() const { return m_opts; }
private:
unique_ptr<SharedMemorySegmentHolder> m_seg;
detail::Bookkeeping *m_bookkeeping;
Options m_opts;
};
IPCRingBufferPtr IPCRingBuffer::m_constructorHelper(Options const &opts,
bool doCreate) {
IPCRingBufferPtr ret;
unique_ptr<SharedMemorySegmentHolder> segment;
switch (opts.getBackend()) {
case ipc::BASIC_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::basic_managed_shm>(opts, doCreate);
break;
#ifdef OSVR_HAVE_WINDOWS_SHM
case ipc::WINDOWS_MANAGED_SHM_ID:
segment = constructMemorySegment<ipc::windows_managed_shm>(
opts, doCreate);
break;
#endif
#ifdef OSVR_HAVE_XSI_SHM
case ipc::SYSV_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::sysv_managed_shm>(opts, doCreate);
break;
#endif
default:
OSVR_SHM_VERBOSE("Unsupported/unrecognized shared memory backend: "
<< int(opts.getBackend()));
break;
}
if (!segment) {
return ret;
}
unique_ptr<Impl> impl(new Impl(std::move(segment), opts));
ret.reset(new IPCRingBuffer(std::move(impl)));
return ret;
}
IPCRingBuffer::abi_level_type IPCRingBuffer::getABILevel() {
return SHM_SOURCE_ABI_LEVEL;
}
IPCRingBufferPtr IPCRingBuffer::create(Options const &opts) {
return m_constructorHelper(opts, true);
}
IPCRingBufferPtr IPCRingBuffer::find(Options const &opts) {
return m_constructorHelper(opts, false);
}
IPCRingBuffer::IPCRingBuffer(unique_ptr<Impl> &&impl)
: m_impl(std::move(impl)) {}
IPCRingBuffer::~IPCRingBuffer() {}
IPCRingBuffer::BackendType IPCRingBuffer::getBackend() const {
return m_impl->getOpts().getBackend();
}
std::string const &IPCRingBuffer::getName() const {
return m_impl->getOpts().getName();
}
uint32_t IPCRingBuffer::getEntrySize() const {
return m_impl->getOpts().getEntrySize();
}
uint16_t IPCRingBuffer::getEntries() const {
return m_impl->getOpts().getEntries();
}
IPCRingBuffer::BufferWriteProxy IPCRingBuffer::put() {
return BufferWriteProxy(m_impl->put(), shared_from_this());
}
IPCRingBuffer::sequence_type IPCRingBuffer::put(pointer_to_const_type data,
size_t len) {
auto proxy = put();
std::memcpy(proxy.get(), data, len);
return proxy.getSequenceNumber();
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::get(sequence_type num) {
return BufferReadProxy(m_impl->get(num), shared_from_this());
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::getLatest() {
return BufferReadProxy(m_impl->getLatest(), shared_from_this());
}
} // namespace common
} // namespace osvr
<|endoftext|> |
<commit_before><commit_msg>Delete glibc_compat.cpp<commit_after><|endoftext|> |
<commit_before>#include "unit_tests.h"
#include "crc_t.h"
//------------- tests for CRC_t methods -------------
int test_crc_t_name(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc;
if( crc.name != "CRC-32" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
CRC_t crc(name);
if( crc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 123, 0, true, true, 0);
if( crc.get_poly() != 123 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_init(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 1234, true, true, 0);
if( crc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 1000);
if( crc.get_xor_out() != 1000 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_in(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_in() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_out() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_set_bits(struct test_info_t *test_info)
{
TEST_INIT;
int i, res;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
if( crc.set_bits(0) != -1 )
return TEST_BROKEN;
// 1..64
for( i = 1; i <= 64; ++i)
{
res = crc.set_bits(i);
if( res != 0 )
return TEST_BROKEN;
if( crc.get_bits() != i )
return TEST_BROKEN;
}
//more 64
for( i = 65; i <= 256; ++i)
{
if( crc.set_bits(i) != -1 )
return TEST_BROKEN;
}
return TEST_PASSED;
}
//------------- tests for Calculate CRC -------------
//width=3 poly=0x3 init=0x7 refin=true refout=true xorout=0x0 check=0x6 name="CRC-3/ROHC"
int test_crc3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(3, 0x3, 0x7, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x6 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xE )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=4 poly=0x3 init=0x0 refin=true refout=true xorout=0x0 check=0x7 name="CRC-4/ITU"
int test_crc4_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x09 init=0x09 refin=false refout=false xorout=0x00 check=0x00 name="CRC-5/EPC"
int test_crc5(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x09, 0x09, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x15 init=0x00 refin=true refout=true xorout=0x00 check=0x07 name="CRC-5/ITU"
int test_crc5_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x15, 0x00, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x07 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x05 init=0x1f refin=true refout=true xorout=0x1f check=0x19 name="CRC-5/USB"
int test_crc5_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x05, 0x1f, true, true, 0x1f);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x19 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x27 init=0x3f refin=false refout=false xorout=0x00 check=0x0d name="CRC-6/CDMA2000-A"
int test_crc6(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x27, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0d )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x07 init=0x3f refin=false refout=false xorout=0x00 check=0x3b name="CRC-6/CDMA2000-B"
int test_crc6_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x07, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x3b )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x19 init=0x00 refin=true refout=true xorout=0x00 check=0x26 name="CRC-6/DARC"
int test_crc6_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x19, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x26 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x03 init=0x00 refin=true refout=true xorout=0x00 check=0x06 name="CRC-6/ITU"
int test_crc6_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x03, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x06 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x09 init=0x00 refin=false refout=false xorout=0x00 check=0x75 name="CRC-7"
int test_crc7(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x09, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x75 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x4f init=0x7f refin=true refout=true xorout=0x00 check=0x53 name="CRC-7/ROHC"
int test_crc7_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x4f, 0x7f, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x53 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc8(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x31, 0xFF, false, false, 0x00);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x07 init=0x00 refin=false refout=false xorout=0x00 check=0xf4 name="CRC-8"
int test_crc8_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x07, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF4 )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_t methods
test_crc_t_name,
test_crc_t_name_2,
test_crc_t_get_bits,
test_crc_t_get_poly,
test_crc_t_get_init,
test_crc_t_get_xor_out,
test_crc_t_get_ref_in,
test_crc_t_get_ref_out,
test_crc_t_set_bits,
//CRC
test_crc3,
test_crc4,
test_crc4_2,
test_crc5,
test_crc5_2,
test_crc5_3,
test_crc6,
test_crc6_2,
test_crc6_3,
test_crc6_4,
test_crc7,
test_crc7_2,
test_crc8,
test_crc8_2,
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
<commit_msg>add test to calculate the CRC-8/CDMA2000<commit_after>#include "unit_tests.h"
#include "crc_t.h"
//------------- tests for CRC_t methods -------------
int test_crc_t_name(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc;
if( crc.name != "CRC-32" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
CRC_t crc(name);
if( crc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 123, 0, true, true, 0);
if( crc.get_poly() != 123 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_init(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 1234, true, true, 0);
if( crc.get_init() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_xor_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 1000);
if( crc.get_xor_out() != 1000 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_in(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_in() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_get_ref_out(struct test_info_t *test_info)
{
TEST_INIT;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_ref_out() != true )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_t_set_bits(struct test_info_t *test_info)
{
TEST_INIT;
int i, res;
CRC_t crc(1, 0, 0, true, true, 0);
if( crc.get_bits() != 1 )
return TEST_BROKEN;
if( crc.set_bits(0) != -1 )
return TEST_BROKEN;
// 1..64
for( i = 1; i <= 64; ++i)
{
res = crc.set_bits(i);
if( res != 0 )
return TEST_BROKEN;
if( crc.get_bits() != i )
return TEST_BROKEN;
}
//more 64
for( i = 65; i <= 256; ++i)
{
if( crc.set_bits(i) != -1 )
return TEST_BROKEN;
}
return TEST_PASSED;
}
//------------- tests for Calculate CRC -------------
//width=3 poly=0x3 init=0x7 refin=true refout=true xorout=0x0 check=0x6 name="CRC-3/ROHC"
int test_crc3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(3, 0x3, 0x7, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x6 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xE )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=4 poly=0x3 init=0x0 refin=true refout=true xorout=0x0 check=0x7 name="CRC-4/ITU"
int test_crc4_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(4, 0x3, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x09 init=0x09 refin=false refout=false xorout=0x00 check=0x00 name="CRC-5/EPC"
int test_crc5(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x09, 0x09, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x15 init=0x00 refin=true refout=true xorout=0x00 check=0x07 name="CRC-5/ITU"
int test_crc5_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x15, 0x00, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x07 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=5 poly=0x05 init=0x1f refin=true refout=true xorout=0x1f check=0x19 name="CRC-5/USB"
int test_crc5_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(5, 0x05, 0x1f, true, true, 0x1f);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x19 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x27 init=0x3f refin=false refout=false xorout=0x00 check=0x0d name="CRC-6/CDMA2000-A"
int test_crc6(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x27, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x0d )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x07 init=0x3f refin=false refout=false xorout=0x00 check=0x3b name="CRC-6/CDMA2000-B"
int test_crc6_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x07, 0x3f, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x3b )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x19 init=0x00 refin=true refout=true xorout=0x00 check=0x26 name="CRC-6/DARC"
int test_crc6_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x19, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x26 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=6 poly=0x03 init=0x00 refin=true refout=true xorout=0x00 check=0x06 name="CRC-6/ITU"
int test_crc6_4(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(6, 0x03, 0x0, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x06 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x09 init=0x00 refin=false refout=false xorout=0x00 check=0x75 name="CRC-7"
int test_crc7(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x09, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x75 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=7 poly=0x4f init=0x7f refin=true refout=true xorout=0x00 check=0x53 name="CRC-7/ROHC"
int test_crc7_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(7, 0x4f, 0x7f, true, true, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0x53 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc8(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x31, 0xFF, false, false, 0x00);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF7 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x07 init=0x00 refin=false refout=false xorout=0x00 check=0xf4 name="CRC-8"
int test_crc8_2(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x07, 0x0, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xF4 )
return TEST_BROKEN;
return TEST_PASSED;
}
//width=8 poly=0x9b init=0xff refin=false refout=false xorout=0x00 check=0xda name="CRC-8/CDMA2000"
int test_crc8_3(struct test_info_t *test_info)
{
TEST_INIT;
uint8_t crc;
CRC_t ucrc(8, 0x9b, 0xff, false, false, 0x0);
crc = ucrc.get_crc("123456789", 9);
if( crc != 0xDA )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_t methods
test_crc_t_name,
test_crc_t_name_2,
test_crc_t_get_bits,
test_crc_t_get_poly,
test_crc_t_get_init,
test_crc_t_get_xor_out,
test_crc_t_get_ref_in,
test_crc_t_get_ref_out,
test_crc_t_set_bits,
//CRC
test_crc3,
test_crc4,
test_crc4_2,
test_crc5,
test_crc5_2,
test_crc5_3,
test_crc6,
test_crc6_2,
test_crc6_3,
test_crc6_4,
test_crc7,
test_crc7_2,
test_crc8,
test_crc8_2,
test_crc8_3,
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mlistindexfloatingview.h"
#include "mlistindexfloatingview_p.h"
#include "mlistview_p.h"
#include <mlistindex.h>
#include <MApplicationPage>
#include <MCancelEvent>
#include <MPannableViewport>
#include <MSeparator>
#include "mlistindextooltip.h"
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneMouseEvent>
#include <QTapAndHoldGesture>
MListIndexFloatingViewPrivate::MListIndexFloatingViewPrivate()
: MWidgetViewPrivate(),
controller(NULL),
container(NULL),
tooltipWidget(NULL),
tooltipVerticalOffset(0.0)
{
}
MListIndexFloatingViewPrivate::~MListIndexFloatingViewPrivate()
{
}
void MListIndexFloatingViewPrivate::initLayout()
{
attachToContainer();
configureController();
}
void MListIndexFloatingViewPrivate::configureController()
{
controller->show();
controller->setOpacity(1.0);
}
void MListIndexFloatingViewPrivate::updateLayout()
{
Q_Q(MListIndexFloatingView);
if(container) {
controller->resize(controller->preferredWidth(), containerRect.height() - q->model()->offset().y());
controller->setPos(containerRect.x() + containerRect.width() - controller->preferredWidth(), containerRect.y() + q->model()->offset().y());
}
}
void MListIndexFloatingViewPrivate::attachToContainer()
{
Q_Q(MListIndexFloatingView);
if (container)
container->disconnect(container, SIGNAL(exposedContentRectChanged()), q, SLOT(_q_exposedContentRectChanged()));
if (q->model()->list()) {
container = MListViewPrivateNamespace::findParentWidgetOfType<MApplicationPage>(q->model()->list());
if (container) {
controller->setParentItem(container);
container->connect(container, SIGNAL(exposedContentRectChanged()), q, SLOT(_q_recalculateListIndexRegion()));
_q_recalculateListIndexRegion();
}
}
}
MListIndexTooltip *MListIndexFloatingViewPrivate::tooltip()
{
Q_Q(MListIndexFloatingView);
if (!tooltipWidget) {
tooltipWidget = new MListIndexTooltip(controller);
tooltipWidget->setIndexCount(q->style()->floatingIndexCount());
// should be hidden by default;
tooltipWidget->hide();
q->connect(tooltipWidget, SIGNAL(geometryChanged()), q, SLOT(_q_recalculateTooltipOffsets()));
_q_recalculateTooltipOffsets();
}
return tooltipWidget;
}
void MListIndexFloatingViewPrivate::updateTooltipPosition(const QPointF &pos)
{
Q_Q(MListIndexFloatingView);
if (tooltip()) {
qreal top = 0;
qreal tooltipHeight = tooltip()->size().height();
if (pos.y() > tooltipHeight / 2 && pos.y() < tooltipVerticalOffset)
top = pos.y() - tooltipHeight / 2;
else if (pos.y() >= tooltipVerticalOffset)
top = controller->size().height() - tooltipHeight;
tooltip()->setPos(-tooltip()->size().width() - q->style()->floatingIndexOffset(), top);
}
}
void MListIndexFloatingViewPrivate::updateTooltipData()
{
Q_Q(MListIndexFloatingView);
int shortcutCount = q->model()->shortcutIndexes().count();
int shortcutIndex = q->model()->shortcutIndexes().indexOf(currentScrollToIndex);
int floatingIndexCount = qMin(q->style()->floatingIndexCount(), shortcutCount);
int startIndex = qMax(shortcutIndex - floatingIndexCount + 2, 0);
int endIndex = qMin(startIndex + floatingIndexCount - 1, shortcutCount - 1);
startIndex = qMin(startIndex, shortcutCount - floatingIndexCount);
for (int i = startIndex; i <= endIndex; i++) {
tooltip()->setIndexText(i - startIndex, q->model()->shortcutLabels().at(i));
}
tooltip()->setIndexSelected(shortcutIndex - startIndex);
}
void MListIndexFloatingViewPrivate::scrollToGroupHeader(int y)
{
Q_Q(MListIndexFloatingView);
qreal offset = (qreal)y / controller->size().height();
int shortcutCount = q->model()->shortcutIndexes().count();
int shortcutIndex = shortcutCount * offset;
if (shortcutIndex < shortcutCount && shortcutIndex >= 0) {
QModelIndex scrollToIndex = q->model()->shortcutIndexes().at(shortcutIndex);
if (scrollToIndex.isValid()) {
if (scrollToIndex != currentScrollToIndex) {
int snapDirection = -1;
if (q->model()->shortcutIndexes().indexOf(currentScrollToIndex) < shortcutIndex)
snapDirection = 1;
currentScrollToIndex = scrollToIndex;
q->model()->list()->scrollTo(scrollToIndex, MList::PositionAtTopHint);
updateTooltipData();
tooltip()->snap(q->style()->floatingSnapDistance() * snapDirection);
}
}
}
}
void MListIndexFloatingViewPrivate::_q_recalculateListIndexRegion()
{
containerRect = container->exposedContentRect();
updateLayout();
}
void MListIndexFloatingViewPrivate::_q_listParentChanged()
{
initLayout();
}
void MListIndexFloatingViewPrivate::_q_recalculateTooltipOffsets()
{
tooltipVerticalOffset = controller->size().height() - tooltip()->size().height() / 2;
}
MListIndexFloatingView::MListIndexFloatingView(MListIndex *controller)
: MWidgetView(*(new MListIndexFloatingViewPrivate), controller)
{
Q_D(MListIndexFloatingView);
d->controller = controller;
}
MListIndexFloatingView::~MListIndexFloatingView()
{
}
void MListIndexFloatingView::setupModel()
{
MWidgetView::setupModel();
QList<const char*> modifications;
modifications << MListIndexModel::List;
modifications << MListIndexModel::ShortcutLabels;
modifications << MListIndexModel::ShortcutIndexes;
updateData(modifications);
}
void MListIndexFloatingView::updateData(const QList<const char *> &modifications)
{
Q_D(MListIndexFloatingView);
MWidgetView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MListIndexModel::List) {
if (model()->list())
d->initLayout();
} else if (member == MListIndexModel::ShortcutIndexes) {
d->tooltip()->setIndexCount(qMin(style()->floatingIndexCount(), model()->shortcutIndexes().count()));
}
}
}
void MListIndexFloatingView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(painter);
Q_UNUSED(option);
}
void MListIndexFloatingView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
MWidgetView::mousePressEvent(event);
d->scrollToGroupHeader(event->pos().y());
d->updateTooltipPosition(event->pos());
event->accept();
d->tooltip()->show();
}
void MListIndexFloatingView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
if (model()->shortcutIndexes().isEmpty()) {
event->ignore();
return;
}
MWidgetView::mousePressEvent(event);
d->scrollToGroupHeader(event->pos().y());
d->updateTooltipPosition(event->pos());
event->accept();
d->tooltip()->show();
}
void MListIndexFloatingView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
MWidgetView::mouseReleaseEvent(event);
event->accept();
d->tooltip()->hide();
}
void MListIndexFloatingView::cancelEvent(MCancelEvent *event)
{
Q_D(MListIndexFloatingView);
MWidgetView::cancelEvent(event);
event->accept();
d->tooltip()->hide();
}
void MListIndexFloatingView::tapAndHoldGestureEvent(QGestureEvent *event, QTapAndHoldGesture *gesture)
{
event->accept(gesture);
}
void MListIndexFloatingView::panGestureEvent(QGestureEvent *event, QPanGesture *gesture)
{
event->accept(gesture);
}
#include "moc_mlistindexfloatingview.cpp"
M_REGISTER_VIEW_NEW(MListIndexFloatingView, MListIndex)
<commit_msg>Fixes: NB#209140 - Unnecessary floating label displayed when taping in fast scroll area<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mlistindexfloatingview.h"
#include "mlistindexfloatingview_p.h"
#include "mlistview_p.h"
#include <mlistindex.h>
#include <MApplicationPage>
#include <MCancelEvent>
#include <MPannableViewport>
#include <MSeparator>
#include "mlistindextooltip.h"
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneMouseEvent>
#include <QTapAndHoldGesture>
MListIndexFloatingViewPrivate::MListIndexFloatingViewPrivate()
: MWidgetViewPrivate(),
controller(NULL),
container(NULL),
tooltipWidget(NULL),
tooltipVerticalOffset(0.0)
{
}
MListIndexFloatingViewPrivate::~MListIndexFloatingViewPrivate()
{
}
void MListIndexFloatingViewPrivate::initLayout()
{
attachToContainer();
configureController();
}
void MListIndexFloatingViewPrivate::configureController()
{
controller->show();
controller->setOpacity(1.0);
}
void MListIndexFloatingViewPrivate::updateLayout()
{
Q_Q(MListIndexFloatingView);
if(container) {
controller->resize(controller->preferredWidth(), containerRect.height() - q->model()->offset().y());
controller->setPos(containerRect.x() + containerRect.width() - controller->preferredWidth(), containerRect.y() + q->model()->offset().y());
}
}
void MListIndexFloatingViewPrivate::attachToContainer()
{
Q_Q(MListIndexFloatingView);
if (container)
container->disconnect(container, SIGNAL(exposedContentRectChanged()), q, SLOT(_q_exposedContentRectChanged()));
if (q->model()->list()) {
container = MListViewPrivateNamespace::findParentWidgetOfType<MApplicationPage>(q->model()->list());
if (container) {
controller->setParentItem(container);
container->connect(container, SIGNAL(exposedContentRectChanged()), q, SLOT(_q_recalculateListIndexRegion()));
_q_recalculateListIndexRegion();
}
}
}
MListIndexTooltip *MListIndexFloatingViewPrivate::tooltip()
{
Q_Q(MListIndexFloatingView);
if (!tooltipWidget) {
tooltipWidget = new MListIndexTooltip(controller);
tooltipWidget->setIndexCount(q->style()->floatingIndexCount());
// should be hidden by default;
tooltipWidget->hide();
q->connect(tooltipWidget, SIGNAL(geometryChanged()), q, SLOT(_q_recalculateTooltipOffsets()));
_q_recalculateTooltipOffsets();
}
return tooltipWidget;
}
void MListIndexFloatingViewPrivate::updateTooltipPosition(const QPointF &pos)
{
Q_Q(MListIndexFloatingView);
if (tooltip()) {
qreal top = 0;
qreal tooltipHeight = tooltip()->size().height();
if (pos.y() > tooltipHeight / 2 && pos.y() < tooltipVerticalOffset)
top = pos.y() - tooltipHeight / 2;
else if (pos.y() >= tooltipVerticalOffset)
top = controller->size().height() - tooltipHeight;
tooltip()->setPos(-tooltip()->size().width() - q->style()->floatingIndexOffset(), top);
}
}
void MListIndexFloatingViewPrivate::updateTooltipData()
{
Q_Q(MListIndexFloatingView);
int shortcutCount = q->model()->shortcutIndexes().count();
int shortcutIndex = q->model()->shortcutIndexes().indexOf(currentScrollToIndex);
int floatingIndexCount = qMin(q->style()->floatingIndexCount(), shortcutCount);
int startIndex = qMax(shortcutIndex - floatingIndexCount + 2, 0);
int endIndex = qMin(startIndex + floatingIndexCount - 1, shortcutCount - 1);
startIndex = qMin(startIndex, shortcutCount - floatingIndexCount);
for (int i = startIndex; i <= endIndex; i++) {
tooltip()->setIndexText(i - startIndex, q->model()->shortcutLabels().at(i));
}
tooltip()->setIndexSelected(shortcutIndex - startIndex);
}
void MListIndexFloatingViewPrivate::scrollToGroupHeader(int y)
{
Q_Q(MListIndexFloatingView);
qreal offset = (qreal)y / controller->size().height();
int shortcutCount = q->model()->shortcutIndexes().count();
int shortcutIndex = shortcutCount * offset;
if (shortcutIndex < shortcutCount && shortcutIndex >= 0) {
QModelIndex scrollToIndex = q->model()->shortcutIndexes().at(shortcutIndex);
if (scrollToIndex.isValid()) {
if (scrollToIndex != currentScrollToIndex) {
int snapDirection = -1;
if (q->model()->shortcutIndexes().indexOf(currentScrollToIndex) < shortcutIndex)
snapDirection = 1;
currentScrollToIndex = scrollToIndex;
q->model()->list()->scrollTo(scrollToIndex, MList::PositionAtTopHint);
updateTooltipData();
tooltip()->snap(q->style()->floatingSnapDistance() * snapDirection);
}
}
}
}
void MListIndexFloatingViewPrivate::_q_recalculateListIndexRegion()
{
containerRect = container->exposedContentRect();
updateLayout();
}
void MListIndexFloatingViewPrivate::_q_listParentChanged()
{
initLayout();
}
void MListIndexFloatingViewPrivate::_q_recalculateTooltipOffsets()
{
tooltipVerticalOffset = controller->size().height() - tooltip()->size().height() / 2;
}
MListIndexFloatingView::MListIndexFloatingView(MListIndex *controller)
: MWidgetView(*(new MListIndexFloatingViewPrivate), controller)
{
Q_D(MListIndexFloatingView);
d->controller = controller;
}
MListIndexFloatingView::~MListIndexFloatingView()
{
}
void MListIndexFloatingView::setupModel()
{
MWidgetView::setupModel();
QList<const char*> modifications;
modifications << MListIndexModel::List;
modifications << MListIndexModel::ShortcutLabels;
modifications << MListIndexModel::ShortcutIndexes;
updateData(modifications);
}
void MListIndexFloatingView::updateData(const QList<const char *> &modifications)
{
Q_D(MListIndexFloatingView);
MWidgetView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MListIndexModel::List) {
if (model()->list())
d->initLayout();
} else if (member == MListIndexModel::ShortcutIndexes) {
d->tooltip()->setIndexCount(qMin(style()->floatingIndexCount(), model()->shortcutIndexes().count()));
}
}
}
void MListIndexFloatingView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(painter);
Q_UNUSED(option);
}
void MListIndexFloatingView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
if (model()->shortcutIndexes().isEmpty()) {
event->ignore();
return;
}
MWidgetView::mousePressEvent(event);
d->scrollToGroupHeader(event->pos().y());
d->updateTooltipPosition(event->pos());
event->accept();
d->tooltip()->show();
}
void MListIndexFloatingView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
if (model()->shortcutIndexes().isEmpty()) {
event->ignore();
return;
}
MWidgetView::mousePressEvent(event);
d->scrollToGroupHeader(event->pos().y());
d->updateTooltipPosition(event->pos());
event->accept();
d->tooltip()->show();
}
void MListIndexFloatingView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(MListIndexFloatingView);
MWidgetView::mouseReleaseEvent(event);
event->accept();
d->tooltip()->hide();
}
void MListIndexFloatingView::cancelEvent(MCancelEvent *event)
{
Q_D(MListIndexFloatingView);
MWidgetView::cancelEvent(event);
event->accept();
d->tooltip()->hide();
}
void MListIndexFloatingView::tapAndHoldGestureEvent(QGestureEvent *event, QTapAndHoldGesture *gesture)
{
event->accept(gesture);
}
void MListIndexFloatingView::panGestureEvent(QGestureEvent *event, QPanGesture *gesture)
{
event->accept(gesture);
}
#include "moc_mlistindexfloatingview.cpp"
M_REGISTER_VIEW_NEW(MListIndexFloatingView, MListIndex)
<|endoftext|> |
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_XCODE_PROJECT_HPP
#define OUZEL_XCODE_PROJECT_HPP
#include <fstream>
#include "OuzelProject.hpp"
#include "PBXBuildFile.hpp"
#include "PBXContainerItemProxy.hpp"
#include "PBXFileReference.hpp"
#include "PBXFrameworksBuildPhase.hpp"
#include "PBXGroup.hpp"
#include "PBXNativeTarget.hpp"
#include "PBXProject.hpp"
#include "PBXReferenceProxy.hpp"
#include "PBXResourcesBuildPhase.hpp"
#include "PBXShellScriptBuildPhase.hpp"
#include "PBXSourcesBuildPhase.hpp"
#include "PBXTargetDependency.hpp"
#include "XCBuildConfiguration.hpp"
#include "XCConfigurationList.hpp"
#include "storage/FileSystem.hpp"
#include "utils/Plist.hpp"
namespace ouzel
{
namespace xcode
{
class Project final
{
public:
Project(const OuzelProject& p):
project(p)
{
}
void generate()
{
const storage::Path projectFilename = project.getPath().getFilename();
const storage::Path projectDirectory = project.getPath().getDirectory();
auto xcodeProjectDirectory = projectDirectory / storage::Path{project.getName() + ".xcodeproj"};
auto xcodeProjectDirectoryType = xcodeProjectDirectory.getType();
if (xcodeProjectDirectoryType == storage::Path::Type::NotFound)
storage::FileSystem::createDirectory(xcodeProjectDirectory);
else if (xcodeProjectDirectoryType != storage::Path::Type::Directory)
{
storage::FileSystem::deleteFile(xcodeProjectDirectory);
storage::FileSystem::createDirectory(xcodeProjectDirectory);
}
auto pbxProjectFile = xcodeProjectDirectory / storage::Path{"project.pbxproj"};
constexpr auto libouzelIosId = Id{0x30, 0x3B, 0x75, 0x33, 0x1C, 0x2A, 0x3C, 0x58, 0x00, 0xFE, 0xDE, 0x92};
constexpr auto libouzelMacOsId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
constexpr auto libouzelTvosId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
constexpr auto ouzelId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
const auto ouzelProjectPath = project.getOuzelPath() / "build" / "ouzel.xcodeproj";
const auto& ouzelProjectFileRef = create<PBXFileReference>("ouzel.xcodeproj", ouzelProjectPath,
PBXFileType::WrapperPBProject,
PBXSourceTree::Group);
const auto& libouzelIosProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelIosId, "libouzel_ios");
const auto& libouzelIosReferenceProxy = create<PBXReferenceProxy>("", "libouzel_ios.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelIosProxy);
const auto& libouzelMacOsProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelMacOsId, "libouzel_macos");
const auto& libouzelMacOsReferenceProxy = create<PBXReferenceProxy>("", "libouzel_macos.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelMacOsProxy);
const auto& libouzelTvosProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelTvosId, "libouzel_tvos");
const auto& libouzelTvosReferenceProxy = create<PBXReferenceProxy>("", "libouzel_tvos.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelTvosProxy);
const auto& ouzelProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
ouzelId, "ouzel");
const auto& ouzelNativeTargetProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::NativeTarget,
ouzelId, "ouzel");
const auto& ouzelReferenceProxy = create<PBXReferenceProxy>("", "ouzel",
PBXFileType::CompiledMachOExecutable,
PBXSourceTree::BuildProductsDir,
ouzelProxy);
const auto& ouzelPoductRefGroup = create<PBXGroup>("Products", storage::Path{},
std::vector<PBXFileElementRef>{
libouzelIosReferenceProxy,
libouzelMacOsReferenceProxy,
libouzelTvosReferenceProxy,
ouzelReferenceProxy},
PBXSourceTree::Group);
const auto& productFile = create<PBXFileReference>("", storage::Path{project.getName() + ".app"},
PBXFileType::WrapperApplication,
PBXSourceTree::BuildProductsDir);
const auto& resourcesGroup = create<PBXGroup>("", storage::Path{"Resources"},
std::vector<PBXFileElementRef>{},
PBXSourceTree::Group);
const auto& productRefGroup = create<PBXGroup>("Products", storage::Path{},
std::vector<PBXFileElementRef>{productFile},
PBXSourceTree::Group);
std::vector<PBXBuildFileRef> buildFiles;
std::vector<PBXFileElementRef> sourceFiles;
for (const auto& sourceFile : project.getSourceFiles())
{
const auto extension = sourceFile.getExtension();
// TODO: support more file formats
const auto fileType = extension == "plist" ? PBXFileType::TextPlistXml :
extension == "c" ? PBXFileType::SourcecodeC :
extension == "h" ? PBXFileType::SourcecodeCH :
extension == "cpp" ? PBXFileType::SourcecodeCppCpp :
extension == "hpp" ? PBXFileType::SourcecodeCppH :
throw std::runtime_error("Unsupported file type");
const auto& fileReference = create<PBXFileReference>("", sourceFile, fileType, PBXSourceTree::Group);
sourceFiles.push_back(fileReference);
const auto& buildFile = create<PBXBuildFile>(fileReference);
buildFiles.push_back(buildFile);
}
const auto& sourceGroup = create<PBXGroup>("src", storage::Path{"src"},
sourceFiles, PBXSourceTree::Group);
const auto headerSearchPath = std::string(project.getOuzelPath() / "engine");
const auto& debugConfiguration = create<XCBuildConfiguration>("Debug",
std::map<std::string, std::string>{
{"CLANG_CXX_LANGUAGE_STANDARD", "c++14"},
{"GCC_OPTIMIZATION_LEVEL", "0"},
{"HEADER_SEARCH_PATHS", headerSearchPath}});
const auto& releaseConfiguration = create<XCBuildConfiguration>("Release",
std::map<std::string, std::string>{
{"CLANG_CXX_LANGUAGE_STANDARD", "c++14"},
{"HEADER_SEARCH_PATHS", headerSearchPath}});
const auto& projectConfigurationList = create<XCConfigurationList>(std::vector<XCBuildConfigurationRef>{
debugConfiguration,
releaseConfiguration},
releaseConfiguration.getName());
std::vector<PBXTargetRef> targets;
std::vector<PBXFileElementRef> frameworkFiles;
for (const auto platform : project.getPlatforms())
{
// TODO: do it for all platforms
if (platform == Platform::MacOs ||
platform == Platform::Ios ||
platform == Platform::Tvos)
{
const std::map<std::string, std::string> buildSettings =
platform == Platform::MacOs ? std::map<std::string, std::string>{{"PRODUCT_NAME", project.getName()}} :
platform == Platform::Ios ? std::map<std::string, std::string>{
{"PRODUCT_NAME", project.getName()},
{"SDKROOT", "iphoneos"}
} :
platform == Platform::Tvos ? std::map<std::string, std::string>{
{"PRODUCT_NAME", project.getName()},
{"SDKROOT", "appletvos"}
} :
std::map<std::string, std::string>{};
const auto& targetDebugConfiguration = create<XCBuildConfiguration>("Debug", buildSettings);
const auto& targetReleaseConfiguration = create<XCBuildConfiguration>("Release", buildSettings);
const auto& targetConfigurationList = create<XCConfigurationList>(std::vector<XCBuildConfigurationRef>{
targetDebugConfiguration,
targetReleaseConfiguration},
targetReleaseConfiguration.getName());
const auto& sourcesBuildPhase = create<PBXSourcesBuildPhase>(buildFiles);
std::vector<PBXFileReferenceRef> frameworkFileReferences;
std::vector<PBXBuildFileRef> frameworkBuildFiles;
switch (platform)
{
case Platform::MacOs:
{
const auto frameworksPath = storage::Path{"System/Library/Frameworks"};
for (const auto& framework : {
"AudioToolbox.framework",
"AudioUnit.framework",
"Cocoa.framework",
"CoreAudio.framework",
"CoreVideo.framework",
"GameController.framework",
"IOKit.framework",
"Metal.framework",
"OpenAL.framework",
"OpenGL.framework",
"QuartzCore.framework"
})
{
const auto& frameworkFileReference = create<PBXFileReference>(framework,
frameworksPath / framework,
PBXFileType::WrapperFramework,
PBXSourceTree::SdkRoot);
frameworkFileReferences.push_back(frameworkFileReference);
frameworkFiles.push_back(frameworkFileReference);
}
const auto& libouzelMacOsBuildFile = create<PBXBuildFile>(libouzelMacOsReferenceProxy);
frameworkBuildFiles.push_back(libouzelMacOsBuildFile);
break;
}
case Platform::Ios:
{
const auto& libouzelIosBuildFile = create<PBXBuildFile>(libouzelIosReferenceProxy);
frameworkBuildFiles.push_back(libouzelIosBuildFile);
break;
}
case Platform::Tvos:
{
const auto& libouzelTvosBuildFile = create<PBXBuildFile>(libouzelTvosReferenceProxy);
frameworkBuildFiles.push_back(libouzelTvosBuildFile);
break;
}
default:
throw std::runtime_error("Unsupported platform");
}
for (const PBXFileReferenceRef& frameworkFileReference : frameworkFileReferences)
{
const auto& frameworkBuildFile = create<PBXBuildFile>(frameworkFileReference);
frameworkBuildFiles.push_back(frameworkBuildFile);
}
const auto& frameworksBuildPhase = create<PBXFrameworksBuildPhase>(frameworkBuildFiles);
// TODO: implement asset build shell script
const auto& assetsBuildPhase = create<PBXShellScriptBuildPhase>("$BUILT_PRODUCTS_DIR/ouzel --export-assets $PROJECT_DIR/" + std::string(projectFilename));
// TODO: implement resource copy
const auto& resourcesBuildPhase = create<PBXResourcesBuildPhase>(std::vector<PBXBuildFileRef>{});
const auto& ouzelDependency = create<PBXTargetDependency>("ouzel", ouzelNativeTargetProxy);
const auto targetName = project.getName() + (
(platform == Platform::MacOs) ? " macOS" :
(platform == Platform::Ios) ? " iOS" :
(platform == Platform::Tvos) ? " tvOS" : "");
const auto& nativeTarget = create<PBXNativeTarget>(targetName,
targetConfigurationList,
std::vector<PBXBuildPhaseRef>{sourcesBuildPhase, frameworksBuildPhase, assetsBuildPhase, resourcesBuildPhase},
std::vector<PBXTargetDependencyRef>{ouzelDependency},
productFile);
targets.push_back(nativeTarget);
}
}
const auto& frameworksGroup = create<PBXGroup>("Frameworks", storage::Path{},
frameworkFiles,
PBXSourceTree::Group);
const auto& mainGroup = create<PBXGroup>("", storage::Path{},
std::vector<PBXFileElementRef>{
frameworksGroup,
ouzelProjectFileRef,
productRefGroup,
resourcesGroup,
sourceGroup},
PBXSourceTree::Group);
const auto& pbxProject = create<PBXProject>(project.getOrganization(),
projectConfigurationList,
mainGroup,
productRefGroup,
std::map<std::string, PBXObjectRef>{
{"ProductGroup", ouzelPoductRefGroup},
{"ProjectRef", ouzelProjectFileRef}},
targets);
rootObject = &pbxProject;
std::ofstream file(pbxProjectFile, std::ios::trunc);
file << plist::encode(encode());
}
private:
template <class T, class ...Args>
T& create(Args&& ...args)
{
std::unique_ptr<T> object = std::make_unique<T>(std::forward<Args>(args)...);
T& result = *object;
objects.push_back(std::move(object));
return result;
}
plist::Value encode() const {
plist::Value result = plist::Value::Dictionary{
{"archiveVersion", 1},
{"classes", plist::Value::Dictionary{}},
{"objectVersion", 50},
{"objects", plist::Value::Dictionary{}},
{"rootObject", rootObject ? toString(rootObject->getId()): ""}
};
for (const auto& object : objects)
result["objects"][toString(object->getId())] = object->encode();
return result;
}
const OuzelProject& project;
std::vector<std::unique_ptr<PBXObject>> objects;
const PBXObject* rootObject;
};
}
}
#endif // OUZEL_XCODE_PROJECT_HPP
<commit_msg>Enable testability and build only active architecture for debug targets<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_XCODE_PROJECT_HPP
#define OUZEL_XCODE_PROJECT_HPP
#include <fstream>
#include "OuzelProject.hpp"
#include "PBXBuildFile.hpp"
#include "PBXContainerItemProxy.hpp"
#include "PBXFileReference.hpp"
#include "PBXFrameworksBuildPhase.hpp"
#include "PBXGroup.hpp"
#include "PBXNativeTarget.hpp"
#include "PBXProject.hpp"
#include "PBXReferenceProxy.hpp"
#include "PBXResourcesBuildPhase.hpp"
#include "PBXShellScriptBuildPhase.hpp"
#include "PBXSourcesBuildPhase.hpp"
#include "PBXTargetDependency.hpp"
#include "XCBuildConfiguration.hpp"
#include "XCConfigurationList.hpp"
#include "storage/FileSystem.hpp"
#include "utils/Plist.hpp"
namespace ouzel
{
namespace xcode
{
class Project final
{
public:
Project(const OuzelProject& p):
project(p)
{
}
void generate()
{
const storage::Path projectFilename = project.getPath().getFilename();
const storage::Path projectDirectory = project.getPath().getDirectory();
auto xcodeProjectDirectory = projectDirectory / storage::Path{project.getName() + ".xcodeproj"};
auto xcodeProjectDirectoryType = xcodeProjectDirectory.getType();
if (xcodeProjectDirectoryType == storage::Path::Type::NotFound)
storage::FileSystem::createDirectory(xcodeProjectDirectory);
else if (xcodeProjectDirectoryType != storage::Path::Type::Directory)
{
storage::FileSystem::deleteFile(xcodeProjectDirectory);
storage::FileSystem::createDirectory(xcodeProjectDirectory);
}
auto pbxProjectFile = xcodeProjectDirectory / storage::Path{"project.pbxproj"};
constexpr auto libouzelIosId = Id{0x30, 0x3B, 0x75, 0x33, 0x1C, 0x2A, 0x3C, 0x58, 0x00, 0xFE, 0xDE, 0x92};
constexpr auto libouzelMacOsId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
constexpr auto libouzelTvosId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
constexpr auto ouzelId = Id{0x30, 0xA3, 0x96, 0x29, 0x24, 0x37, 0x73, 0xB5, 0x00, 0xD8, 0xE2, 0x8E};
const auto ouzelProjectPath = project.getOuzelPath() / "build" / "ouzel.xcodeproj";
const auto& ouzelProjectFileRef = create<PBXFileReference>("ouzel.xcodeproj", ouzelProjectPath,
PBXFileType::WrapperPBProject,
PBXSourceTree::Group);
const auto& libouzelIosProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelIosId, "libouzel_ios");
const auto& libouzelIosReferenceProxy = create<PBXReferenceProxy>("", "libouzel_ios.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelIosProxy);
const auto& libouzelMacOsProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelMacOsId, "libouzel_macos");
const auto& libouzelMacOsReferenceProxy = create<PBXReferenceProxy>("", "libouzel_macos.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelMacOsProxy);
const auto& libouzelTvosProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
libouzelTvosId, "libouzel_tvos");
const auto& libouzelTvosReferenceProxy = create<PBXReferenceProxy>("", "libouzel_tvos.a",
PBXFileType::ArchiveAr,
PBXSourceTree::BuildProductsDir,
libouzelTvosProxy);
const auto& ouzelProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::Reference,
ouzelId, "ouzel");
const auto& ouzelNativeTargetProxy = create<PBXContainerItemProxy>(ouzelProjectFileRef,
PBXContainerItemProxy::NativeTarget,
ouzelId, "ouzel");
const auto& ouzelReferenceProxy = create<PBXReferenceProxy>("", "ouzel",
PBXFileType::CompiledMachOExecutable,
PBXSourceTree::BuildProductsDir,
ouzelProxy);
const auto& ouzelPoductRefGroup = create<PBXGroup>("Products", storage::Path{},
std::vector<PBXFileElementRef>{
libouzelIosReferenceProxy,
libouzelMacOsReferenceProxy,
libouzelTvosReferenceProxy,
ouzelReferenceProxy},
PBXSourceTree::Group);
const auto& productFile = create<PBXFileReference>("", storage::Path{project.getName() + ".app"},
PBXFileType::WrapperApplication,
PBXSourceTree::BuildProductsDir);
const auto& resourcesGroup = create<PBXGroup>("", storage::Path{"Resources"},
std::vector<PBXFileElementRef>{},
PBXSourceTree::Group);
const auto& productRefGroup = create<PBXGroup>("Products", storage::Path{},
std::vector<PBXFileElementRef>{productFile},
PBXSourceTree::Group);
std::vector<PBXBuildFileRef> buildFiles;
std::vector<PBXFileElementRef> sourceFiles;
for (const auto& sourceFile : project.getSourceFiles())
{
const auto extension = sourceFile.getExtension();
// TODO: support more file formats
const auto fileType = extension == "plist" ? PBXFileType::TextPlistXml :
extension == "c" ? PBXFileType::SourcecodeC :
extension == "h" ? PBXFileType::SourcecodeCH :
extension == "cpp" ? PBXFileType::SourcecodeCppCpp :
extension == "hpp" ? PBXFileType::SourcecodeCppH :
throw std::runtime_error("Unsupported file type");
const auto& fileReference = create<PBXFileReference>("", sourceFile, fileType, PBXSourceTree::Group);
sourceFiles.push_back(fileReference);
const auto& buildFile = create<PBXBuildFile>(fileReference);
buildFiles.push_back(buildFile);
}
const auto& sourceGroup = create<PBXGroup>("src", storage::Path{"src"},
sourceFiles, PBXSourceTree::Group);
const auto headerSearchPath = std::string(project.getOuzelPath() / "engine");
const auto& debugConfiguration = create<XCBuildConfiguration>("Debug",
std::map<std::string, std::string>{
{"CLANG_CXX_LANGUAGE_STANDARD", "c++14"},
{"ENABLE_TESTABILITY", "YES"},
{"GCC_OPTIMIZATION_LEVEL", "0"},
{"HEADER_SEARCH_PATHS", headerSearchPath},
{"ONLY_ACTIVE_ARCH", "YES"}});
const auto& releaseConfiguration = create<XCBuildConfiguration>("Release",
std::map<std::string, std::string>{
{"CLANG_CXX_LANGUAGE_STANDARD", "c++14"},
{"HEADER_SEARCH_PATHS", headerSearchPath}});
const auto& projectConfigurationList = create<XCConfigurationList>(std::vector<XCBuildConfigurationRef>{
debugConfiguration,
releaseConfiguration},
releaseConfiguration.getName());
std::vector<PBXTargetRef> targets;
std::vector<PBXFileElementRef> frameworkFiles;
for (const auto platform : project.getPlatforms())
{
// TODO: do it for all platforms
if (platform == Platform::MacOs ||
platform == Platform::Ios ||
platform == Platform::Tvos)
{
const std::map<std::string, std::string> buildSettings =
platform == Platform::MacOs ? std::map<std::string, std::string>{{"PRODUCT_NAME", project.getName()}} :
platform == Platform::Ios ? std::map<std::string, std::string>{
{"PRODUCT_NAME", project.getName()},
{"SDKROOT", "iphoneos"}
} :
platform == Platform::Tvos ? std::map<std::string, std::string>{
{"PRODUCT_NAME", project.getName()},
{"SDKROOT", "appletvos"}
} :
std::map<std::string, std::string>{};
const auto& targetDebugConfiguration = create<XCBuildConfiguration>("Debug", buildSettings);
const auto& targetReleaseConfiguration = create<XCBuildConfiguration>("Release", buildSettings);
const auto& targetConfigurationList = create<XCConfigurationList>(std::vector<XCBuildConfigurationRef>{
targetDebugConfiguration,
targetReleaseConfiguration},
targetReleaseConfiguration.getName());
const auto& sourcesBuildPhase = create<PBXSourcesBuildPhase>(buildFiles);
std::vector<PBXFileReferenceRef> frameworkFileReferences;
std::vector<PBXBuildFileRef> frameworkBuildFiles;
switch (platform)
{
case Platform::MacOs:
{
const auto frameworksPath = storage::Path{"System/Library/Frameworks"};
for (const auto& framework : {
"AudioToolbox.framework",
"AudioUnit.framework",
"Cocoa.framework",
"CoreAudio.framework",
"CoreVideo.framework",
"GameController.framework",
"IOKit.framework",
"Metal.framework",
"OpenAL.framework",
"OpenGL.framework",
"QuartzCore.framework"
})
{
const auto& frameworkFileReference = create<PBXFileReference>(framework,
frameworksPath / framework,
PBXFileType::WrapperFramework,
PBXSourceTree::SdkRoot);
frameworkFileReferences.push_back(frameworkFileReference);
frameworkFiles.push_back(frameworkFileReference);
}
const auto& libouzelMacOsBuildFile = create<PBXBuildFile>(libouzelMacOsReferenceProxy);
frameworkBuildFiles.push_back(libouzelMacOsBuildFile);
break;
}
case Platform::Ios:
{
const auto& libouzelIosBuildFile = create<PBXBuildFile>(libouzelIosReferenceProxy);
frameworkBuildFiles.push_back(libouzelIosBuildFile);
break;
}
case Platform::Tvos:
{
const auto& libouzelTvosBuildFile = create<PBXBuildFile>(libouzelTvosReferenceProxy);
frameworkBuildFiles.push_back(libouzelTvosBuildFile);
break;
}
default:
throw std::runtime_error("Unsupported platform");
}
for (const PBXFileReferenceRef& frameworkFileReference : frameworkFileReferences)
{
const auto& frameworkBuildFile = create<PBXBuildFile>(frameworkFileReference);
frameworkBuildFiles.push_back(frameworkBuildFile);
}
const auto& frameworksBuildPhase = create<PBXFrameworksBuildPhase>(frameworkBuildFiles);
// TODO: implement asset build shell script
const auto& assetsBuildPhase = create<PBXShellScriptBuildPhase>("$BUILT_PRODUCTS_DIR/ouzel --export-assets $PROJECT_DIR/" + std::string(projectFilename));
// TODO: implement resource copy
const auto& resourcesBuildPhase = create<PBXResourcesBuildPhase>(std::vector<PBXBuildFileRef>{});
const auto& ouzelDependency = create<PBXTargetDependency>("ouzel", ouzelNativeTargetProxy);
const auto targetName = project.getName() + (
(platform == Platform::MacOs) ? " macOS" :
(platform == Platform::Ios) ? " iOS" :
(platform == Platform::Tvos) ? " tvOS" : "");
const auto& nativeTarget = create<PBXNativeTarget>(targetName,
targetConfigurationList,
std::vector<PBXBuildPhaseRef>{sourcesBuildPhase, frameworksBuildPhase, assetsBuildPhase, resourcesBuildPhase},
std::vector<PBXTargetDependencyRef>{ouzelDependency},
productFile);
targets.push_back(nativeTarget);
}
}
const auto& frameworksGroup = create<PBXGroup>("Frameworks", storage::Path{},
frameworkFiles,
PBXSourceTree::Group);
const auto& mainGroup = create<PBXGroup>("", storage::Path{},
std::vector<PBXFileElementRef>{
frameworksGroup,
ouzelProjectFileRef,
productRefGroup,
resourcesGroup,
sourceGroup},
PBXSourceTree::Group);
const auto& pbxProject = create<PBXProject>(project.getOrganization(),
projectConfigurationList,
mainGroup,
productRefGroup,
std::map<std::string, PBXObjectRef>{
{"ProductGroup", ouzelPoductRefGroup},
{"ProjectRef", ouzelProjectFileRef}},
targets);
rootObject = &pbxProject;
std::ofstream file(pbxProjectFile, std::ios::trunc);
file << plist::encode(encode());
}
private:
template <class T, class ...Args>
T& create(Args&& ...args)
{
std::unique_ptr<T> object = std::make_unique<T>(std::forward<Args>(args)...);
T& result = *object;
objects.push_back(std::move(object));
return result;
}
plist::Value encode() const {
plist::Value result = plist::Value::Dictionary{
{"archiveVersion", 1},
{"classes", plist::Value::Dictionary{}},
{"objectVersion", 50},
{"objects", plist::Value::Dictionary{}},
{"rootObject", rootObject ? toString(rootObject->getId()): ""}
};
for (const auto& object : objects)
result["objects"][toString(object->getId())] = object->encode();
return result;
}
const OuzelProject& project;
std::vector<std::unique_ptr<PBXObject>> objects;
const PBXObject* rootObject;
};
}
}
#endif // OUZEL_XCODE_PROJECT_HPP
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#include <filesystem>
#endif
#include <map>
#include <babylon/core/string.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <imgui_utils/imgui_utils.h>
#include <babylon/inspector/samples_browser.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <imgui.h>
#include <babylon/inspector/inspector.h>
namespace
{
std::string to_snake_case(const std::string &sPascalCase)
{
std::stringstream ss;
bool first = true;
for (auto c : sPascalCase)
{
if (std::tolower(c) != c)
{
if (!first)
ss << "_";
ss << static_cast<unsigned char>(std::tolower(c));
}
else
ss << c;
first = false;
}
return ss.str();
}
#ifdef _WIN32
const std::string screenshotsFolderCurrent = "../../../assets/screenshots/samples_current/";
const std::string screenshotsFolderOriginal = "../../../assets/screenshots/samples/";
#else
const std::string screenshotsFolderCurrent = "../assets/screenshots/samples_current/";
const std::string screenshotsFolderOriginal = "../assets/screenshots/samples/";
#endif
} // end anonymous namespace
namespace BABYLON {
using namespace BABYLON::Samples;
class SamplesBrowserImpl
{
public:
using CategoryName = std::string;
using SampleName = std::string;
SamplesBrowserImpl() : _samplesIndex(Samples::SamplesIndex::Instance())
{
for (const std::string & sample : _samplesIndex.getSampleNames())
_samplesInfos[sample] = _samplesIndex.getSampleInfo(sample);
fillMatchingSamples();
}
void render()
{
render_filter();
ImGui::Separator();
render_list();
}
SamplesBrowser::CallbackNewRenderableScene OnNewRenderableScene;
SamplesBrowser::CallbackEditFiles OnEditFiles;
SamplesBrowser::CallbackLoopSamples OnLoopSamples;
private:
void render_filter()
{
bool changed = false;
ImGui::PushItemWidth(200);
if (ImGui::InputText_String("Filter", _query.query))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox(ICON_FA_WRENCH "Experimental", &_query.onlyFailures))
changed = true;
if (OnLoopSamples) {
if (ImGui::Button("Loop filtered samples")) {
std::vector<std::string> filteredSamples;
for (const auto& kv : _matchingSamples) {
for (auto sampleName : kv.second)
filteredSamples.push_back(sampleName);
}
OnLoopSamples(filteredSamples);
}
}
if (changed)
fillMatchingSamples();
ImGui::Text("Matching samples : %zi", nbMatchingSamples());
}
void render_list()
{
enum class CollapseMode
{
None,
CollapseAll,
ExpandAll
};
CollapseMode collapseMode = CollapseMode::None;
if (ImGui::Button("Collapse All"))
collapseMode = CollapseMode::CollapseAll;
ImGui::SameLine();
if (ImGui::Button("Expand All"))
collapseMode = CollapseMode::ExpandAll;
ImGui::Separator();
ImGui::BeginChild("Child1");
for (const auto & kv : _matchingSamples)
{
CategoryName category = kv.first;
auto samples = kv.second;
if (!samples.empty())
{
std::string header = category + " (" + std::to_string(samples.size()) + ")";
if (collapseMode == CollapseMode::CollapseAll)
ImGui::SetNextItemOpen(false);
if (collapseMode == CollapseMode::ExpandAll)
ImGui::SetNextItemOpen(true);
if (ImGui::CollapsingHeader(header.c_str())) //ImGuiTreeNodeFlags_DefaultOpen))
{
for (const std::string & sample : samples)
{
//ImGui::Text("%s", sample.c_str());
guiOneSample(sample);
ImGui::Separator();
}
}
}
}
ImGui::EndChild();
}
void guiOneSampleInfos(const std::string & sampleName)
{
const auto & sampleInfo = _samplesInfos.at(sampleName);
std::string runLabel = std::string(ICON_FA_PLAY_CIRCLE " Run##") + sampleName;
if (ImGui::Button(runLabel.c_str()))
{
if (OnNewRenderableScene)
{
BABYLON::ICanvas *dummyCanvas = nullptr;
auto scene = _samplesIndex.createRenderableScene(sampleName, dummyCanvas);
OnNewRenderableScene(std::move(scene));
}
if (Inspector::OnSampleChanged)
Inspector::OnSampleChanged(sampleName);
}
if (OnEditFiles)
{
ImGui::SameLine();
std::string viewCodeLabel = ICON_FA_EDIT " View code##" + sampleName;
if (ImGui::Button(viewCodeLabel.c_str()))
OnEditFiles({ sampleInfo.HeaderFile, sampleInfo.SourceFile });
}
if (!sampleInfo.Links.empty()) {
for (auto link : sampleInfo.Links) {
std::string btnUrlString = std::string(ICON_FA_EXTERNAL_LINK_ALT "##") + link;
if (ImGui::Button(btnUrlString.c_str()))
BABYLON::System::openBrowser(link);
ImGui::SameLine();
ImVec4 linkColor(0.5f, 0.5f, 0.95f, 1.f);
ImGui::TextColored(linkColor, "%s", link.c_str());
}
}
}
void guiOneSample(const std::string &sampleName)
{
const auto & sampleInfo = _samplesInfos[sampleName];
std::string currentScreenshotFile = screenshotsFolderCurrent + sampleName + ".jpg";
std::string sample_snake = to_snake_case(sampleName);
std::string originalScreenshotFile = screenshotsFolderOriginal + sample_snake + ".png";
if (_showCurrentScreenshots)
{
ImGui::BeginGroup();
ImVec2 imageSize(ImGui::GetWindowWidth() / 3.f, 0.f);
ImGuiUtils::ImageFromFile(currentScreenshotFile, imageSize);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Current(c++)");
ImGui::EndGroup();
ImGui::SameLine();
}
if (_showOriginalScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(originalScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Original(js)");
ImGui::EndGroup();
ImGui::SameLine();
}
ImGui::BeginGroup();
ImGui::Text("%s", sampleName.c_str());
ImGui::TextWrapped("%s", sampleInfo.Brief.c_str());
auto failure = _samplesIndex.doesSampleFail(sampleName);
if (failure)
{
ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.3f, 1.f), "Failure: %s",
SampleFailureReason_Str(failure.value().Kind).c_str()
);
if (!failure.value().Info.empty())
ImGui::TextColored(
ImVec4(0.4f, 0.9f, 0.6f, 1.f), "More details: %s",
failure.value().Info.c_str());
}
guiOneSampleInfos(sampleName);
ImGui::EndGroup();
ImGui::SameLine();
}
bool doesSampleMatchQuery(const CategoryName & categoryName, const SampleName & sampleName)
{
std::vector<std::string> search_items = BABYLON::String::split(_query.query, ' ');
bool doesMatch = true;
{
std::string all = BABYLON::String::toLowerCase(categoryName + " / " + sampleName);
for (const auto &item : search_items)
if (!BABYLON::String::contains(all, BABYLON::String::toLowerCase(item)))
doesMatch = false;
}
if (_query.onlyFailures)
{
if (!_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
else
{
if (_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
return doesMatch;
}
void fillMatchingSamples()
{
_matchingSamples.clear();
for (CategoryName category : _samplesIndex.getCategoryNames())
{
std::vector<SampleName> s;
for (SampleName sample : _samplesIndex.getSampleNamesInCategory(category))
{
if (doesSampleMatchQuery(category, sample))
s.push_back(sample);
_matchingSamples[category] = s;
}
}
}
size_t nbMatchingSamples()
{
size_t r = 0;
for (const auto &kv : _matchingSamples)
r += kv.second.size();
return r;
}
std::map<SampleName, SampleInfo> _samplesInfos;
SamplesIndex & _samplesIndex;
std::map<CategoryName, std::vector<SampleName>> _matchingSamples;
struct {
std::string query = "";
bool onlyFailures = false;
} _query;
bool _showOriginalScreenshots = false;
bool _showCurrentScreenshots = true;
};
SamplesBrowser::SamplesBrowser()
{
pImpl = std::make_unique<SamplesBrowserImpl>();
}
SamplesBrowser::~SamplesBrowser() = default;
void SamplesBrowser::render()
{
pImpl->OnNewRenderableScene = OnNewRenderableScene;
pImpl->OnEditFiles = OnEditFiles;
pImpl->OnLoopSamples = OnLoopSamples;
pImpl->render();
}
} // end of namespace BABYLON
<commit_msg>samples_browser: use assets_folder()<commit_after>#ifdef _MSC_VER
#include <filesystem>
#endif
#include <map>
#include <babylon/core/string.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <imgui_utils/imgui_utils.h>
#include <babylon/inspector/samples_browser.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/babylon_common.h>
#include <imgui.h>
#include <babylon/inspector/inspector.h>
namespace
{
std::string to_snake_case(const std::string &sPascalCase)
{
std::stringstream ss;
bool first = true;
for (auto c : sPascalCase)
{
if (std::tolower(c) != c)
{
if (!first)
ss << "_";
ss << static_cast<unsigned char>(std::tolower(c));
}
else
ss << c;
first = false;
}
return ss.str();
}
const std::string screenshotsFolderCurrent = BABYLON::assets_folder() + "/screenshots/samples_current/";
const std::string screenshotsFolderOriginal = BABYLON::assets_folder() +"/screenshots/samples/";
} // end anonymous namespace
namespace BABYLON {
using namespace BABYLON::Samples;
class SamplesBrowserImpl
{
public:
using CategoryName = std::string;
using SampleName = std::string;
SamplesBrowserImpl() : _samplesIndex(Samples::SamplesIndex::Instance())
{
for (const std::string & sample : _samplesIndex.getSampleNames())
_samplesInfos[sample] = _samplesIndex.getSampleInfo(sample);
fillMatchingSamples();
}
void render()
{
render_filter();
ImGui::Separator();
render_list();
}
SamplesBrowser::CallbackNewRenderableScene OnNewRenderableScene;
SamplesBrowser::CallbackEditFiles OnEditFiles;
SamplesBrowser::CallbackLoopSamples OnLoopSamples;
private:
void render_filter()
{
bool changed = false;
ImGui::PushItemWidth(200);
if (ImGui::InputText_String("Filter", _query.query))
changed = true;
ImGui::SameLine();
if (ImGui::Checkbox(ICON_FA_WRENCH "Experimental", &_query.onlyFailures))
changed = true;
if (OnLoopSamples) {
if (ImGui::Button("Loop filtered samples")) {
std::vector<std::string> filteredSamples;
for (const auto& kv : _matchingSamples) {
for (auto sampleName : kv.second)
filteredSamples.push_back(sampleName);
}
OnLoopSamples(filteredSamples);
}
}
if (changed)
fillMatchingSamples();
ImGui::Text("Matching samples : %zi", nbMatchingSamples());
}
void render_list()
{
enum class CollapseMode
{
None,
CollapseAll,
ExpandAll
};
CollapseMode collapseMode = CollapseMode::None;
if (ImGui::Button("Collapse All"))
collapseMode = CollapseMode::CollapseAll;
ImGui::SameLine();
if (ImGui::Button("Expand All"))
collapseMode = CollapseMode::ExpandAll;
ImGui::Separator();
ImGui::BeginChild("Child1");
for (const auto & kv : _matchingSamples)
{
CategoryName category = kv.first;
auto samples = kv.second;
if (!samples.empty())
{
std::string header = category + " (" + std::to_string(samples.size()) + ")";
if (collapseMode == CollapseMode::CollapseAll)
ImGui::SetNextItemOpen(false);
if (collapseMode == CollapseMode::ExpandAll)
ImGui::SetNextItemOpen(true);
if (ImGui::CollapsingHeader(header.c_str())) //ImGuiTreeNodeFlags_DefaultOpen))
{
for (const std::string & sample : samples)
{
//ImGui::Text("%s", sample.c_str());
guiOneSample(sample);
ImGui::Separator();
}
}
}
}
ImGui::EndChild();
}
void guiOneSampleInfos(const std::string & sampleName)
{
const auto & sampleInfo = _samplesInfos.at(sampleName);
std::string runLabel = std::string(ICON_FA_PLAY_CIRCLE " Run##") + sampleName;
if (ImGui::Button(runLabel.c_str()))
{
if (OnNewRenderableScene)
{
BABYLON::ICanvas *dummyCanvas = nullptr;
auto scene = _samplesIndex.createRenderableScene(sampleName, dummyCanvas);
OnNewRenderableScene(std::move(scene));
}
if (Inspector::OnSampleChanged)
Inspector::OnSampleChanged(sampleName);
}
if (OnEditFiles)
{
ImGui::SameLine();
std::string viewCodeLabel = ICON_FA_EDIT " View code##" + sampleName;
if (ImGui::Button(viewCodeLabel.c_str()))
OnEditFiles({ sampleInfo.HeaderFile, sampleInfo.SourceFile });
}
if (!sampleInfo.Links.empty()) {
for (auto link : sampleInfo.Links) {
std::string btnUrlString = std::string(ICON_FA_EXTERNAL_LINK_ALT "##") + link;
if (ImGui::Button(btnUrlString.c_str()))
BABYLON::System::openBrowser(link);
ImGui::SameLine();
ImVec4 linkColor(0.5f, 0.5f, 0.95f, 1.f);
ImGui::TextColored(linkColor, "%s", link.c_str());
}
}
}
void guiOneSample(const std::string &sampleName)
{
const auto & sampleInfo = _samplesInfos[sampleName];
std::string currentScreenshotFile = screenshotsFolderCurrent + sampleName + ".jpg";
std::string sample_snake = to_snake_case(sampleName);
std::string originalScreenshotFile = screenshotsFolderOriginal + sample_snake + ".png";
if (_showCurrentScreenshots)
{
ImGui::BeginGroup();
ImVec2 imageSize(ImGui::GetWindowWidth() / 3.f, 0.f);
ImGuiUtils::ImageFromFile(currentScreenshotFile, imageSize);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Current(c++)");
ImGui::EndGroup();
ImGui::SameLine();
}
if (_showOriginalScreenshots)
{
ImGui::BeginGroup();
ImGuiUtils::ImageFromFile(originalScreenshotFile);
if (_showOriginalScreenshots && _showCurrentScreenshots)
ImGui::TextColored(ImVec4(0.5f, 0.5f, 0.5f, 0.7f), "Original(js)");
ImGui::EndGroup();
ImGui::SameLine();
}
ImGui::BeginGroup();
ImGui::Text("%s", sampleName.c_str());
ImGui::TextWrapped("%s", sampleInfo.Brief.c_str());
auto failure = _samplesIndex.doesSampleFail(sampleName);
if (failure)
{
ImGui::TextColored(ImVec4(0.9f, 0.4f, 0.3f, 1.f), "Failure: %s",
SampleFailureReason_Str(failure.value().Kind).c_str()
);
if (!failure.value().Info.empty())
ImGui::TextColored(
ImVec4(0.4f, 0.9f, 0.6f, 1.f), "More details: %s",
failure.value().Info.c_str());
}
guiOneSampleInfos(sampleName);
ImGui::EndGroup();
ImGui::SameLine();
}
bool doesSampleMatchQuery(const CategoryName & categoryName, const SampleName & sampleName)
{
std::vector<std::string> search_items = BABYLON::String::split(_query.query, ' ');
bool doesMatch = true;
{
std::string all = BABYLON::String::toLowerCase(categoryName + " / " + sampleName);
for (const auto &item : search_items)
if (!BABYLON::String::contains(all, BABYLON::String::toLowerCase(item)))
doesMatch = false;
}
if (_query.onlyFailures)
{
if (!_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
else
{
if (_samplesIndex.doesSampleFail(sampleName))
doesMatch = false;
}
return doesMatch;
}
void fillMatchingSamples()
{
_matchingSamples.clear();
for (CategoryName category : _samplesIndex.getCategoryNames())
{
std::vector<SampleName> s;
for (SampleName sample : _samplesIndex.getSampleNamesInCategory(category))
{
if (doesSampleMatchQuery(category, sample))
s.push_back(sample);
_matchingSamples[category] = s;
}
}
}
size_t nbMatchingSamples()
{
size_t r = 0;
for (const auto &kv : _matchingSamples)
r += kv.second.size();
return r;
}
std::map<SampleName, SampleInfo> _samplesInfos;
SamplesIndex & _samplesIndex;
std::map<CategoryName, std::vector<SampleName>> _matchingSamples;
struct {
std::string query = "";
bool onlyFailures = false;
} _query;
bool _showOriginalScreenshots = false;
bool _showCurrentScreenshots = true;
};
SamplesBrowser::SamplesBrowser()
{
pImpl = std::make_unique<SamplesBrowserImpl>();
}
SamplesBrowser::~SamplesBrowser() = default;
void SamplesBrowser::render()
{
pImpl->OnNewRenderableScene = OnNewRenderableScene;
pImpl->OnEditFiles = OnEditFiles;
pImpl->OnLoopSamples = OnLoopSamples;
pImpl->render();
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>#include "EnvimetReader.h"
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkInformationVector.h>
#include <vtkInformation.h>
#include <vtkSmartPointer.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkFloatArray.h>
#include <iostream>
#include <fstream>
#include <string>
vtkStandardNewMacro(EnvimetReader);
EnvimetReader::EnvimetReader()
{
this->FileName = NULL;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
int EnvimetReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
if(!this->FileName)
{
vtkErrorMacro(<< "A FileName must be specified.");
return -1;
}
vtkDebugMacro (<< "reading seismic header");
// TODO: read this info from EDI file
x_spacing = 5;
y_spacing = 5;
x_dim = 249;
y_dim = 249;
z_dim = 30;
int ext[6] = {0, x_dim, 0, y_dim, 0, z_dim};
double origin[3] = {0, 0, 0};
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext, 6);
outInfo->Set(vtkDataObject::ORIGIN(), origin, 3);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
return 1;
}
int EnvimetReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
output->SetExtent(
outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
// Points
output->SetDimensions(x_dim, y_dim, z_dim);
vtkFloatArray *xCoords = vtkFloatArray::New();
for(int i = 0; i < x_dim; i++) xCoords->InsertNextValue(i*x_spacing);
vtkFloatArray *yCoords = vtkFloatArray::New();
for(int i = 0; i < y_dim; i++) yCoords->InsertNextValue(i*y_spacing);
vtkFloatArray *zCoords = vtkFloatArray::New();
zCoords->InsertNextValue(0.f);
zCoords->InsertNextValue(1.f);
float z_sum = 1;
for(int i = 2; i < z_dim; i++)
{
float lastCellHeight = zCoords->GetValue(i-1)-zCoords->GetValue(i-2);
float currentCellHeight = 1.2f * lastCellHeight;
z_sum += currentCellHeight;
zCoords->InsertNextValue(z_sum);
}
output->SetXCoordinates(xCoords);
output->SetYCoordinates(yCoords);
output->SetZCoordinates(zCoords);
// data arrays
std::string arrayNames[] = {
"z",
"Classed LAD",
"Flow u",
"Flow v",
"Flow w",
"Wind speed",
"Wind speed change",
"Wind direction",
"Pressure perturb",
"Pot. temperature",
"Pot. temperature (Diff K)",
"Pot. temperature Change K/h",
"Spec. humidity",
"Relative humidity",
"Turbulent kinetic energy",
"Dissipitation",
"Vertical exchange coef.",
"Horizontal exchange coef.",
"Absoule LAD",
"Direct SW radiation",
"Diffuse SW radiation",
"Reflected SW radiation",
"Longwave rad. environment",
"Sky-view-factor buildings",
"Sky-view-factor buildings + vegetation",
"Temperature flux",
"Vapour flux",
"Water on leafs",
"Wall temperature x",
"Wall temperature y",
"Wall temperature z",
"Leaf temperature",
"Local mixing length",
"PMV",
"Percentage people dissatisfied",
"Mean radiant temperature",
"Gas/particle concentration",
"Gas/particle source",
"Deposition velocities",
"Total deposed mass",
"Deposed mass time averaged",
"TKE normalised 1D",
"Dissipitaion normalised 1D",
"km normalised 1D",
"TKE mechanical prod",
"Stomata resistance",
"CO2",
"CO2 ppm",
"Plant CO2 flux",
"Div Rlw Temp change",
"Local mass budget"
};
std::ifstream in (this->FileName, std::ifstream::in | std::ios::binary);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << this->FileName << " could not be opened");
return -1;
}
// TODO: read all vars
int numVars = 5;
for(int varIndex = 0; varIndex < numVars; varIndex++)
{
vtkFloatArray *varArray = vtkFloatArray::New();
varArray->SetName(arrayNames[varIndex].c_str());
varArray->SetNumberOfTuples(x_dim*y_dim*z_dim);
for(int zIndex = 0; zIndex < z_dim; zIndex++)
{
for(int xIndex = 0; xIndex < x_dim; xIndex++)
{
for(int yIndex = 0; yIndex < y_dim; yIndex++)
{
float myFloat = -9999;
in.read(reinterpret_cast<char *>(&myFloat), sizeof(myFloat));
varArray->SetValue(xIndex + yIndex*x_dim + zIndex*x_dim*y_dim, myFloat);
}
}
}
output->GetPointData()->AddArray(varArray);
}
in.close();
return 1;
}
void EnvimetReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
}
<commit_msg>Optimized file reading, fixed read order.<commit_after>#include "EnvimetReader.h"
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkInformationVector.h>
#include <vtkInformation.h>
#include <vtkSmartPointer.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkFloatArray.h>
#include <iostream>
#include <fstream>
#include <string>
vtkStandardNewMacro(EnvimetReader);
EnvimetReader::EnvimetReader()
{
this->FileName = NULL;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
int EnvimetReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
if(!this->FileName)
{
vtkErrorMacro(<< "A FileName must be specified.");
return -1;
}
vtkDebugMacro (<< "reading seismic header");
// TODO: read this info from EDI file
x_spacing = 5;
y_spacing = 5;
x_dim = 249;
y_dim = 249;
z_dim = 30;
int ext[6] = {0, x_dim, 0, y_dim, 0, z_dim};
double origin[3] = {0, 0, 0};
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext, 6);
outInfo->Set(vtkDataObject::ORIGIN(), origin, 3);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
return 1;
}
int EnvimetReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
output->SetExtent(
outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
// Points
output->SetDimensions(x_dim, y_dim, z_dim);
vtkFloatArray *xCoords = vtkFloatArray::New();
for(int i = 0; i < x_dim; i++) xCoords->InsertNextValue(i*x_spacing);
vtkFloatArray *yCoords = vtkFloatArray::New();
for(int i = 0; i < y_dim; i++) yCoords->InsertNextValue(i*y_spacing);
vtkFloatArray *zCoords = vtkFloatArray::New();
zCoords->InsertNextValue(0.f);
zCoords->InsertNextValue(1.f);
float z_sum = 1;
for(int i = 2; i < z_dim; i++)
{
float lastCellHeight = zCoords->GetValue(i-1)-zCoords->GetValue(i-2);
float currentCellHeight = 1.2f * lastCellHeight;
z_sum += currentCellHeight;
zCoords->InsertNextValue(z_sum);
}
output->SetXCoordinates(xCoords);
output->SetYCoordinates(yCoords);
output->SetZCoordinates(zCoords);
// data arrays
std::string arrayNames[] = {
"z",
"Classed LAD",
"Flow u",
"Flow v",
"Flow w",
"Wind speed",
"Wind speed change",
"Wind direction",
"Pressure perturb",
"Pot. temperature",
"Pot. temperature (Diff K)",
"Pot. temperature Change K/h",
"Spec. humidity",
"Relative humidity",
"Turbulent kinetic energy",
"Dissipitation",
"Vertical exchange coef.",
"Horizontal exchange coef.",
"Absoule LAD",
"Direct SW radiation",
"Diffuse SW radiation",
"Reflected SW radiation",
"Longwave rad. environment",
"Sky-view-factor buildings",
"Sky-view-factor buildings + vegetation",
"Temperature flux",
"Vapour flux",
"Water on leafs",
"Wall temperature x",
"Wall temperature y",
"Wall temperature z",
"Leaf temperature",
"Local mixing length",
"PMV",
"Percentage people dissatisfied",
"Mean radiant temperature",
"Gas/particle concentration",
"Gas/particle source",
"Deposition velocities",
"Total deposed mass",
"Deposed mass time averaged",
"TKE normalised 1D",
"Dissipitaion normalised 1D",
"km normalised 1D",
"TKE mechanical prod",
"Stomata resistance",
"CO2",
"CO2 ppm",
"Plant CO2 flux",
"Div Rlw Temp change",
"Local mass budget"
};
std::ifstream in (this->FileName, std::ifstream::in | std::ios::binary);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << this->FileName << " could not be opened");
return -1;
}
// TODO: read all vars
int numVars = 5;
const vtkIdType numTuples = x_dim*y_dim*z_dim;
for(int varIndex = 0; varIndex < numVars; varIndex++)
{
vtkFloatArray *varArray = vtkFloatArray::New();
varArray->SetName(arrayNames[varIndex].c_str());
varArray->SetNumberOfTuples(numTuples);
float* tuples = new float[numTuples];
in.read(reinterpret_cast<char *>(&tuples[0]), sizeof(float)*numTuples);
// Ownership of tuples is handed over to varArray
varArray->SetArray(tuples, numTuples, 0);
output->GetPointData()->AddArray(varArray);
}
in.close();
return 1;
}
void EnvimetReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrCaps.h"
#include "GrContextFactory.h"
#include "SkCanvas.h"
#include "SkCommandLineFlags.h"
#include "SkJSONCanvas.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkSurface.h"
#include <sys/socket.h>
#include <microhttpd.h>
// To get image decoders linked in we have to do the below magic
#include "SkForceLinking.h"
#include "SkImageDecoder.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
// TODO make this configurable
#define PORT 8888
DEFINE_string(dir, "skps", "Directory to read skp.");
DEFINE_string(name, "desk_carsvg", "skp to load.");
DEFINE_bool(useTemplate, true, "whether or not to use the skdebugger template string.");
// TODO probably want to make this configurable
static const int kImageWidth = 1920;
static const int kImageHeight = 1080;
// TODO move to template file
SkString generateTemplate(SkString source) {
SkString debuggerTemplate;
debuggerTemplate.appendf(
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
" <title>SkDebugger</title>\n"
" <meta charset=\"utf-8\" />\n"
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=egde,chrome=1\">\n"
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
" <script src=\"%s/res/js/core.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n"
" <link href=\"%s/res/vul/elements.html\" rel=\"import\" />\n"
"</head>\n"
"<body class=\"fullbleed layout vertical\">\n"
" <debugger-app-sk>This is the app."
" </debugger-app-sk>\n"
"</body>\n"
"</html>", source.c_str(), source.c_str());
return debuggerTemplate;
}
struct UploadContext {
SkDynamicMemoryWStream fStream;
MHD_PostProcessor* fPostProcessor;
MHD_Connection* connection;
};
struct Request {
Request() : fUploadContext(nullptr) {}
UploadContext* fUploadContext;
SkAutoTUnref<SkData> fPNG;
SkAutoTUnref<SkPicture> fPicture;
};
// TODO factor this out into functions, also handle CPU path
bool setupAndDrawToCanvas(Request* request, SkString* error) {
GrContextOptions grContextOpts;
SkAutoTDelete<GrContextFactory> factory(new GrContextFactory(grContextOpts));
GrContext* context = factory->get(GrContextFactory::kNative_GLContextType,
GrContextFactory::kNone_GLContextOptions);
int maxRTSize = context->caps()->maxRenderTargetSize();
SkImageInfo info = SkImageInfo::Make(SkTMin(kImageWidth, maxRTSize),
SkTMin(kImageHeight, maxRTSize),
kN32_SkColorType, kPremul_SkAlphaType);
uint32_t flags = 0;
SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(context,
SkSurface::kNo_Budgeted, info,
0, &props));
SkASSERT(surface.get());
SkGLContext* gl = factory->getContextInfo(GrContextFactory::kNative_GLContextType,
GrContextFactory::kNone_GLContextOptions).fGLContext;
gl->makeCurrent();
// draw
request->fPicture.reset(
SkPicture::CreateFromStream(request->fUploadContext->fStream.detachAsStream()));
if (!request->fPicture.get()) {
error->appendf("Could not create picture from stream.\n");
return false;
}
SkCanvas* canvas = surface->getCanvas();
canvas->drawPicture(request->fPicture);
// capture pixels
SkBitmap bmp;
bmp.setInfo(canvas->imageInfo());
if (!canvas->readPixels(&bmp, 0, 0)) {
error->appendf("Can't read canvas pixels.\n");
return false;
}
// write to png
request->fPNG.reset(SkImageEncoder::EncodeData(bmp, SkImageEncoder::kPNG_Type, 100));
if (!request->fPNG) {
error->appendf("Can't encode a PNG.\n");
return false;
}
return true;
}
static const size_t kBufferSize = 1024;
static int process_upload_data(void* cls, enum MHD_ValueKind kind,
const char* key, const char* filename,
const char* content_type, const char* transfer_encoding,
const char* data, uint64_t off, size_t size) {
struct UploadContext* uc = reinterpret_cast<UploadContext*>(cls);
if (0 != size) {
uc->fStream.write(data, size);
}
return MHD_YES;
}
static int SendData(MHD_Connection* connection, const SkData* data, const char* type) {
MHD_Response* response = MHD_create_response_from_buffer(data->size(),
const_cast<void*>(data->data()),
MHD_RESPMEM_MUST_COPY);
MHD_add_response_header(response, "Content-Type", type);
int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
}
static int SendJSON(MHD_Connection* connection, SkPicture* picture) {
SkDynamicMemoryWStream stream;
SkAutoTUnref<SkJSONCanvas> jsonCanvas(new SkJSONCanvas(kImageWidth, kImageHeight, stream));
jsonCanvas->drawPicture(picture);
jsonCanvas->finish();
SkAutoTUnref<SkData> data(stream.copyToData());
return SendData(connection, data, "application/json");
}
static int SendTemplate(MHD_Connection* connection, bool redirect = false,
const char* redirectUrl = nullptr) {
SkString debuggerTemplate = generateTemplate(SkString("https://debugger.skia.org"));
MHD_Response* response = MHD_create_response_from_buffer(
debuggerTemplate.size(),
(void*) const_cast<char*>(debuggerTemplate.c_str()),
MHD_RESPMEM_MUST_COPY);
MHD_add_response_header (response, "Access-Control-Allow-Origin", "*");
int status = MHD_HTTP_OK;
if (redirect) {
MHD_add_response_header (response, "Location", redirectUrl);
status = MHD_HTTP_SEE_OTHER;
}
int ret = MHD_queue_response(connection, status, response);
MHD_destroy_response(response);
return ret;
}
typedef int (*UrlHandler)(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size);
int rootHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
return SendTemplate(connection);
}
int postHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
UploadContext* uc = request->fUploadContext;
// New connection
if (!uc) {
// TODO make this a method on request
uc = new UploadContext;
uc->connection = connection;
uc->fPostProcessor = MHD_create_post_processor(connection, kBufferSize,
&process_upload_data, uc);
SkASSERT(uc->fPostProcessor);
request->fUploadContext = uc;
return MHD_YES;
}
// in process upload
if (0 != *upload_data_size) {
SkASSERT(uc->fPostProcessor);
MHD_post_process(uc->fPostProcessor, upload_data, *upload_data_size);
*upload_data_size = 0;
return MHD_YES;
}
// end of upload
MHD_destroy_post_processor(uc->fPostProcessor);
uc->fPostProcessor = nullptr;
// TODO response
SkString error;
if (!setupAndDrawToCanvas(request, &error)) {
// TODO send error
return MHD_YES;
}
return SendTemplate(connection, true, "/");
}
int imgHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
if (request->fPNG.get()) {
SkData* data = request->fPNG.get();
return SendData(connection, data, "image/png");
}
return MHD_NO;
}
int infoHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
if (request->fPicture.get()) {
return SendJSON(connection, request->fPicture);
}
return MHD_NO;
}
class UrlManager {
public:
UrlManager() {
// Register handlers
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/", rootHandler});
fHandlers.push_back({MHD_HTTP_METHOD_POST, "/new", postHandler});
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/img", imgHandler});
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/cmd", infoHandler});
}
// This is clearly not efficient for a large number of urls and handlers
int invoke(Request* request, MHD_Connection* connection, const char* url, const char* method,
const char* upload_data, size_t* upload_data_size) const {
for (int i = 0; i < fHandlers.count(); i++) {
const Url& urlHandler = fHandlers[i];
if (0 == strcmp(method, urlHandler.fMethod) &&
0 == strcmp(url, urlHandler.fPath)) {
return (*urlHandler.fHandler)(request, connection, upload_data,
upload_data_size);
}
}
return MHD_NO;
}
private:
struct Url {
const char* fMethod;
const char* fPath;
UrlHandler fHandler;
};
SkTArray<Url> fHandlers;
};
const UrlManager kUrlManager;
int answer_to_connection(void* cls, struct MHD_Connection* connection,
const char* url, const char* method, const char* version,
const char* upload_data, size_t* upload_data_size,
void** con_cls) {
SkDebugf("New %s request for %s using version %s\n", method, url, version);
Request* request = reinterpret_cast<Request*>(cls);
return kUrlManager.invoke(request, connection, url, method, upload_data, upload_data_size);
}
int skiaserve_main() {
Request request; // This simple server has one request
struct MHD_Daemon* daemon;
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, nullptr, nullptr,
&answer_to_connection, &request,
MHD_OPTION_END);
if (NULL == daemon) {
return 1;
}
getchar();
MHD_stop_daemon(daemon);
return 0;
}
#if !defined SK_BUILD_FOR_IOS
int main(int argc, char** argv) {
SkCommandLineFlags::Parse(argc, argv);
return skiaserve_main();
}
#endif
<commit_msg>skiaserve: Clean up flags.<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrCaps.h"
#include "GrContextFactory.h"
#include "SkCanvas.h"
#include "SkCommandLineFlags.h"
#include "SkJSONCanvas.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkSurface.h"
#include <sys/socket.h>
#include <microhttpd.h>
// To get image decoders linked in we have to do the below magic
#include "SkForceLinking.h"
#include "SkImageDecoder.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
DEFINE_string(source, "https://debugger.skia.org", "Where to load the web UI from.");
DEFINE_int32(port, 8888, "The port to listen on.");
// TODO probably want to make this configurable
static const int kImageWidth = 1920;
static const int kImageHeight = 1080;
// TODO move to template file
SkString generateTemplate(SkString source) {
SkString debuggerTemplate;
debuggerTemplate.appendf(
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
" <title>SkDebugger</title>\n"
" <meta charset=\"utf-8\" />\n"
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=egde,chrome=1\">\n"
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
" <script src=\"%s/res/js/core.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n"
" <link href=\"%s/res/vul/elements.html\" rel=\"import\" />\n"
"</head>\n"
"<body class=\"fullbleed layout vertical\">\n"
" <debugger-app-sk>This is the app."
" </debugger-app-sk>\n"
"</body>\n"
"</html>", source.c_str(), source.c_str());
return debuggerTemplate;
}
struct UploadContext {
SkDynamicMemoryWStream fStream;
MHD_PostProcessor* fPostProcessor;
MHD_Connection* connection;
};
struct Request {
Request() : fUploadContext(nullptr) {}
UploadContext* fUploadContext;
SkAutoTUnref<SkData> fPNG;
SkAutoTUnref<SkPicture> fPicture;
};
// TODO factor this out into functions, also handle CPU path
bool setupAndDrawToCanvas(Request* request, SkString* error) {
GrContextOptions grContextOpts;
SkAutoTDelete<GrContextFactory> factory(new GrContextFactory(grContextOpts));
GrContext* context = factory->get(GrContextFactory::kNative_GLContextType,
GrContextFactory::kNone_GLContextOptions);
int maxRTSize = context->caps()->maxRenderTargetSize();
SkImageInfo info = SkImageInfo::Make(SkTMin(kImageWidth, maxRTSize),
SkTMin(kImageHeight, maxRTSize),
kN32_SkColorType, kPremul_SkAlphaType);
uint32_t flags = 0;
SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(context,
SkSurface::kNo_Budgeted, info,
0, &props));
SkASSERT(surface.get());
SkGLContext* gl = factory->getContextInfo(GrContextFactory::kNative_GLContextType,
GrContextFactory::kNone_GLContextOptions).fGLContext;
gl->makeCurrent();
// draw
request->fPicture.reset(
SkPicture::CreateFromStream(request->fUploadContext->fStream.detachAsStream()));
if (!request->fPicture.get()) {
error->appendf("Could not create picture from stream.\n");
return false;
}
SkCanvas* canvas = surface->getCanvas();
canvas->drawPicture(request->fPicture);
// capture pixels
SkBitmap bmp;
bmp.setInfo(canvas->imageInfo());
if (!canvas->readPixels(&bmp, 0, 0)) {
error->appendf("Can't read canvas pixels.\n");
return false;
}
// write to png
request->fPNG.reset(SkImageEncoder::EncodeData(bmp, SkImageEncoder::kPNG_Type, 100));
if (!request->fPNG) {
error->appendf("Can't encode a PNG.\n");
return false;
}
return true;
}
static const size_t kBufferSize = 1024;
static int process_upload_data(void* cls, enum MHD_ValueKind kind,
const char* key, const char* filename,
const char* content_type, const char* transfer_encoding,
const char* data, uint64_t off, size_t size) {
struct UploadContext* uc = reinterpret_cast<UploadContext*>(cls);
if (0 != size) {
uc->fStream.write(data, size);
}
return MHD_YES;
}
static int SendData(MHD_Connection* connection, const SkData* data, const char* type) {
MHD_Response* response = MHD_create_response_from_buffer(data->size(),
const_cast<void*>(data->data()),
MHD_RESPMEM_MUST_COPY);
MHD_add_response_header(response, "Content-Type", type);
int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
}
static int SendJSON(MHD_Connection* connection, SkPicture* picture) {
SkDynamicMemoryWStream stream;
SkAutoTUnref<SkJSONCanvas> jsonCanvas(new SkJSONCanvas(kImageWidth, kImageHeight, stream));
jsonCanvas->drawPicture(picture);
jsonCanvas->finish();
SkAutoTUnref<SkData> data(stream.copyToData());
return SendData(connection, data, "application/json");
}
static int SendTemplate(MHD_Connection* connection, bool redirect = false,
const char* redirectUrl = nullptr) {
SkString debuggerTemplate = generateTemplate(SkString(FLAGS_source[0]));
MHD_Response* response = MHD_create_response_from_buffer(
debuggerTemplate.size(),
(void*) const_cast<char*>(debuggerTemplate.c_str()),
MHD_RESPMEM_MUST_COPY);
MHD_add_response_header (response, "Access-Control-Allow-Origin", "*");
int status = MHD_HTTP_OK;
if (redirect) {
MHD_add_response_header (response, "Location", redirectUrl);
status = MHD_HTTP_SEE_OTHER;
}
int ret = MHD_queue_response(connection, status, response);
MHD_destroy_response(response);
return ret;
}
typedef int (*UrlHandler)(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size);
int rootHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
return SendTemplate(connection);
}
int postHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
UploadContext* uc = request->fUploadContext;
// New connection
if (!uc) {
// TODO make this a method on request
uc = new UploadContext;
uc->connection = connection;
uc->fPostProcessor = MHD_create_post_processor(connection, kBufferSize,
&process_upload_data, uc);
SkASSERT(uc->fPostProcessor);
request->fUploadContext = uc;
return MHD_YES;
}
// in process upload
if (0 != *upload_data_size) {
SkASSERT(uc->fPostProcessor);
MHD_post_process(uc->fPostProcessor, upload_data, *upload_data_size);
*upload_data_size = 0;
return MHD_YES;
}
// end of upload
MHD_destroy_post_processor(uc->fPostProcessor);
uc->fPostProcessor = nullptr;
// TODO response
SkString error;
if (!setupAndDrawToCanvas(request, &error)) {
// TODO send error
return MHD_YES;
}
return SendTemplate(connection, true, "/");
}
int imgHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
if (request->fPNG.get()) {
SkData* data = request->fPNG.get();
return SendData(connection, data, "image/png");
}
return MHD_NO;
}
int infoHandler(Request* request, MHD_Connection* connection,
const char* upload_data, size_t* upload_data_size) {
if (request->fPicture.get()) {
return SendJSON(connection, request->fPicture);
}
return MHD_NO;
}
class UrlManager {
public:
UrlManager() {
// Register handlers
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/", rootHandler});
fHandlers.push_back({MHD_HTTP_METHOD_POST, "/new", postHandler});
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/img", imgHandler});
fHandlers.push_back({MHD_HTTP_METHOD_GET, "/cmd", infoHandler});
}
// This is clearly not efficient for a large number of urls and handlers
int invoke(Request* request, MHD_Connection* connection, const char* url, const char* method,
const char* upload_data, size_t* upload_data_size) const {
for (int i = 0; i < fHandlers.count(); i++) {
const Url& urlHandler = fHandlers[i];
if (0 == strcmp(method, urlHandler.fMethod) &&
0 == strcmp(url, urlHandler.fPath)) {
return (*urlHandler.fHandler)(request, connection, upload_data,
upload_data_size);
}
}
return MHD_NO;
}
private:
struct Url {
const char* fMethod;
const char* fPath;
UrlHandler fHandler;
};
SkTArray<Url> fHandlers;
};
const UrlManager kUrlManager;
int answer_to_connection(void* cls, struct MHD_Connection* connection,
const char* url, const char* method, const char* version,
const char* upload_data, size_t* upload_data_size,
void** con_cls) {
SkDebugf("New %s request for %s using version %s\n", method, url, version);
Request* request = reinterpret_cast<Request*>(cls);
return kUrlManager.invoke(request, connection, url, method, upload_data, upload_data_size);
}
int skiaserve_main() {
Request request; // This simple server has one request
struct MHD_Daemon* daemon;
// TODO Add option to bind this strictly to an address, e.g. localhost, for security.
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, FLAGS_port, nullptr, nullptr,
&answer_to_connection, &request,
MHD_OPTION_END);
if (NULL == daemon) {
return 1;
}
getchar();
MHD_stop_daemon(daemon);
return 0;
}
#if !defined SK_BUILD_FOR_IOS
int main(int argc, char** argv) {
SkCommandLineFlags::Parse(argc, argv);
return skiaserve_main();
}
#endif
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
#include "xenia/cpu/processor.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_state, KernelState* state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
XUserModule* module = state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
xe_xex2_ref xex = module->xex();
const xe_xex2_header_t* header = xe_xex2_get_header(xex);
uint32_t result = (header->system_flags & mask) > 0;
module->Release();
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_handle_ptr = SHIM_GET_ARG_32(1);
XModule* module = nullptr;
if (!module_name) {
module = state->GetExecutableModule();
} else {
module = state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(module_handle_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(module_handle_ptr, module->handle());
XELOGD("%.8X = XexGetModuleHandle(%s, %.8X)", module->handle(), module_name, module_handle_ptr);
module->Release();
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", handle, name, data_ptr,
size_ptr);
XModule* module = NULL;
X_STATUS result =
state->object_table()->GetObject(handle, (XObject**)&module);
if (XSUCCEEDED(result)) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t handle_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, handle_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
XModule* module = state->GetModule(module_name);
if (module) {
module->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, module->handle());
module->Release();
result = X_STATUS_SUCCESS;
} else {
XUserModule* usermod = state->LoadUserModule(module_name);
if (usermod) {
// If the module has an entry point function, we have to call it.
const xe_xex2_header_t* header = usermod->xex_header();
if (header->exe_entry_point) {
state->processor()->Execute(ppc_state->thread_state,
header->exe_entry_point);
}
result = X_STATUS_SUCCESS;
usermod->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, usermod->handle());
usermod->Release();
}
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", handle);
X_STATUS result = X_STATUS_INVALID_HANDLE;
result = state->object_table()->RemoveHandle(handle);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t module_handle = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(ordinal);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
X_STATUS result = X_STATUS_INVALID_HANDLE;
SHIM_SET_MEM_32(out_function_ptr, 0xDEADF00D);
XModule* module = NULL;
if (!module_handle) {
module = state->GetExecutableModule();
} else {
result =
state->object_table()->GetObject(module_handle, (XObject**)&module);
}
uint32_t ptr = 0;
if (XSUCCEEDED(result)) {
if (ordinal < 0x10000) {
// Ordinal.
ptr = module->GetProcAddressByOrdinal(ordinal);
} else {
// It's a name pointer instead.
ptr = module->GetProcAddressByName(name);
}
}
// FYI: We don't need to generate this function now. It'll
// be done automatically by xenia when it gets called.
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
result = X_STATUS_UNSUCCESSFUL;
}
if (ordinal < 0x10000) {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X, %.8X)", ptr,
module_handle, ordinal, out_function_ptr);
} else {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", ptr,
module_handle, ordinal, name, out_function_ptr);
}
if (module) {
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL ExRegisterTitleTerminateNotification_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t registration_ptr = SHIM_GET_ARG_32(0);
uint32_t create = SHIM_GET_ARG_32(1);
uint32_t routine = SHIM_MEM_32(registration_ptr + 0);
uint32_t priority = SHIM_MEM_32(registration_ptr + 4);
// list entry flink
// list entry blink
XELOGD("ExRegisterTitleTerminateNotification(%.8X(%.8X), %.1X)",
registration_ptr, routine, create);
if (create) {
// Adding.
// TODO(benvanik): add to master list (kernel?).
} else {
// Removing.
// TODO(benvanik): remove from master list.
}
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
SHIM_SET_MAPPING("xboxkrnl.exe", ExRegisterTitleTerminateNotification, state);
}
<commit_msg>Call a DLL's entry-point function in XexLoadImage<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
#include "xenia/cpu/processor.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_state, KernelState* state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
XUserModule* module = state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
xe_xex2_ref xex = module->xex();
const xe_xex2_header_t* header = xe_xex2_get_header(xex);
uint32_t result = (header->system_flags & mask) > 0;
module->Release();
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_handle_ptr = SHIM_GET_ARG_32(1);
XModule* module = nullptr;
if (!module_name) {
module = state->GetExecutableModule();
} else {
module = state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(module_handle_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(module_handle_ptr, module->handle());
XELOGD("%.8X = XexGetModuleHandle(%s, %.8X)", module->handle(), module_name, module_handle_ptr);
module->Release();
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", handle, name, data_ptr,
size_ptr);
XModule* module = NULL;
X_STATUS result =
state->object_table()->GetObject(handle, (XObject**)&module);
if (XSUCCEEDED(result)) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t handle_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, handle_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
XModule* module = state->GetModule(module_name);
if (module) {
module->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, module->handle());
module->Release();
result = X_STATUS_SUCCESS;
} else {
XUserModule* usermod = state->LoadUserModule(module_name);
if (usermod) {
// If the module has an entry point function, we have to call it.
const xe_xex2_header_t* header = usermod->xex_header();
if (header->exe_entry_point) {
// Return address
uint32_t lr = ppc_state->thread_state->context()->lr;
// TODO: What are these args for?
// param 2: val 1 seems to make CRT initialize
uint64_t args[] = { 0, 1, 0 };
state->processor()->Execute(ppc_state->thread_state,
header->exe_entry_point,
args, xe::countof(args));
ppc_state->thread_state->context()->lr = lr;
}
result = X_STATUS_SUCCESS;
usermod->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, usermod->handle());
usermod->Release();
}
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", handle);
X_STATUS result = X_STATUS_INVALID_HANDLE;
result = state->object_table()->RemoveHandle(handle);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t module_handle = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(ordinal);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
X_STATUS result = X_STATUS_INVALID_HANDLE;
SHIM_SET_MEM_32(out_function_ptr, 0xDEADF00D);
XModule* module = NULL;
if (!module_handle) {
module = state->GetExecutableModule();
} else {
result =
state->object_table()->GetObject(module_handle, (XObject**)&module);
}
uint32_t ptr = 0;
if (XSUCCEEDED(result)) {
if (ordinal < 0x10000) {
// Ordinal.
ptr = module->GetProcAddressByOrdinal(ordinal);
} else {
// It's a name pointer instead.
ptr = module->GetProcAddressByName(name);
}
}
// FYI: We don't need to generate this function now. It'll
// be done automatically by xenia when it gets called.
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
result = X_STATUS_UNSUCCESSFUL;
}
if (ordinal < 0x10000) {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X, %.8X)", ptr,
module_handle, ordinal, out_function_ptr);
} else {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", ptr,
module_handle, ordinal, name, out_function_ptr);
}
if (module) {
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL ExRegisterTitleTerminateNotification_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t registration_ptr = SHIM_GET_ARG_32(0);
uint32_t create = SHIM_GET_ARG_32(1);
uint32_t routine = SHIM_MEM_32(registration_ptr + 0);
uint32_t priority = SHIM_MEM_32(registration_ptr + 4);
// list entry flink
// list entry blink
XELOGD("ExRegisterTitleTerminateNotification(%.8X(%.8X), %.1X)",
registration_ptr, routine, create);
if (create) {
// Adding.
// TODO(benvanik): add to master list (kernel?).
} else {
// Removing.
// TODO(benvanik): remove from master list.
}
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
SHIM_SET_MAPPING("xboxkrnl.exe", ExRegisterTitleTerminateNotification, state);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2003-2008 Grame
Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
[email protected]
This file is provided as an example of the MusicXML Library use.
*/
#ifdef VC6
# pragma warning (disable : 4786)
#endif
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "musicxml2guido.h"
using namespace std;
using namespace MusicXML2;
void usage(int exitStatus) {
cerr <<
endl <<
"--> Usage: musicxml2guido [options] <MusicXMLFile>" << endl <<
" Action: reads <MusicXMLFile> or stdin if <MusicXMLFile> is '-'" << endl <<
endl <<
" -b,--autobars: don't generates barlines" << endl <<
endl;
exit(exitStatus);
}
//_______________________________________________________________________________
int main(int argc, char *argv[])
{
/*
cout << "argc = " << argc << endl;
for (int i = 0; i < argc ; i++ ) {
cout << "argv[ " << i << "] = " << argv[i] << endl;
}
*/
bool generateBars = true;
static struct option long_options [] =
{
/* These options set a flag. */
{"help", no_argument, 0, 'h'},
{"autobars", no_argument, 0, 'b'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
int c;
while (
(c = getopt_long (
argc, argv,
"hab",
long_options, & option_index ))
!=
-1
)
{
switch (c)
{
case 'h' :
usage (0);
break;
case 'b' :
generateBars = false;
break;
} // switch
} // while
int nonOptionArgs = argc-optind;
const char * file = "";
switch (nonOptionArgs)
{
case 1 :
file = argv [optind];
break;
default:
std::cerr <<
"--> nonOptionArgs = " << nonOptionArgs << std::endl;
usage (1);
} // switch
// int remainingArgs = nonOptionArgs;
xmlErr err = kNoErr;
if (!strcmp(file, "-"))
err = musicxmlfd2guido(stdin, generateBars, cout);
else
err = musicxmlfile2guido(file, generateBars, cout);
if (err) {
cout << "conversion failed" << endl;
}
return 0;
}
<commit_msg>manual merge of dev version<commit_after>/*
Copyright (C) 2003-2008 Grame
Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
[email protected]
This file is provided as an example of the MusicXML Library use.
*/
#ifdef VC6
# pragma warning (disable : 4786)
#endif
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <signal.h>
#include <string.h>
#endif
#include "libmusicxml.h"
using namespace std;
using namespace MusicXML2;
static void usage() {
cerr << "usage: musicxml2guido [options] <musicxml file>" << endl;
cerr << " reads stdin when <musicxml file> is '-'" << endl;
cerr << " option: --autobars don't generates barlines" << endl;
exit(1);
}
#ifndef WIN32
static void _sigaction(int signal, siginfo_t *si, void *arg)
{
cerr << "Signal #" << signal << " catched!" << endl;
exit(-2);
}
static void catchsigs()
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = _sigaction;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGILL, &sa, NULL);
sigaction(SIGFPE, &sa, NULL);
}
#else
static void catchsigs() {}
#endif
//_______________________________________________________________________________
int main(int argc, char *argv[])
{
catchsigs();
bool generateBars = true;
char * file = argv[1];
if (argc == 3) {
if (!strcmp(argv[1], "--autobars")) {
generateBars = false;
file = argv[2];
}
else usage();
}
else if (argc != 2) usage();
xmlErr err = kNoErr;
if (!strcmp(file, "-"))
err = musicxmlfd2guido(stdin, generateBars, cout);
else
err = musicxmlfile2guido(file, generateBars, cout);
if (err) {
cout << "conversion failed" << endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Make sure rhs is ready for assembly<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <canvas/canvastools.hxx>
#include "attributemap.hxx"
#include "tools.hxx"
namespace slideshow
{
namespace internal
{
typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;
AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )
{
/** Maps attribute name to AttributeType enum.
String entries are all case-insensitive and MUST
BE STORED lowercase.
String entries MUST BE SORTED in ascending order!
*/
static AnimateAttributeMap::MapEntry lcl_attributeMap[] =
{
{ "charcolor", ATTRIBUTE_CHAR_COLOR },
{ "charfontname", ATTRIBUTE_CHAR_FONT_NAME },
{ "charheight", ATTRIBUTE_CHAR_HEIGHT },
{ "charposture", ATTRIBUTE_CHAR_POSTURE },
// TODO(Q1): This should prolly be changed in PPT import
// { "charrotation", ATTRIBUTE_CHAR_ROTATION },
{ "charrotation", ATTRIBUTE_ROTATE },
{ "charunderline", ATTRIBUTE_CHAR_UNDERLINE },
{ "charweight", ATTRIBUTE_CHAR_WEIGHT },
{ "color", ATTRIBUTE_COLOR },
{ "dimcolor", ATTRIBUTE_DIMCOLOR },
{ "fillcolor", ATTRIBUTE_FILL_COLOR },
{ "fillstyle", ATTRIBUTE_FILL_STYLE },
{ "height", ATTRIBUTE_HEIGHT },
{ "linecolor", ATTRIBUTE_LINE_COLOR },
{ "linestyle", ATTRIBUTE_LINE_STYLE },
{ "opacity", ATTRIBUTE_OPACITY },
{ "rotate", ATTRIBUTE_ROTATE },
{ "skewx", ATTRIBUTE_SKEW_X },
{ "skewy", ATTRIBUTE_SKEW_Y },
{ "visibility", ATTRIBUTE_VISIBILITY },
{ "width", ATTRIBUTE_WIDTH },
{ "x", ATTRIBUTE_POS_X },
{ "y", ATTRIBUTE_POS_Y }
};
static AnimateAttributeMap aMap( lcl_attributeMap,
sizeof(lcl_attributeMap)/sizeof(*lcl_attributeMap),
false );
AttributeType eAttributeType = ATTRIBUTE_INVALID;
// determine the type from the attribute name
if( !aMap.lookup( rAttrName,
eAttributeType ) )
{
OSL_TRACE( "mapAttributeName(): attribute name %s not found in map.",
::rtl::OUStringToOString( rAttrName,
RTL_TEXTENCODING_ASCII_US ).getStr() );
return ATTRIBUTE_INVALID;
}
return eAttributeType;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove double line spacing.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <canvas/canvastools.hxx>
#include "attributemap.hxx"
#include "tools.hxx"
namespace slideshow
{
namespace internal
{
typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;
AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )
{
/** Maps attribute name to AttributeType enum.
String entries are all case-insensitive and MUST
BE STORED lowercase.
String entries MUST BE SORTED in ascending order!
*/
static AnimateAttributeMap::MapEntry lcl_attributeMap[] =
{
{ "charcolor", ATTRIBUTE_CHAR_COLOR },
{ "charfontname", ATTRIBUTE_CHAR_FONT_NAME },
{ "charheight", ATTRIBUTE_CHAR_HEIGHT },
{ "charposture", ATTRIBUTE_CHAR_POSTURE },
// TODO(Q1): This should prolly be changed in PPT import
// { "charrotation", ATTRIBUTE_CHAR_ROTATION },
{ "charrotation", ATTRIBUTE_ROTATE },
{ "charunderline", ATTRIBUTE_CHAR_UNDERLINE },
{ "charweight", ATTRIBUTE_CHAR_WEIGHT },
{ "color", ATTRIBUTE_COLOR },
{ "dimcolor", ATTRIBUTE_DIMCOLOR },
{ "fillcolor", ATTRIBUTE_FILL_COLOR },
{ "fillstyle", ATTRIBUTE_FILL_STYLE },
{ "height", ATTRIBUTE_HEIGHT },
{ "linecolor", ATTRIBUTE_LINE_COLOR },
{ "linestyle", ATTRIBUTE_LINE_STYLE },
{ "opacity", ATTRIBUTE_OPACITY },
{ "rotate", ATTRIBUTE_ROTATE },
{ "skewx", ATTRIBUTE_SKEW_X },
{ "skewy", ATTRIBUTE_SKEW_Y },
{ "visibility", ATTRIBUTE_VISIBILITY },
{ "width", ATTRIBUTE_WIDTH },
{ "x", ATTRIBUTE_POS_X },
{ "y", ATTRIBUTE_POS_Y }
};
static AnimateAttributeMap aMap( lcl_attributeMap,
sizeof(lcl_attributeMap)/sizeof(*lcl_attributeMap),
false );
AttributeType eAttributeType = ATTRIBUTE_INVALID;
// determine the type from the attribute name
if( !aMap.lookup( rAttrName,
eAttributeType ) )
{
OSL_TRACE( "mapAttributeName(): attribute name %s not found in map.",
::rtl::OUStringToOString( rAttrName,
RTL_TEXTENCODING_ASCII_US ).getStr() );
return ATTRIBUTE_INVALID;
}
return eAttributeType;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// vi: set ts=2:
//
// $Id: mainframe.C,v 1.62.8.6 2007/06/12 05:42:24 oliver Exp $
//
#include "mainframe.h"
#include "icons.h"
#include "demoTutorialDialog.h"
#include <BALL/CONCEPT/moleculeObjectCreator.h>
#ifdef BALL_HAS_ASIO
#include <BALL/VIEW/KERNEL/serverWidget.h>
#endif
#include <BALL/VIEW/RENDERING/POVRenderer.h>
#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/WIDGETS/molecularControl.h>
#include <BALL/VIEW/WIDGETS/geometricControl.h>
#include <BALL/VIEW/WIDGETS/logView.h>
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/WIDGETS/datasetControl.h>
#include <BALL/VIEW/WIDGETS/editableScene.h>
#include <BALL/VIEW/WIDGETS/fileObserver.h>
#include <BALL/VIEW/WIDGETS/testFramework.h>
#include <BALL/VIEW/DIALOGS/pubchemDialog.h>
#include <BALL/VIEW/DIALOGS/downloadPDBFile.h>
#include <BALL/VIEW/DIALOGS/labelDialog.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>
#ifdef BALL_PYTHON_SUPPORT
# include <BALL/VIEW/WIDGETS/pyWidget.h>
#endif
#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/COMMON/version.h>
#include <QtGui/QKeyEvent>
#include <QtGui/QTreeWidget>
#ifdef BALL_COMPILER_MSVC
# include "ui_aboutDialog.h"
#else
# include "aboutDialog.h"
#endif
#include <BALL/VIEW/INPUT/spaceNavigatorDriver.h>
using namespace std;
namespace BALL
{
using namespace std;
using namespace BALL::VIEW;
Mainframe::Mainframe(QWidget* parent, const char* name)
: MainControl(parent, name, ".BALLView"),
scene_(0)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new Mainframe " << this << std::endl;
#endif
// ---------------------
// setup main window
// ---------------------
setWindowTitle("BALLView");
setWindowIcon(QPixmap(bucky_64x64_xpm));
// make sure submenus are the first
initPopupMenu(FILE_OPEN);
initPopupMenu(EDIT);
initPopupMenu(BUILD);
initPopupMenu(DISPLAY);
initPopupMenu(MOLECULARMECHANICS);
initPopupMenu(TOOLS);
#ifdef BALL_PYTHON_SUPPORT
initPopupMenu(TOOLS_PYTHON);
initPopupMenu(MainControl::USER);
#endif
initPopupMenu(WINDOWS);
initPopupMenu(MACRO);
// ---------------------
// Logstream setup -----
// ---------------------
// Log.remove(std::cout);
// Log.remove(std::cerr);
setLoggingFilename("BALLView.log");
// Display Menu
insertMenuEntry(MainControl::DISPLAY, "Toggle Fullscreen", this, SLOT(toggleFullScreen()),
Qt::ALT+Qt::Key_X);
insertPopupMenuSeparator(DISPLAY);
initPopupMenu(DISPLAY_VIEWPOINT);
new MolecularFileDialog(this, "MolecularFileDialog");
new DownloadPDBFile( this, "DownloadPDBFile", false);
new PubChemDialog(this, "PubChemDialog");
addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, "Structures"));
addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, "Representations"));
addDockWidget(Qt::TopDockWidgetArea, new DatasetControl(this, "Datasets"));
DatasetControl* dc = DatasetControl::getInstance(0);
dc->registerController(new RegularData3DController());
dc->registerController(new TrajectoryController());
dc->registerController(new VectorGridController());
dc->registerController(new DockResultController());
DatasetControl::getInstance(0)->hide();
new DemoTutorialDialog(this, "BALLViewDemo");
HelpViewer* BALL_docu = new HelpViewer(this, "BALL Docu");
addDockWidget(Qt::BottomDockWidgetArea, BALL_docu);
String dirp = getDataPath() + ".." + FileSystem::PATH_SEPARATOR + "doc" +
FileSystem::PATH_SEPARATOR + "BALL" + FileSystem::PATH_SEPARATOR;
BALL_docu->setBaseDirectory(dirp);
BALL_docu->setWhatsThisEnabled(false);
BALL_docu->setProject("BALL");
BALL_docu->setDefaultPage("index.htm");
addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu"));
new LabelDialog( this, "LabelDialog");
new MolecularStructure( this, "MolecularStructure");
addDockWidget(Qt::BottomDockWidgetArea, new LogView(this, "Logs"));
addDockWidget(Qt::BottomDockWidgetArea, new FileObserver( this, "FileObserver"));
Scene::stereoBufferSupportTest();
scene_ = new EditableScene(this, "3D View");
setCentralWidget(scene_);
setAcceptDrops(true);
new DisplayProperties( this, "DisplayProperties");
// setup the VIEW server
#ifdef BALL_HAS_ASIO
ServerWidget* server = new ServerWidget(this);
// registering object generator
MoleculeObjectCreator* object_creator = new MoleculeObjectCreator;
server->registerObjectCreator(*object_creator);
#endif
new TestFramework(this, "Test Framework");
#ifdef BALL_PYTHON_SUPPORT
addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, "Python Interpreter"));
#endif
// ---------------------
// Menus ---------------
// ---------------------
String hint;
insertMenuEntry(MainControl::FILE_OPEN, "Project", this, SLOT(loadBALLViewProjectFile()));
save_project_action_ = insertMenuEntry(MainControl::FILE, "Save Project", this,
SLOT(saveBALLViewProjectFile()));
// Help-Menu -------------------------------------------------------------------
QAction* action = 0;
action = insertMenuEntry(MainControl::HELP, "About", this, SLOT(about()));
setMenuHint(action, "Show informations on this version of BALLView");
action = insertMenuEntry(MainControl::HELP, "How to cite", this, SLOT(howToCite()));
setMenuHint(action, "Show infos on how to cite BALL and BALLView");
stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, "Abort Calculation", this,
SLOT(stopSimulation()), Qt::ALT+Qt::Key_C);
stop_simulation_action_->setEnabled(false);
insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);
setMenuHint(stop_simulation_action_, "Abort a running simulation");
Path path;
String filename = path.find("graphics/stop.png");
stop_simulation_action_->setIcon(QIcon(filename.c_str()));
complement_selection_action_ = insertMenuEntry(MainControl::EDIT, "Toggle Selection", this, SLOT(complementSelection()));
qApp->installEventFilter(this);
setStatusbarText("Ready.");
SpaceNavigatorDriver* drv = new SpaceNavigatorDriver(scene_);
if(!drv->setUp()) {
delete drv;
} else {
drv->setEnabled(true);
}
}
Mainframe::~Mainframe()
throw()
{
}
bool Mainframe::eventFilter(QObject* sender, QEvent* event)
{
if (event->type() != QEvent::KeyPress) return false;
QKeyEvent* e = dynamic_cast<QKeyEvent*>(event);
if (e->key() == Qt::Key_Escape &&
HelpViewer::getInstance(1)->isWhatsThisEnabled())
{
HelpViewer::getInstance(1)->exitWhatsThisMode();
}
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
if (widget == scene_ &&
qApp->focusWidget() != scene_)
{
scene_->keyPressEvent(e);
return true;
}
if (widget != scene_ &&
e->key() == Qt::Key_Escape)
{
scene_->switchToLastMode();
return true;
}
if (e->key() == Qt::Key_Delete &&
RTTI::isKindOf<QTreeWidget>(*sender))
{
deleteClicked();
return true;
}
if (e->key() == Qt::Key_Enter)
{
if (composite_manager_.getNumberOfComposites() == 0) return false;
if (getMolecularControlSelection().size() == 0)
{
control_selection_.push_back(*composite_manager_.begin());
}
MolecularStructure::getInstance(0)->centerCamera();
return true;
}
// check all menu entries if Alt or CTRL is pressed to enable shortcuts
if (e->key() == Qt::Key_Alt ||
e->key() == Qt::Key_Control)
{
checkMenus();
return false;
}
#ifdef BALL_PYTHON_SUPPORT
PyWidget::getInstance(0)->reactTo(*e);
e->accept();
#endif
return false;
}
void Mainframe::reset()
{
if (composites_locked_ || getRepresentationManager().updateRunning()) return;
clearData();
DisplayProperties* dp = DisplayProperties::getInstance(0);
dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
dp->selectModel(MODEL_STICK);
dp->selectColoringMethod(COLORING_ELEMENT);
dp->selectMode(DRAWING_MODE_SOLID);
dp->setTransparency(0);
dp->setSurfaceDrawingPrecision(6.5);
}
void Mainframe::howToCite()
{
HelpViewer::getInstance(1)->showHelp("tips.html", "cite");
}
void Mainframe::show()
{
// prevent multiple inserting of menu entries, by calls of showFullScreen(), ...
if (preferences_action_ != 0)
{
MainControl::show();
return;
}
QToolBar* tb = new QToolBar("Main Toolbar", this);
tb->setObjectName("Main Toolbar");
tb->setIconSize(QSize(23,23));
tb->layout()->setMargin(2);
tb->layout()->setSpacing(2);
addToolBar(Qt::TopToolBarArea, tb);
MainControl::show();
initPopupMenu(MainControl::WINDOWS)->addSeparator();
initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());
MolecularFileDialog::getInstance(0)->addToolBarEntries(tb);
DownloadPDBFile::getInstance(0)->addToolBarEntries(tb);
PubChemDialog::getInstance(0)->addToolBarEntries(tb);
Path path;
QIcon load_icon(path.find("graphics/quickload.png").c_str());
qload_action_ = new QAction(load_icon, "quickload", this);
qload_action_->setObjectName("quickload");
connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));
HelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, "tips.html#quickload");
tb->addAction(qload_action_);
QIcon save_icon(path.find("graphics/quicksave.png").c_str());
qsave_action_ = new QAction(save_icon, "quicksave", this);
qsave_action_->setObjectName("quicksave");
connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));
HelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, "tips.html#quickload");
tb->addAction(qsave_action_);
tb->addSeparator();
DisplayProperties::getInstance(0)->addToolBarEntries(tb);
MolecularStructure::getInstance(0)->addToolBarEntries(tb);
scene_->addToolBarEntries(tb);
tb->addAction(stop_simulation_action_);
tb->addAction(preferences_action_);
HelpViewer::getInstance(1)->addToolBarEntries(tb);
// we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have
// to restore the window state again!
restoreWindows();
}
void Mainframe::about()
{
// Display about dialog
QDialog w;
Ui_AboutDialog about;
about.setupUi(&w);
QString version = QString("QT ") + qVersion();
#ifdef BALL_QT_HAS_THREADS
version += "(mt)";
#endif
about.qt_version_label->setText(version);
QFont font = about.BALLView_version_label->font();
about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING);
font.setPixelSize(18);
about.BALLView_version_label->setFont(font);
about.BALL_version_label->setText(__DATE__);
w.exec();
}
}
<commit_msg>Removed the SpaceNavigator driver from BALLView<commit_after>// vi: set ts=2:
//
// $Id: mainframe.C,v 1.62.8.6 2007/06/12 05:42:24 oliver Exp $
//
#include "mainframe.h"
#include "icons.h"
#include "demoTutorialDialog.h"
#include <BALL/CONCEPT/moleculeObjectCreator.h>
#ifdef BALL_HAS_ASIO
#include <BALL/VIEW/KERNEL/serverWidget.h>
#endif
#include <BALL/VIEW/RENDERING/POVRenderer.h>
#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/WIDGETS/molecularControl.h>
#include <BALL/VIEW/WIDGETS/geometricControl.h>
#include <BALL/VIEW/WIDGETS/logView.h>
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/WIDGETS/datasetControl.h>
#include <BALL/VIEW/WIDGETS/editableScene.h>
#include <BALL/VIEW/WIDGETS/fileObserver.h>
#include <BALL/VIEW/WIDGETS/testFramework.h>
#include <BALL/VIEW/DIALOGS/pubchemDialog.h>
#include <BALL/VIEW/DIALOGS/downloadPDBFile.h>
#include <BALL/VIEW/DIALOGS/labelDialog.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>
#ifdef BALL_PYTHON_SUPPORT
# include <BALL/VIEW/WIDGETS/pyWidget.h>
#endif
#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/COMMON/version.h>
#include <QtGui/QKeyEvent>
#include <QtGui/QTreeWidget>
#ifdef BALL_COMPILER_MSVC
# include "ui_aboutDialog.h"
#else
# include "aboutDialog.h"
#endif
using namespace std;
namespace BALL
{
using namespace std;
using namespace BALL::VIEW;
Mainframe::Mainframe(QWidget* parent, const char* name)
: MainControl(parent, name, ".BALLView"),
scene_(0)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new Mainframe " << this << std::endl;
#endif
// ---------------------
// setup main window
// ---------------------
setWindowTitle("BALLView");
setWindowIcon(QPixmap(bucky_64x64_xpm));
// make sure submenus are the first
initPopupMenu(FILE_OPEN);
initPopupMenu(EDIT);
initPopupMenu(BUILD);
initPopupMenu(DISPLAY);
initPopupMenu(MOLECULARMECHANICS);
initPopupMenu(TOOLS);
#ifdef BALL_PYTHON_SUPPORT
initPopupMenu(TOOLS_PYTHON);
initPopupMenu(MainControl::USER);
#endif
initPopupMenu(WINDOWS);
initPopupMenu(MACRO);
// ---------------------
// Logstream setup -----
// ---------------------
// Log.remove(std::cout);
// Log.remove(std::cerr);
setLoggingFilename("BALLView.log");
// Display Menu
insertMenuEntry(MainControl::DISPLAY, "Toggle Fullscreen", this, SLOT(toggleFullScreen()),
Qt::ALT+Qt::Key_X);
insertPopupMenuSeparator(DISPLAY);
initPopupMenu(DISPLAY_VIEWPOINT);
new MolecularFileDialog(this, "MolecularFileDialog");
new DownloadPDBFile( this, "DownloadPDBFile", false);
new PubChemDialog(this, "PubChemDialog");
addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, "Structures"));
addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, "Representations"));
addDockWidget(Qt::TopDockWidgetArea, new DatasetControl(this, "Datasets"));
DatasetControl* dc = DatasetControl::getInstance(0);
dc->registerController(new RegularData3DController());
dc->registerController(new TrajectoryController());
dc->registerController(new VectorGridController());
dc->registerController(new DockResultController());
DatasetControl::getInstance(0)->hide();
new DemoTutorialDialog(this, "BALLViewDemo");
HelpViewer* BALL_docu = new HelpViewer(this, "BALL Docu");
addDockWidget(Qt::BottomDockWidgetArea, BALL_docu);
String dirp = getDataPath() + ".." + FileSystem::PATH_SEPARATOR + "doc" +
FileSystem::PATH_SEPARATOR + "BALL" + FileSystem::PATH_SEPARATOR;
BALL_docu->setBaseDirectory(dirp);
BALL_docu->setWhatsThisEnabled(false);
BALL_docu->setProject("BALL");
BALL_docu->setDefaultPage("index.htm");
addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu"));
new LabelDialog( this, "LabelDialog");
new MolecularStructure( this, "MolecularStructure");
addDockWidget(Qt::BottomDockWidgetArea, new LogView(this, "Logs"));
addDockWidget(Qt::BottomDockWidgetArea, new FileObserver( this, "FileObserver"));
Scene::stereoBufferSupportTest();
scene_ = new EditableScene(this, "3D View");
setCentralWidget(scene_);
setAcceptDrops(true);
new DisplayProperties( this, "DisplayProperties");
// setup the VIEW server
#ifdef BALL_HAS_ASIO
ServerWidget* server = new ServerWidget(this);
// registering object generator
MoleculeObjectCreator* object_creator = new MoleculeObjectCreator;
server->registerObjectCreator(*object_creator);
#endif
new TestFramework(this, "Test Framework");
#ifdef BALL_PYTHON_SUPPORT
addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, "Python Interpreter"));
#endif
// ---------------------
// Menus ---------------
// ---------------------
String hint;
insertMenuEntry(MainControl::FILE_OPEN, "Project", this, SLOT(loadBALLViewProjectFile()));
save_project_action_ = insertMenuEntry(MainControl::FILE, "Save Project", this,
SLOT(saveBALLViewProjectFile()));
// Help-Menu -------------------------------------------------------------------
QAction* action = 0;
action = insertMenuEntry(MainControl::HELP, "About", this, SLOT(about()));
setMenuHint(action, "Show informations on this version of BALLView");
action = insertMenuEntry(MainControl::HELP, "How to cite", this, SLOT(howToCite()));
setMenuHint(action, "Show infos on how to cite BALL and BALLView");
stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, "Abort Calculation", this,
SLOT(stopSimulation()), Qt::ALT+Qt::Key_C);
stop_simulation_action_->setEnabled(false);
insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);
setMenuHint(stop_simulation_action_, "Abort a running simulation");
Path path;
String filename = path.find("graphics/stop.png");
stop_simulation_action_->setIcon(QIcon(filename.c_str()));
complement_selection_action_ = insertMenuEntry(MainControl::EDIT, "Toggle Selection", this, SLOT(complementSelection()));
qApp->installEventFilter(this);
setStatusbarText("Ready.");
}
Mainframe::~Mainframe()
throw()
{
}
bool Mainframe::eventFilter(QObject* sender, QEvent* event)
{
if (event->type() != QEvent::KeyPress) return false;
QKeyEvent* e = dynamic_cast<QKeyEvent*>(event);
if (e->key() == Qt::Key_Escape &&
HelpViewer::getInstance(1)->isWhatsThisEnabled())
{
HelpViewer::getInstance(1)->exitWhatsThisMode();
}
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
if (widget == scene_ &&
qApp->focusWidget() != scene_)
{
scene_->keyPressEvent(e);
return true;
}
if (widget != scene_ &&
e->key() == Qt::Key_Escape)
{
scene_->switchToLastMode();
return true;
}
if (e->key() == Qt::Key_Delete &&
RTTI::isKindOf<QTreeWidget>(*sender))
{
deleteClicked();
return true;
}
if (e->key() == Qt::Key_Enter)
{
if (composite_manager_.getNumberOfComposites() == 0) return false;
if (getMolecularControlSelection().size() == 0)
{
control_selection_.push_back(*composite_manager_.begin());
}
MolecularStructure::getInstance(0)->centerCamera();
return true;
}
// check all menu entries if Alt or CTRL is pressed to enable shortcuts
if (e->key() == Qt::Key_Alt ||
e->key() == Qt::Key_Control)
{
checkMenus();
return false;
}
#ifdef BALL_PYTHON_SUPPORT
PyWidget::getInstance(0)->reactTo(*e);
e->accept();
#endif
return false;
}
void Mainframe::reset()
{
if (composites_locked_ || getRepresentationManager().updateRunning()) return;
clearData();
DisplayProperties* dp = DisplayProperties::getInstance(0);
dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
dp->selectModel(MODEL_STICK);
dp->selectColoringMethod(COLORING_ELEMENT);
dp->selectMode(DRAWING_MODE_SOLID);
dp->setTransparency(0);
dp->setSurfaceDrawingPrecision(6.5);
}
void Mainframe::howToCite()
{
HelpViewer::getInstance(1)->showHelp("tips.html", "cite");
}
void Mainframe::show()
{
// prevent multiple inserting of menu entries, by calls of showFullScreen(), ...
if (preferences_action_ != 0)
{
MainControl::show();
return;
}
QToolBar* tb = new QToolBar("Main Toolbar", this);
tb->setObjectName("Main Toolbar");
tb->setIconSize(QSize(23,23));
tb->layout()->setMargin(2);
tb->layout()->setSpacing(2);
addToolBar(Qt::TopToolBarArea, tb);
MainControl::show();
initPopupMenu(MainControl::WINDOWS)->addSeparator();
initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());
MolecularFileDialog::getInstance(0)->addToolBarEntries(tb);
DownloadPDBFile::getInstance(0)->addToolBarEntries(tb);
PubChemDialog::getInstance(0)->addToolBarEntries(tb);
Path path;
QIcon load_icon(path.find("graphics/quickload.png").c_str());
qload_action_ = new QAction(load_icon, "quickload", this);
qload_action_->setObjectName("quickload");
connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));
HelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, "tips.html#quickload");
tb->addAction(qload_action_);
QIcon save_icon(path.find("graphics/quicksave.png").c_str());
qsave_action_ = new QAction(save_icon, "quicksave", this);
qsave_action_->setObjectName("quicksave");
connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));
HelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, "tips.html#quickload");
tb->addAction(qsave_action_);
tb->addSeparator();
DisplayProperties::getInstance(0)->addToolBarEntries(tb);
MolecularStructure::getInstance(0)->addToolBarEntries(tb);
scene_->addToolBarEntries(tb);
tb->addAction(stop_simulation_action_);
tb->addAction(preferences_action_);
HelpViewer::getInstance(1)->addToolBarEntries(tb);
// we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have
// to restore the window state again!
restoreWindows();
}
void Mainframe::about()
{
// Display about dialog
QDialog w;
Ui_AboutDialog about;
about.setupUi(&w);
QString version = QString("QT ") + qVersion();
#ifdef BALL_QT_HAS_THREADS
version += "(mt)";
#endif
about.qt_version_label->setText(version);
QFont font = about.BALLView_version_label->font();
about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING);
font.setPixelSize(18);
about.BALLView_version_label->setFont(font);
about.BALL_version_label->setText(__DATE__);
w.exec();
}
}
<|endoftext|> |
<commit_before>/* MolPredictor.C
*
* Copyright (C) 2009 Marcel Schumann
*
* This file is part of QuEasy -- A Toolbox for Automated QSAR Model
* Construction and Validation.
* QuEasy 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.
*
* QuEasy is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/QSAR/registry.h>
#include <BALL/QSAR/configIO.h>
#include <fstream>
#include "version.h"
using namespace BALL::QSAR;
using namespace BALL;
using namespace std;
int main(int argc, char* argv[])
{
CommandlineParser par("MolPredictor","predict molecule activities with QSAR model", VERSION, String(__DATE__), "QuEasy (QSAR)");
par.registerParameter("i","input sd-file",INFILE,true);
par.registerParameter("mod","file containing QSAR model",INFILE,true);
par.registerParameter("o","output sd-file",OUTFILE,true);
par.registerParameter("csv","input csv-file w/ additional descriptors",INFILE);
par.registerParameter("csv_nr","no. of response variables in csv-file",INT);
par.registerFlag("sdp","use sd-properties as additional descriptors");
par.registerFlag("csv_cl","csv-file has compound (row) labels");
par.registerFlag("csv_dl","csv-file has descriptor (column) labels");
par.registerParameter("csv_sep","separator symbol in csv-file",INT);
par.registerFlag("rm", "remove input sd-file when finished");
String man = "This tool predictes the response values of compounds in the given molecule file using the specified QSAR model.\n\nInput of this tool is a molecule file (sdf,mol2,drf) and a model-file as generated by ModelCreator or FeatureSelector.\nFeatures for all molecules in the input file are generated automatically. However, if you used an additional, externally generated feature-set to generate your QSAR model, make sure to generate features in the same manner (i.e. using the same external tool with the same settings) for the molecule file to be used here and specify the csv-file with the above options.\n\nOutput of this tool (as specified by '-o') is a molecule file containing the predicted values as a property tag named 'predicted_activity'.";
par.setToolManual(man);
par.setSupportedFormats("i","sdf");
par.setSupportedFormats("mod","mod");
par.setSupportedFormats("csv","csv");
par.setSupportedFormats("o","sdf,txt");
par.parse(argc,argv);
string input = par.get("i");
string model_file = par.get("mod");
string output = par.get("o");
String csv = "";
String s = par.get("csv");
if (s!=CommandlineParser::NOT_FOUND) csv = s;
int csv_no_response = 0;
s = par.get("csv_nr");
if (s!=CommandlineParser::NOT_FOUND) csv_no_response = s.toInt();
bool csv_desc_labels = 0;
s = par.get("csv_dl");
if (s!=CommandlineParser::NOT_FOUND) csv_desc_labels = s.toInt();
bool csv_compound_labels = 0;
s = par.get("csv_cl");
if (s!=CommandlineParser::NOT_FOUND) csv_compound_labels = s.toInt();
String csv_separator = "\t";
s = par.get("csv_sep");
if (s!=CommandlineParser::NOT_FOUND) csv_separator = s;
bool read_sd_descriptors = 0;
s = par.get("sdp");
if(s!=CommandlineParser::NOT_FOUND) read_sd_descriptors = s.toBool();
bool txt_output=0;
if(output.size()>4 && output.substr(output.size()-4)==".txt")
{
txt_output=true;
}
/// read model from given file
QSARData q;
Model* m = createNewModelFromFile(model_file,q);
/// read molecules and descriptors
set<String> act;
Log.level(5) << "Will now read input-file and generate features ... "; Log.flush();
q.readSDFile(input.c_str(),act,read_sd_descriptors,0,0,1,1);
Log.level(5) << "done. " << endl << flush;
if(csv!="") q.readCSVFile(csv.c_str(),0,csv_desc_labels,csv_compound_labels,csv_separator.c_str(),csv_no_response);
/// predict acitivity of each molecule in the SD-file
vector<double> activities(q.getNoSubstances());
Size total = q.getNoSubstances();
for(unsigned int i=0;i<total;i++)
{
if(i%50==0)
{
Log.level(5) << "\tPredicting activities of compounds: " << (i+1) << "/" << total;
Log.flush();
}
vector<double>* v = q.getSubstance(i); // get UNcentered descriptor-vector of test compound
Eigen::VectorXd res = m->predict(*v,1); // transform val. data according to centering of training data
delete v;
activities[i] = res[0];
}
Log.level(5) << "\tPredicting activities of compounds: " << total << "/" << total << endl;
/// write molecules with appended activity-labels to output sd-file
if(!txt_output)
{
SDFile sd_in(input);
SDFile sd_out(output,ios::out);
Molecule* mol;
uint no_pos=0;
for(uint i=0; (mol=sd_in.read()); i++)
{
if(i%50==0)
{
Log.level(5) << "\tSaving compounds: " << (i+1) << "/" << total; Log.flush();
}
mol->setProperty("predicted_activity",activities[i]);
no_pos++;
sd_out << *mol;
delete mol;
}
Log.level(5) << "\tSaving compounds: " << total << "/" << total << endl;
}
else
{
ofstream out(output.c_str());
for(unsigned int i=0; i<activities.size(); i++)
{
out<<"mol_"<<i<<"\t"<<activities[i]<<endl;
}
}
delete m;
if (par.has("rm"))
{
File::remove(par.get("i"));
}
}
<commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/QSAR/registry.h>
#include <BALL/QSAR/configIO.h>
#include <fstream>
#include "version.h"
using namespace BALL::QSAR;
using namespace BALL;
using namespace std;
int main(int argc, char* argv[])
{
CommandlineParser par("MolPredictor","predict molecule activities with QSAR model", VERSION, String(__DATE__), "QuEasy (QSAR)");
par.registerParameter("i","input sd-file",INFILE,true);
par.registerParameter("mod","file containing QSAR model",INFILE,true);
par.registerParameter("o","output sd-file",OUTFILE,true);
par.registerParameter("csv","input csv-file w/ additional descriptors",INFILE);
par.registerParameter("csv_nr","no. of response variables in csv-file",INT);
par.registerFlag("sdp","use sd-properties as additional descriptors");
par.registerFlag("csv_cl","csv-file has compound (row) labels");
par.registerFlag("csv_dl","csv-file has descriptor (column) labels");
par.registerParameter("csv_sep","separator symbol in csv-file",INT);
par.registerFlag("rm", "remove input sd-file when finished");
String man = "This tool predictes the response values of compounds in the given molecule file using the specified QSAR model.\n\nInput of this tool is a molecule file (sdf,mol2,drf) and a model-file as generated by ModelCreator or FeatureSelector.\nFeatures for all molecules in the input file are generated automatically. However, if you used an additional, externally generated feature-set to generate your QSAR model, make sure to generate features in the same manner (i.e. using the same external tool with the same settings) for the molecule file to be used here and specify the csv-file with the above options.\n\nOutput of this tool (as specified by '-o') is a molecule file containing the predicted values as a property tag named 'predicted_activity'.";
par.setToolManual(man);
par.setSupportedFormats("i","sdf");
par.setSupportedFormats("mod","mod");
par.setSupportedFormats("csv","csv");
par.setSupportedFormats("o","sdf,txt");
par.parse(argc,argv);
string input = par.get("i");
string model_file = par.get("mod");
string output = par.get("o");
String csv = "";
String s = par.get("csv");
if (s!=CommandlineParser::NOT_FOUND) csv = s;
int csv_no_response = 0;
s = par.get("csv_nr");
if (s!=CommandlineParser::NOT_FOUND) csv_no_response = s.toInt();
bool csv_desc_labels = 0;
s = par.get("csv_dl");
if (s!=CommandlineParser::NOT_FOUND) csv_desc_labels = s.toInt();
bool csv_compound_labels = 0;
s = par.get("csv_cl");
if (s!=CommandlineParser::NOT_FOUND) csv_compound_labels = s.toInt();
String csv_separator = "\t";
s = par.get("csv_sep");
if (s!=CommandlineParser::NOT_FOUND) csv_separator = s;
bool read_sd_descriptors = 0;
s = par.get("sdp");
if(s!=CommandlineParser::NOT_FOUND) read_sd_descriptors = s.toBool();
bool txt_output=0;
if(output.size()>4 && output.substr(output.size()-4)==".txt")
{
txt_output=true;
}
/// read model from given file
QSARData q;
Model* m = createNewModelFromFile(model_file,q);
/// read molecules and descriptors
set<String> act;
Log.level(5) << "Will now read input-file and generate features ... "; Log.flush();
q.readSDFile(input.c_str(),act,read_sd_descriptors,0,0,1,1);
Log.level(5) << "done. " << endl << flush;
if(csv!="") q.readCSVFile(csv.c_str(),0,csv_desc_labels,csv_compound_labels,csv_separator.c_str(),csv_no_response);
/// predict acitivity of each molecule in the SD-file
vector<double> activities(q.getNoSubstances());
Size total = q.getNoSubstances();
for(unsigned int i=0;i<total;i++)
{
if(i%50==0)
{
Log.level(5) << "\tPredicting activities of compounds: " << (i+1) << "/" << total;
Log.flush();
}
vector<double>* v = q.getSubstance(i); // get UNcentered descriptor-vector of test compound
Eigen::VectorXd res = m->predict(*v,1); // transform val. data according to centering of training data
delete v;
activities[i] = res[0];
}
Log.level(5) << "\tPredicting activities of compounds: " << total << "/" << total << endl;
/// write molecules with appended activity-labels to output sd-file
if(!txt_output)
{
SDFile sd_in(input);
SDFile sd_out(output,ios::out);
Molecule* mol;
uint no_pos=0;
for(uint i=0; (mol=sd_in.read()); i++)
{
if(i%50==0)
{
Log.level(5) << "\tSaving compounds: " << (i+1) << "/" << total; Log.flush();
}
mol->setProperty("predicted_activity",activities[i]);
no_pos++;
sd_out << *mol;
delete mol;
}
Log.level(5) << "\tSaving compounds: " << total << "/" << total << endl;
}
else
{
ofstream out(output.c_str());
for(unsigned int i=0; i<activities.size(); i++)
{
out<<"mol_"<<i<<"\t"<<activities[i]<<endl;
}
}
delete m;
if (par.has("rm"))
{
File::remove(par.get("i"));
}
}
<|endoftext|> |
<commit_before>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#include <algorithm>
#include <memory>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "transaction/Transaction.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
namespace transaction {
/** \addtogroup Transaction
* @{
*/
/**
* @brief Class for representing a directed graph.
* Vertices are transaction ids, edges are
* wait-for relations.
*/
class DirectedGraph {
public:
typedef std::uint64_t node_id;
/**
* @brief Default constructor
*/
DirectedGraph() {}
/**
* @brief Adds node with given transaction id.
* @warning It does not check whether transaction id
* is already in the graph.
* @warning Pointer ownership will pass to the graph,
* threfore it should not be deleted.
*
* @param data Pointer to the transaction id that
* will be contained in the node.
*
* @return Id of the newly created node.
*/
inline NodeId addNode(TransactionId *data) {
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds an edge between nodes.
* @warning Does not check arguments are legit.
* It may cause out of range errors.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
*/
inline void addEdge(NodeId from_node, NodeId to_node) {
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Check whether there is a directed edge.
* @warning Does not check argument are legit.
* It may cause out of range errors.
*
* @param fromNode Id of the node that edge is originated from.
* @param toNode Id of the node that edge is ended.
*
* @return True if there is an edge, false otherwise.
*/
inline bool hasEdge(NodeId from_node, NodeId to_node) const {
return nodes_[from_node].hasOutgoingEdge(to_node);
}
/**
* @brief Get data (transaction id) contained in the node.
* @warning Does not check index validity.
*
* @param node Id of the node that the data is got from.
* @return Id of the transaction that this node contains.
*/
inline TransactionId getDataFromNode(NodeId node) const {
return nodes_[node].getData();
}
/**
* @brief Calculate how many nodes the graph has.
*
* @return The number of nodes the graph has.
*/
inline std::size_t count() const {
return nodes_.size();
}
/**
* @brief Gives the node ids that this node has edges to.
*
* @param id Id of the corresponding node.
* @return Vector of node ids that id has edges to.
*/
inline std::vector<NodeId> getAdjacentNodes(NodeId id) const {
return nodes_[id].getOutgoingEdges();
}
private:
// Class for representing a graph node.
class DirectedGraphNode {
public:
explicit DirectedGraphNode(TransactionId *data)
: data_(data) {}
inline void addOutgoingEdge(NodeId to_node) {
outgoing_edges_.insert(to_node);
}
inline bool hasOutgoingEdge(NodeId to_node) const {
return outgoing_edges_.count(to_node) == 1;
}
inline std::vector<NodeId> getOutgoingEdges() const {
std::vector<NodeId> result;
std::copy(outgoing_edges_.begin(), outgoing_edges_.end(),
std::back_inserter(result));
return result;
}
inline TransactionId getData() const {
return *(data_.get());
}
private:
// Owner pointer to transaction id.
std::unique_ptr<TransactionId> data_;
// Endpoint nodes of outgoing edges originated from this node.
std::unordered_set<NodeId> outgoing_edges_;
};
// Buffer of nodes that are created. NodeId is the index of that
// node in this buffer.
std::vector<DirectedGraphNode> nodes_;
DISALLOW_COPY_AND_ASSIGN(DirectedGraph);
};
/** @} */
} // namespace transaction
} // namespace quickstep
#endif
<commit_msg>Added addNodeUnchecked, addNodeCheckExists methods to DirectedGraph.<commit_after>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#include <algorithm>
#include <memory>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "transaction/Transaction.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
namespace transaction {
/** \addtogroup Transaction
* @{
*/
/**
* @brief Class for representing a directed graph. Vertices are
* transaction ids, edges are wait-for relations.
**/
class DirectedGraph {
public:
typedef std::uint64_t node_id;
/**
* @brief Default constructor
**/
DirectedGraph() {}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It does not check whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeUnchecked(TransactionId *data) {
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It checks whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeCheckExists(TransactionId *data) {
for (const std::vector<DirectedGraphNode>::const_iter
it = nodes_.begin(), end = nodes_.end();
it != end;
++it) {
CHECK(*data != *(it->data_));
}
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds an edge between nodes.
* @warning Does not check arguments are legit.
* It may cause out of range errors.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
*/
inline void addEdge(NodeId from_node, NodeId to_node) {
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Check whether there is a directed edge.
* @warning Does not check argument are legit.
* It may cause out of range errors.
*
* @param fromNode Id of the node that edge is originated from.
* @param toNode Id of the node that edge is ended.
* @return True if there is an edge, false otherwise.
*/
inline bool hasEdge(NodeId from_node, NodeId to_node) const {
return nodes_[from_node].hasOutgoingEdge(to_node);
}
/**
* @brief Get data (transaction id) contained in the node.
* @warning Does not check index validity.
*
* @param node Id of the node that the data is got from.
* @return Id of the transaction that this node contains.
*/
inline TransactionId getDataFromNode(NodeId node) const {
return nodes_[node].getData();
}
/**
* @brief Calculate how many nodes the graph has.
*
* @return The number of nodes the graph has.
*/
inline std::size_t count() const {
return nodes_.size();
}
/**
* @brief Gives the node ids that this node has edges to.
*
* @param id Id of the corresponding node.
* @return Vector of node ids that id has edges to.
*/
inline std::vector<NodeId> getAdjacentNodes(NodeId id) const {
return nodes_[id].getOutgoingEdges();
}
private:
// Class for representing a graph node.
class DirectedGraphNode {
public:
explicit DirectedGraphNode(TransactionId *data)
: data_(data) {}
inline void addOutgoingEdge(NodeId to_node) {
outgoing_edges_.insert(to_node);
}
inline bool hasOutgoingEdge(NodeId to_node) const {
return outgoing_edges_.count(to_node) == 1;
}
inline std::vector<NodeId> getOutgoingEdges() const {
std::vector<NodeId> result;
std::copy(outgoing_edges_.begin(), outgoing_edges_.end(),
std::back_inserter(result));
return result;
}
inline TransactionId getData() const {
return *(data_.get());
}
private:
// Owner pointer to transaction id.
std::unique_ptr<TransactionId> data_;
// Endpoint nodes of outgoing edges originated from this node.
std::unordered_set<NodeId> outgoing_edges_;
};
// Buffer of nodes that are created. NodeId is the index of that
// node in this buffer.
std::vector<DirectedGraphNode> nodes_;
DISALLOW_COPY_AND_ASSIGN(DirectedGraph);
};
/** @} */
} // namespace transaction
} // namespace quickstep
#endif
<|endoftext|> |
<commit_before>/* Copyright 2015 Yurii Litvinov and CyberTech Labs Ltd.
*
* 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 "trikFifo.h"
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <QtCore/QSocketNotifier>
#include <QtCore/QStringList>
#include <QsLog.h>
using namespace trikHal::trik;
TrikFifo::TrikFifo(const QString &fileName)
: mFileName(fileName)
, mFileDescriptor(-1)
{
}
TrikFifo::~TrikFifo()
{
close();
}
bool TrikFifo::open()
{
mFileDescriptor = ::open(mFileName.toStdString().c_str(), O_RDONLY | O_NONBLOCK);
if (mFileDescriptor == -1) {
QLOG_ERROR() << "Can't open FIFO file" << mFileName;
return false;
}
mSocketNotifier.reset(new QSocketNotifier(mFileDescriptor, QSocketNotifier::Read));
connect(mSocketNotifier.data(), &QSocketNotifier::activated, this, &TrikFifo::readFile);
mSocketNotifier->setEnabled(true);
QLOG_INFO() << "Opened FIFO file" << mFileName;
return true;
}
void TrikFifo::readFile()
{
QVector<uint8_t> bytes(4000);
mSocketNotifier->setEnabled(false);
auto bytesRead = ::read(mFileDescriptor, bytes.data(), static_cast<size_t>(bytes.size()));
if (bytesRead < 0) {
QLOG_ERROR() << "FIFO read failed: " << strerror(errno) << "in" << mFileName;
emit readError();
mSocketNotifier->setEnabled(true);
return;
}
bytes.resize(bytesRead);
emit newData(bytes);
mBuffer += QByteArray(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (mBuffer.contains("\n")) {
QStringList lines = mBuffer.split('\n', QString::KeepEmptyParts);
mBuffer = lines.last();
lines.removeLast();
for (auto &&line : lines) {
emit newLine(line);
}
}
mSocketNotifier->setEnabled(true);
}
bool TrikFifo::close()
{
if (mFileDescriptor != -1) {
bool result = ::close(mFileDescriptor) == 0;
mFileDescriptor = -1;
return result;
}
return false;
}
QString TrikFifo::fileName()
{
return mFileName;
}
<commit_msg>Ignore EAGAIN error (#686)<commit_after>/* Copyright 2015 Yurii Litvinov and CyberTech Labs Ltd.
*
* 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 "trikFifo.h"
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <QtCore/QSocketNotifier>
#include <QtCore/QStringList>
#include <QsLog.h>
using namespace trikHal::trik;
TrikFifo::TrikFifo(const QString &fileName)
: mFileName(fileName)
, mFileDescriptor(-1)
{
}
TrikFifo::~TrikFifo()
{
close();
}
bool TrikFifo::open()
{
mFileDescriptor = ::open(mFileName.toStdString().c_str(), O_RDONLY | O_NONBLOCK);
if (mFileDescriptor == -1) {
QLOG_ERROR() << "Can't open FIFO file" << mFileName;
return false;
}
mSocketNotifier.reset(new QSocketNotifier(mFileDescriptor, QSocketNotifier::Read));
connect(mSocketNotifier.data(), &QSocketNotifier::activated, this, &TrikFifo::readFile);
mSocketNotifier->setEnabled(true);
QLOG_INFO() << "Opened FIFO file" << mFileName;
return true;
}
void TrikFifo::readFile()
{
QVector<uint8_t> bytes(4000);
mSocketNotifier->setEnabled(false);
auto bytesRead = ::read(mFileDescriptor, bytes.data(), static_cast<size_t>(bytes.size()));
if (bytesRead < 0) {
if (errno != EAGAIN) {
QLOG_ERROR() << "FIFO read failed: " << strerror(errno) << "in" << mFileName;
emit readError();
}
mSocketNotifier->setEnabled(true);
return;
}
bytes.resize(bytesRead);
emit newData(bytes);
mBuffer += QByteArray(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (mBuffer.contains("\n")) {
QStringList lines = mBuffer.split('\n', QString::KeepEmptyParts);
mBuffer = lines.last();
lines.removeLast();
for (auto &&line : lines) {
emit newLine(line);
}
}
mSocketNotifier->setEnabled(true);
}
bool TrikFifo::close()
{
if (mFileDescriptor != -1) {
bool result = ::close(mFileDescriptor) == 0;
mFileDescriptor = -1;
return result;
}
return false;
}
QString TrikFifo::fileName()
{
return mFileName;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/thread/posix/PosixConditionVariable.h>
#include <stingraykit/ScopeExit.h>
#include <stingraykit/Singleton.h>
#include <stingraykit/reference.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/TimeEngine.h>
#include <stingraykit/time/posix/utils.h>
#include <errno.h>
namespace stingray
{
struct CancellationHolder : public CancellationRegistratorBase
{
struct CancellationHandler : public ICancellationHandler
{
private:
const PosixMutex& _mutex;
PosixConditionVariable& _cond;
public:
CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond) : _mutex(mutex), _cond(cond)
{ }
virtual ~CancellationHandler()
{ }
virtual void Cancel()
{
MutexLock l(_mutex);
_cond.Broadcast();
}
const PosixMutex& GetMutex() const
{ return _mutex; }
};
private:
CancellationHandler _handler;
public:
CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token) :
CancellationRegistratorBase(token), _handler(mutex, cond)
{ Register(_handler); }
~CancellationHolder()
{
if (TryUnregister(_handler))
return;
MutexUnlock ul(_handler.GetMutex());
Unregister(_handler);
}
};
class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
{
STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);
private:
pthread_condattr_t _condAttr;
private:
PosixConditionVariableAttr()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
}
public:
~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }
const pthread_condattr_t& Get() const { return _condAttr; }
};
PosixConditionVariable::PosixConditionVariable()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
}
PosixConditionVariable::~PosixConditionVariable()
{
pthread_cond_destroy(&_cond);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return;
Wait(mutex);
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return true;
return TimedWait(mutex, interval);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex) const
{
int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_wait", ret));
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
{
timespec t = { };
posix::timespec_now(CLOCK_MONOTONIC, &t);
posix::timespec_add(&t, interval);
int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
STINGRAYKIT_CHECK(ret == 0 || ret == ETIMEDOUT, SystemException("pthread_cond_timedwait", ret));
return ret != ETIMEDOUT;
}
void PosixConditionVariable::Broadcast()
{
int ret = pthread_cond_broadcast(&_cond);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_broadcast", ret));
}
}
<commit_msg>PosixConditionVariable: dropped excess includes, fixed some style<commit_after>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/thread/posix/PosixConditionVariable.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/utils.h>
#include <stingraykit/Singleton.h>
#include <errno.h>
namespace stingray
{
class CancellationHolder : public CancellationRegistratorBase
{
class CancellationHandler : public ICancellationHandler
{
private:
const PosixMutex& _mutex;
PosixConditionVariable& _cond;
public:
CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond)
: _mutex(mutex), _cond(cond)
{ }
virtual ~CancellationHandler()
{ }
virtual void Cancel()
{
MutexLock l(_mutex);
_cond.Broadcast();
}
const PosixMutex& GetMutex() const
{ return _mutex; }
};
private:
CancellationHandler _handler;
public:
CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token)
: CancellationRegistratorBase(token), _handler(mutex, cond)
{ Register(_handler); }
~CancellationHolder()
{
if (TryUnregister(_handler))
return;
MutexUnlock ul(_handler.GetMutex());
Unregister(_handler);
}
};
class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
{
STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);
private:
pthread_condattr_t _condAttr;
private:
PosixConditionVariableAttr()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
}
public:
~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }
const pthread_condattr_t& Get() const { return _condAttr; }
};
PosixConditionVariable::PosixConditionVariable()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
}
PosixConditionVariable::~PosixConditionVariable()
{
pthread_cond_destroy(&_cond);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return;
Wait(mutex);
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return true;
return TimedWait(mutex, interval);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex) const
{
int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_wait", ret));
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
{
timespec t = { };
posix::timespec_now(CLOCK_MONOTONIC, &t);
posix::timespec_add(&t, interval);
int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
STINGRAYKIT_CHECK(ret == 0 || ret == ETIMEDOUT, SystemException("pthread_cond_timedwait", ret));
return ret != ETIMEDOUT;
}
void PosixConditionVariable::Broadcast()
{
int ret = pthread_cond_broadcast(&_cond);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_broadcast", ret));
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_output.h"
#include "media/audio/simple_sources.h"
#include "testing/gtest/include/gtest/gtest.h"
// This class allows to find out if the callbacks are occurring as
// expected and if any error has been reported.
class TestSourceBasic : public AudioOutputStream::AudioSourceCallback {
public:
explicit TestSourceBasic()
: callback_count_(0),
had_error_(0),
was_closed_(0) {
}
// AudioSourceCallback::OnMoreData implementation:
virtual size_t OnMoreData(AudioOutputStream* stream,
void* dest, size_t max_size) {
++callback_count_;
// Touch the first byte to make sure memory is good.
if (max_size)
reinterpret_cast<char*>(dest)[0] = 1;
return max_size;
}
// AudioSourceCallback::OnClose implementation:
virtual void OnClose(AudioOutputStream* stream) {
++was_closed_;
}
// AudioSourceCallback::OnError implementation:
virtual void OnError(AudioOutputStream* stream, int code) {
++had_error_;
}
// Returns how many times OnMoreData() has been called.
int callback_count() const {
return callback_count_;
}
// Returns how many times the OnError callback was called.
int had_error() const {
return had_error_;
}
void set_error(bool error) {
had_error_ += error ? 1 : 0;
}
// Returns how many times the OnClose callback was called.
int was_closed() const {
return was_closed_;
}
private:
int callback_count_;
int had_error_;
int was_closed_;
};
// Specializes TestSourceBasic to detect that the AudioStream is using
// double buffering correctly.
class TestSourceDoubleBuffer : public TestSourceBasic {
public:
TestSourceDoubleBuffer() {
buffer_address_[0] = NULL;
buffer_address_[1] = NULL;
}
// Override of TestSourceBasic::OnMoreData.
virtual size_t OnMoreData(AudioOutputStream* stream,
void* dest, size_t max_size) {
// Call the base, which increments the callback_count_.
TestSourceBasic::OnMoreData(stream, dest, max_size);
if (callback_count() % 2) {
set_error(!CompareExistingIfNotNULL(1, dest));
} else {
set_error(!CompareExistingIfNotNULL(0, dest));
}
if (callback_count() > 2) {
set_error(buffer_address_[0] == buffer_address_[1]);
}
return max_size;
}
private:
bool CompareExistingIfNotNULL(size_t index, void* address) {
void*& entry = buffer_address_[index];
if (!entry)
entry = address;
return (entry == address);
}
void* buffer_address_[2];
};
// ============================================================================
// Validate that the AudioManager::AUDIO_MOCK callbacks work.
TEST(WinAudioTest, MockStreamBasicCallbacks) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_MOCK, 2, 8000, 8);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(256));
TestSourceBasic source;
oas->Start(&source);
EXPECT_GT(source.callback_count(), 0);
oas->Stop();
oas->Close();
EXPECT_EQ(0, source.had_error());
EXPECT_EQ(1, source.was_closed());
}
// Validate that the SineWaveAudioSource writes the expected values for
// the FORMAT_16BIT_MONO. The values are carefully selected so rounding issues
// do not affect the result. We also test that AudioManager::GetLastMockBuffer
// works.
TEST(WinAudioTest, SineWaveAudio16MonoTest) {
const size_t samples = 1024;
const size_t bytes_per_sample = 2;
const int freq = 200;
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
freq, AudioManager::kTelephoneSampleRate);
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_MOCK, 1,
AudioManager::kTelephoneSampleRate,
bytes_per_sample * 2);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(samples * bytes_per_sample));
oas->Start(&source);
oas->Stop();
oas->Close();
const int16* last_buffer =
reinterpret_cast<const int16*>(audio_man->GetLastMockBuffer());
ASSERT_TRUE(NULL != last_buffer);
size_t half_period = AudioManager::kTelephoneSampleRate / (freq * 2);
// Spot test positive incursion of sine wave.
EXPECT_EQ(0, last_buffer[0]);
EXPECT_EQ(5126, last_buffer[1]);
EXPECT_TRUE(last_buffer[1] < last_buffer[2]);
EXPECT_TRUE(last_buffer[2] < last_buffer[3]);
// Spot test negative incursion of sine wave.
EXPECT_EQ(0, last_buffer[half_period]);
EXPECT_EQ(-5126, last_buffer[half_period + 1]);
EXPECT_TRUE(last_buffer[half_period + 1] > last_buffer[half_period + 2]);
EXPECT_TRUE(last_buffer[half_period + 2] > last_buffer[half_period + 3]);
}
// ===========================================================================
// Validation of AudioManager::AUDIO_PCM_LINEAR
// Test that can it be created and closed.
TEST(WinAudioTest, PCMWaveStreamGetAndClose) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 2, 8000, 16);
ASSERT_TRUE(NULL != oas);
oas->Close();
}
// Test that it can be opened and closed.
TEST(WinAudioTest, PCMWaveStreamOpenAndClose) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 2, 8000, 16);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(1024));
oas->Close();
}
// Test that it uses the double buffers correctly. Because it uses the actual
// audio device, you might hear a short pop noise for a short time.
TEST(WinAudioTest, PCMWaveStreamDoubleBuffer) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1, 16000, 16);
ASSERT_TRUE(NULL != oas);
TestSourceDoubleBuffer test_double_buffer;
EXPECT_TRUE(oas->Open(512));
oas->Start(&test_double_buffer);
::Sleep(300);
EXPECT_GT(test_double_buffer.callback_count(), 2);
EXPECT_FALSE(test_double_buffer.had_error());
oas->Stop();
::Sleep(1000);
oas->Close();
}
// This test produces actual audio for 1.5 seconds on the default wave
// device at 44.1K s/sec. Parameters have been chosen carefully so you should
// not hear pops or noises while the sound is playing.
TEST(WinAudioTest, PCMWaveStreamPlay200HzTone44Kss) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1,
AudioManager::kAudioCDSampleRate, 16);
ASSERT_TRUE(NULL != oas);
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
200.0, AudioManager::kAudioCDSampleRate);
size_t bytes_100_ms = (AudioManager::kAudioCDSampleRate / 10) * 2;
EXPECT_TRUE(oas->Open(bytes_100_ms));
oas->Start(&source);
::Sleep(1500);
oas->Stop();
oas->Close();
}
// This test produces actual audio for for 1.5 seconds on the default wave
// device at 22K s/sec. Parameters have been chosen carefully so you should
// not hear pops or noises while the sound is playing.
TEST(WinAudioTest, PCMWaveStreamPlay200HzTone22Kss) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1,
AudioManager::kAudioCDSampleRate/2, 16);
ASSERT_TRUE(NULL != oas);
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
200.0, AudioManager::kAudioCDSampleRate/2);
size_t bytes_100_ms = (AudioManager::kAudioCDSampleRate / 20) * 2;
EXPECT_TRUE(oas->Open(bytes_100_ms));
oas->Start(&source);
::Sleep(1500);
oas->Stop();
oas->Close();
}
<commit_msg>disable failing media unit tests<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_output.h"
#include "media/audio/simple_sources.h"
#include "testing/gtest/include/gtest/gtest.h"
// This class allows to find out if the callbacks are occurring as
// expected and if any error has been reported.
class TestSourceBasic : public AudioOutputStream::AudioSourceCallback {
public:
explicit TestSourceBasic()
: callback_count_(0),
had_error_(0),
was_closed_(0) {
}
// AudioSourceCallback::OnMoreData implementation:
virtual size_t OnMoreData(AudioOutputStream* stream,
void* dest, size_t max_size) {
++callback_count_;
// Touch the first byte to make sure memory is good.
if (max_size)
reinterpret_cast<char*>(dest)[0] = 1;
return max_size;
}
// AudioSourceCallback::OnClose implementation:
virtual void OnClose(AudioOutputStream* stream) {
++was_closed_;
}
// AudioSourceCallback::OnError implementation:
virtual void OnError(AudioOutputStream* stream, int code) {
++had_error_;
}
// Returns how many times OnMoreData() has been called.
int callback_count() const {
return callback_count_;
}
// Returns how many times the OnError callback was called.
int had_error() const {
return had_error_;
}
void set_error(bool error) {
had_error_ += error ? 1 : 0;
}
// Returns how many times the OnClose callback was called.
int was_closed() const {
return was_closed_;
}
private:
int callback_count_;
int had_error_;
int was_closed_;
};
// Specializes TestSourceBasic to detect that the AudioStream is using
// double buffering correctly.
class TestSourceDoubleBuffer : public TestSourceBasic {
public:
TestSourceDoubleBuffer() {
buffer_address_[0] = NULL;
buffer_address_[1] = NULL;
}
// Override of TestSourceBasic::OnMoreData.
virtual size_t OnMoreData(AudioOutputStream* stream,
void* dest, size_t max_size) {
// Call the base, which increments the callback_count_.
TestSourceBasic::OnMoreData(stream, dest, max_size);
if (callback_count() % 2) {
set_error(!CompareExistingIfNotNULL(1, dest));
} else {
set_error(!CompareExistingIfNotNULL(0, dest));
}
if (callback_count() > 2) {
set_error(buffer_address_[0] == buffer_address_[1]);
}
return max_size;
}
private:
bool CompareExistingIfNotNULL(size_t index, void* address) {
void*& entry = buffer_address_[index];
if (!entry)
entry = address;
return (entry == address);
}
void* buffer_address_[2];
};
// ============================================================================
// Validate that the AudioManager::AUDIO_MOCK callbacks work.
TEST(WinAudioTest, MockStreamBasicCallbacks) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_MOCK, 2, 8000, 8);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(256));
TestSourceBasic source;
oas->Start(&source);
EXPECT_GT(source.callback_count(), 0);
oas->Stop();
oas->Close();
EXPECT_EQ(0, source.had_error());
EXPECT_EQ(1, source.was_closed());
}
// Validate that the SineWaveAudioSource writes the expected values for
// the FORMAT_16BIT_MONO. The values are carefully selected so rounding issues
// do not affect the result. We also test that AudioManager::GetLastMockBuffer
// works.
TEST(WinAudioTest, SineWaveAudio16MonoTest) {
const size_t samples = 1024;
const size_t bytes_per_sample = 2;
const int freq = 200;
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
freq, AudioManager::kTelephoneSampleRate);
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_MOCK, 1,
AudioManager::kTelephoneSampleRate,
bytes_per_sample * 2);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(samples * bytes_per_sample));
oas->Start(&source);
oas->Stop();
oas->Close();
const int16* last_buffer =
reinterpret_cast<const int16*>(audio_man->GetLastMockBuffer());
ASSERT_TRUE(NULL != last_buffer);
size_t half_period = AudioManager::kTelephoneSampleRate / (freq * 2);
// Spot test positive incursion of sine wave.
EXPECT_EQ(0, last_buffer[0]);
EXPECT_EQ(5126, last_buffer[1]);
EXPECT_TRUE(last_buffer[1] < last_buffer[2]);
EXPECT_TRUE(last_buffer[2] < last_buffer[3]);
// Spot test negative incursion of sine wave.
EXPECT_EQ(0, last_buffer[half_period]);
EXPECT_EQ(-5126, last_buffer[half_period + 1]);
EXPECT_TRUE(last_buffer[half_period + 1] > last_buffer[half_period + 2]);
EXPECT_TRUE(last_buffer[half_period + 2] > last_buffer[half_period + 3]);
}
// ===========================================================================
// Validation of AudioManager::AUDIO_PCM_LINEAR
// Test that can it be created and closed.
TEST(WinAudioTest, PCMWaveStreamGetAndClose) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 2, 8000, 16);
ASSERT_TRUE(NULL != oas);
oas->Close();
}
// Test that it can be opened and closed.
TEST(WinAudioTest, DISABLED_PCMWaveStreamOpenAndClose) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 2, 8000, 16);
ASSERT_TRUE(NULL != oas);
EXPECT_TRUE(oas->Open(1024));
oas->Close();
}
// Test that it uses the double buffers correctly. Because it uses the actual
// audio device, you might hear a short pop noise for a short time.
TEST(WinAudioTest, DISABLED_PCMWaveStreamDoubleBuffer) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1, 16000, 16);
ASSERT_TRUE(NULL != oas);
TestSourceDoubleBuffer test_double_buffer;
EXPECT_TRUE(oas->Open(512));
oas->Start(&test_double_buffer);
::Sleep(300);
EXPECT_GT(test_double_buffer.callback_count(), 2);
EXPECT_FALSE(test_double_buffer.had_error());
oas->Stop();
::Sleep(1000);
oas->Close();
}
// This test produces actual audio for 1.5 seconds on the default wave
// device at 44.1K s/sec. Parameters have been chosen carefully so you should
// not hear pops or noises while the sound is playing.
TEST(WinAudioTest, DISABLED_PCMWaveStreamPlay200HzTone44Kss) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1,
AudioManager::kAudioCDSampleRate, 16);
ASSERT_TRUE(NULL != oas);
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
200.0, AudioManager::kAudioCDSampleRate);
size_t bytes_100_ms = (AudioManager::kAudioCDSampleRate / 10) * 2;
EXPECT_TRUE(oas->Open(bytes_100_ms));
oas->Start(&source);
::Sleep(1500);
oas->Stop();
oas->Close();
}
// This test produces actual audio for for 1.5 seconds on the default wave
// device at 22K s/sec. Parameters have been chosen carefully so you should
// not hear pops or noises while the sound is playing.
TEST(WinAudioTest, DISABLED_PCMWaveStreamPlay200HzTone22Kss) {
AudioManager* audio_man = AudioManager::GetAudioManager();
ASSERT_TRUE(NULL != audio_man);
AudioOutputStream* oas =
audio_man->MakeAudioStream(AudioManager::AUDIO_PCM_LINEAR, 1,
AudioManager::kAudioCDSampleRate/2, 16);
ASSERT_TRUE(NULL != oas);
SineWaveAudioSource source(SineWaveAudioSource::FORMAT_16BIT_LINEAR_PCM, 1,
200.0, AudioManager::kAudioCDSampleRate/2);
size_t bytes_100_ms = (AudioManager::kAudioCDSampleRate / 20) * 2;
EXPECT_TRUE(oas->Open(bytes_100_ms));
oas->Start(&source);
::Sleep(1500);
oas->Stop();
oas->Close();
}
<|endoftext|> |
<commit_before>// MFEM Example 1
//
// Compile with: make ex1
//
// Sample runs: ex1 -m ../data/square-disc.mesh
// ex1 -m ../data/star.mesh
// ex1 -m ../data/escher.mesh
// ex1 -m ../data/fichera.mesh
// ex1 -m ../data/square-disc-p2.vtk -o 2
// ex1 -m ../data/square-disc-p3.mesh -o 3
// ex1 -m ../data/square-disc-nurbs.mesh -o -1
// ex1 -m ../data/disc-nurbs.mesh -o -1
// ex1 -m ../data/pipe-nurbs.mesh -o -1
// ex1 -m ../data/star-surf.mesh
// ex1 -m ../data/square-disc-surf.mesh
// ex1 -m ../data/inline-segment.mesh
// ex1 -m ../data/amr-quad.mesh
// ex1 -m ../data/amr-hex.mesh
// ex1 -m ../data/fichera-amr.mesh
// ex1 -m ../data/mobius-strip.mesh
// ex1 -m ../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = -1;
bool static_cond = false;
bool visualization = 1;
bool ibp = true;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&ibp, "-ibp", "--ibp", "-no-ibp",
"--no-ibp",
"Enable or disable integration by parts.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file. We can handle triangular,
// quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
// the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 3. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 50,000
// elements.
/* {
int ref_levels =
(int)floor(log(5000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
*/
// 4. Define a finite element space on the mesh. Here we use continuous
// Lagrange finite elements of the specified order. If order < 1, we
// instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec = NULL;
NURBSExtension *NURBSext = NULL;
if (order <= 0)
{
if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
fec = new H1_FECollection(order = 1, dim);
}
}
else
{
if (mesh->NURBSext)
{
fec = new NURBSFECollection(order);
NURBSext = new NURBSExtension(mesh->NURBSext, order);
}
else
{
fec = new H1_FECollection(order, dim);
}
}
/*
if (order > 0)
{
fec = new H1_FECollection(order, dim);
}
else if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
fec = new H1_FECollection(order = 1, dim);
}*/
FiniteElementSpace *fespace = new FiniteElementSpace(mesh, NURBSext, fec);
cout << "Number of finite element unknowns: "
<< fespace->GetTrueVSize() << endl;
// 5. Determine the list of true (i.e. conforming) essential boundary dofs.
// In this example, the boundary conditions are defined by marking all
// the boundary attributes from the mesh as essential (Dirichlet) and
// converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (mesh->bdr_attributes.Size())
{
Array<int> ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 1;
// ess_bdr[0] = 0;
// ess_bdr[1] = 1;
ess_bdr.Print();
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 6. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system, which in this case is (1,phi_i) where phi_i are
// the basis functions in the finite element fespace.
LinearForm *b = new LinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
// Array<int> neu_bdr(mesh->bdr_attributes.Max());
// neu_bdr[0] = 1;
// neu_bdr[1] = 0;
// M->AddBoundaryIntegrator(new BoundaryMassIntegrator(*oog), fs_bdr);
// b->AddBoundaryIntegrator(new BoundaryLFIntegrator(one));//,neu_bdr);
// ConstantCoefficient zero(0.0);
// b->AddBdrFaceIntegrator(new BoundaryLFIntegrator(zero));//,neu_bdr);
b->Assemble();
// 7. Define the solution vector x as a finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
GridFunction x(fespace);
x = 0.0;
// 8. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
BilinearForm *a = new BilinearForm(fespace);
if (ibp)
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
else
{
a->AddDomainIntegrator(new Diffusion2Integrator(one));
}
// 9. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
ess_tdof_list.Print();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
B.Print();
//A.Print();
for (int i = 0; i < ess_tdof_list.Size(); i++)
{
A.EliminateRowCol(ess_tdof_list[i]);
}
A.Print();
cout << "Size of linear system: " << A.Height() << endl;
#ifndef MFEM_USE_SUITESPARSE
// 10. Define a simple symmetric Gauss-Seidel preconditioner and use it to
// solve the system A X = B with PCG.
DSmoother M(A);
GMRES(A, M, B, X, 1, 200,100, 1e-12, 0.0);
#else
// 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
UMFPackSolver umf_solver;
umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
umf_solver.SetOperator(A);
umf_solver.Mult(B, X);
#endif
X.Print();
// 11. Recover the solution as a finite element grid function.
a->RecoverFEMSolution(X, *b, x);
x.Print();
// 12 a. Save the refined mesh and the solution.
// This output can be viewed later using
// GLVis: "glvis -m refined.mesh -g sol.gf"
// visit: "visit -o Example1_000000.mfem_root"
ofstream mesh_ofs("refined.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
VisItDataCollection visit_dc("Example1", mesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 13. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 14. Free the used memory.
delete a;
delete b;
delete fespace;
if (order > 0) { delete fec; }
delete mesh;
return 0;
}
<commit_msg>Make ex1 work again<commit_after>// MFEM Example 1
//
// Compile with: make ex1
//
// Sample runs: ex1 -m ../data/square-disc.mesh
// ex1 -m ../data/star.mesh
// ex1 -m ../data/escher.mesh
// ex1 -m ../data/fichera.mesh
// ex1 -m ../data/square-disc-p2.vtk -o 2
// ex1 -m ../data/square-disc-p3.mesh -o 3
// ex1 -m ../data/square-disc-nurbs.mesh -o -1
// ex1 -m ../data/disc-nurbs.mesh -o -1
// ex1 -m ../data/pipe-nurbs.mesh -o -1
// ex1 -m ../data/star-surf.mesh
// ex1 -m ../data/square-disc-surf.mesh
// ex1 -m ../data/inline-segment.mesh
// ex1 -m ../data/amr-quad.mesh
// ex1 -m ../data/amr-hex.mesh
// ex1 -m ../data/fichera-amr.mesh
// ex1 -m ../data/mobius-strip.mesh
// ex1 -m ../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = -1;
bool static_cond = false;
bool visualization = 1;
bool ibp = true;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&ibp, "-ibp", "--ibp", "-no-ibp",
"--no-ibp",
"Enable or disable integration by parts.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file. We can handle triangular,
// quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
// the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 3. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 50,000
// elements.
/* {
int ref_levels =
(int)floor(log(5000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
*/
// 4. Define a finite element space on the mesh. Here we use continuous
// Lagrange finite elements of the specified order. If order < 1, we
// instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec = NULL;
NURBSExtension *NURBSext = NULL;
if (order <= 0)
{
if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
fec = new H1_FECollection(order = 1, dim);
}
}
else
{
if (mesh->NURBSext)
{
fec = new NURBSFECollection(order);
NURBSext = new NURBSExtension(mesh->NURBSext, order);
}
else
{
fec = new H1_FECollection(order, dim);
}
}
/*
if (order > 0)
{
fec = new H1_FECollection(order, dim);
}
else if (mesh->GetNodes())
{
fec = mesh->GetNodes()->OwnFEC();
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
fec = new H1_FECollection(order = 1, dim);
}*/
FiniteElementSpace *fespace = new FiniteElementSpace(mesh, NURBSext, fec);
cout << "Number of finite element unknowns: "
<< fespace->GetTrueVSize() << endl;
// 5. Determine the list of true (i.e. conforming) essential boundary dofs.
// In this example, the boundary conditions are defined by marking all
// the boundary attributes from the mesh as essential (Dirichlet) and
// converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (mesh->bdr_attributes.Size())
{
Array<int> ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 1;
// ess_bdr[0] = 0;
// ess_bdr[1] = 1;
ess_bdr.Print();
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 6. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system, which in this case is (1,phi_i) where phi_i are
// the basis functions in the finite element fespace.
LinearForm *b = new LinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
// Array<int> neu_bdr(mesh->bdr_attributes.Max());
// neu_bdr[0] = 1;
// neu_bdr[1] = 0;
// M->AddBoundaryIntegrator(new BoundaryMassIntegrator(*oog), fs_bdr);
// b->AddBoundaryIntegrator(new BoundaryLFIntegrator(one));//,neu_bdr);
// ConstantCoefficient zero(0.0);
// b->AddBdrFaceIntegrator(new BoundaryLFIntegrator(zero));//,neu_bdr);
b->Assemble();
// 7. Define the solution vector x as a finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
GridFunction x(fespace);
x = 0.0;
// 8. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
BilinearForm *a = new BilinearForm(fespace);
if (ibp)
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
else
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
// 9. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
ess_tdof_list.Print();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
B.Print();
//A.Print();
for (int i = 0; i < ess_tdof_list.Size(); i++)
{
A.EliminateRowCol(ess_tdof_list[i]);
}
A.Print();
cout << "Size of linear system: " << A.Height() << endl;
#ifndef MFEM_USE_SUITESPARSE
// 10. Define a simple symmetric Gauss-Seidel preconditioner and use it to
// solve the system A X = B with PCG.
DSmoother M(A);
GMRES(A, M, B, X, 1, 200,100, 1e-12, 0.0);
#else
// 10. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
UMFPackSolver umf_solver;
umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
umf_solver.SetOperator(A);
umf_solver.Mult(B, X);
#endif
X.Print();
// 11. Recover the solution as a finite element grid function.
a->RecoverFEMSolution(X, *b, x);
x.Print();
// 12 a. Save the refined mesh and the solution.
// This output can be viewed later using
// GLVis: "glvis -m refined.mesh -g sol.gf"
// visit: "visit -o Example1_000000.mfem_root"
ofstream mesh_ofs("refined.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
VisItDataCollection visit_dc("Example1", mesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 13. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 14. Free the used memory.
delete a;
delete b;
delete fespace;
if (order > 0) { delete fec; }
delete mesh;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>dba33b: solaris compiler didn't like a ;<commit_after><|endoftext|> |
<commit_before>
/**************************************************************************
* Copyright(c) 1998-2000, 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. *
**************************************************************************/
#include <TTree.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include <TArrayI.h>
#include <TError.h>
#include <TH1F.h>
#include <TGraph.h>
#include "AliLog.h"
#include "AliSTARTDigitizer.h"
#include "AliSTART.h"
#include "AliSTARThit.h"
#include "AliSTARTdigit.h"
#include "AliRunDigitizer.h"
#include <AliDetector.h>
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
#include "AliSTARTParameters.h"
#include "AliCDBLocal.h"
#include "AliCDBStorage.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
ClassImp(AliSTARTDigitizer)
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager),
fSTART(0),
fHits(0),
fdigits(0),
ftimeCFD(0),
ftimeLED(0),
fADC(0),
fADC0(0)
{
// ctor which should be used
AliDebug(1,"processed");
fSTART = 0;
fHits = 0;
fdigits = 0;
ftimeCFD = new TArrayI(24);
fADC = new TArrayI(24);
ftimeLED = new TArrayI(24);
fADC0 = new TArrayI(24);
}
//------------------------------------------------------------------------
AliSTARTDigitizer::~AliSTARTDigitizer()
{
// Destructor
AliDebug(1,"START");
delete ftimeCFD;
delete fADC;
delete ftimeLED;
delete fADC0;
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::Init()
{
// Initialization
AliDebug(1," Init");
return kTRUE;
}
//---------------------------------------------------------------------
void AliSTARTDigitizer::Exec(Option_t* /*option*/)
{
/*
Produde digits from hits
digits is TObject and includes
We are writing array if left & right TDC
left & right ADC (will need for slow simulation)
TOF first particle left & right
mean time and time difference (vertex position)
*/
//output loader
AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
AliLoader * pOutStartLoader = outRL->GetLoader("STARTLoader");
AliDebug(1,"start...");
//input loader
//
// From hits to digits
//
Int_t hit, nhits;
Int_t countE[24];
Int_t volume, pmt, trCFD, trLED;
Float_t sl, qt;
Int_t bestRightTDC, bestLeftTDC, qtCh;
Float_t time[24], besttime[24], timeGaus[24] ;
//Q->T-> coefficients !!!! should be asked!!!
Float_t gain[24],timeDelayCFD[24], timeDelayLED[24];
Int_t threshold =50; //photoelectrons
Float_t zdetA, zdetC;
Int_t sumMultCoeff = 25;
TObjArray slewingLED;
TObjArray slewingRec;
AliSTARTParameters* param = AliSTARTParameters::Instance();
param->Init();
Int_t ph2Mip = param->GetPh2Mip();
Int_t channelWidth = param->GetChannelWidth() ;
Float_t delayVertex = param->GetTimeDelayTVD();
for (Int_t i=0; i<24; i++){
timeDelayCFD[i] = param->GetTimeDelayCFD(i);
timeDelayLED[i] = param->GetTimeDelayLED(i);
gain[i] = param->GetGain(i);
TGraph* gr = param ->GetSlew(i);
slewingLED.AddAtAndExpand(gr,i);
TGraph* gr1 = param ->GetSlewRec(i);
slewingRec.AddAtAndExpand(gr1,i);
TGraph* grEff = param ->GetPMTeff(i);
fEffPMT.AddAtAndExpand(grEff,i);
}
zdetC = param->GetZposition(0);
zdetA = param->GetZposition(1);
AliSTARThit *startHit;
TBranch *brHits=0;
Int_t nFiles=fManager->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {
if (inputFile < nFiles-1) {
AliWarning(Form("ignoring input stream %d", inputFile));
continue;
}
Float_t besttimeright=99999.;
Float_t besttimeleft=99999.;
Int_t pmtBestRight=9999;
Int_t pmtBestLeft=9999;
Int_t timeDiff=999, meanTime=0;
Int_t sumMult =0;// fSumMult=0;
bestRightTDC = 99999; bestLeftTDC = 99999;
ftimeCFD -> Reset();
fADC -> Reset();
fADC0 -> Reset();
ftimeLED ->Reset();
for (Int_t i0=0; i0<24; i0++)
{
time[i0]=besttime[i0]=timeGaus[i0]=99999; countE[i0]=0;
}
AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
AliLoader * pInStartLoader = inRL->GetLoader("STARTLoader");
if (!inRL->GetAliRun()) inRL->LoadgAlice();
AliSTART *fSTART = (AliSTART*)inRL ->GetAliRun()->GetDetector("START");
//read Hits
pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
TClonesArray *fHits = fSTART->Hits ();
TTree *th = pInStartLoader->TreeH();
brHits = th->GetBranch("START");
if (brHits) {
fSTART->SetHitsAddressBranch(brHits);
}else{
AliError("Branch START hit not found");
exit(111);
}
Int_t ntracks = (Int_t) th->GetEntries();
if (ntracks<=0) return;
// Start loop on tracks in the hits containers
for (Int_t track=0; track<ntracks;track++) {
brHits->GetEntry(track);
nhits = fHits->GetEntriesFast();
for (hit=0;hit<nhits;hit++)
{
startHit = (AliSTARThit*) fHits->UncheckedAt(hit);
if (!startHit) {
AliError("The unchecked hit doesn't exist");
break;
}
pmt=startHit->Pmt();
Int_t numpmt=pmt-1;
Double_t e=startHit->Etot();
volume = startHit->Volume();
if(e>0 && RegisterPhotoE(numpmt,e)) {
countE[numpmt]++;
besttime[numpmt] = startHit->Time();
if(besttime[numpmt]<time[numpmt])
{
time[numpmt]=besttime[numpmt];
}
} //photoelectron accept
} //hits loop
} //track loop
//spread time right&left by 25ps && besttime
Float_t c = 0.0299792; // cm/ps
Float_t koef=(zdetA-zdetC)/c; //correction position difference by cable
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25)+koef;
if(timeGaus[ipmt]<besttimeleft){
besttimeleft=timeGaus[ipmt]; //timeleft
pmtBestLeft=ipmt;}
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeright) {
besttimeright=timeGaus[ipmt]; //timeright
pmtBestRight=ipmt;}
}
}
//folding with alignmentz position distribution
if( besttimeleft > 10000. && besttimeleft <15000)
bestLeftTDC=Int_t ((besttimeleft+1000*timeDelayCFD[pmtBestLeft])
/channelWidth);
if( besttimeright > 10000. && besttimeright <15000)
bestRightTDC=Int_t ((besttimeright+1000*timeDelayCFD[pmtBestRight])
/channelWidth);
if (bestRightTDC < 99999 && bestLeftTDC < 99999)
{
timeDiff=Int_t (((besttimeleft-besttimeright)+1000*delayVertex)
/channelWidth);
meanTime=Int_t (((besttimeright+1000*timeDelayCFD[pmtBestLeft]+
besttimeleft+1000*timeDelayCFD[pmtBestLeft])/2.)
/channelWidth);
AliDebug(10,Form(" time right& left %i %i time diff && mean time in channels %i %i",bestRightTDC,bestLeftTDC, timeDiff, meanTime));
}
for (Int_t i=0; i<24; i++)
{
Float_t al = countE[i];
if (al>threshold && timeGaus[i]<50000 ) {
//fill ADC
// QTC procedure:
// phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
// max 200ns, HIJING mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
// channel 25ps
qt= 50.*al*gain[i]/ph2Mip; // 50mv/Mip amp in mV
// fill TDC
trCFD = Int_t (timeGaus[i] + 1000.*timeDelayCFD[i])/channelWidth;
trLED= Int_t (timeGaus[i] + 1000.*timeDelayLED[i]);
sl = ((TGraph*)slewingLED.At(i))->Eval(qt);
trLED = Int_t(( trLED + 1000*sl )/channelWidth);
qtCh=Int_t (1000.*TMath::Log(qt)) / channelWidth;
fADC0->AddAt(0,i);
fADC->AddAt(qtCh,i);
ftimeCFD->AddAt(Int_t (trCFD),i);
ftimeLED->AddAt(trLED,i);
// sumMult += Int_t ((al*gain[i]/ph2Mip)*50) ;
sumMult += Int_t (qt/sumMultCoeff) ;
AliDebug(10,Form(" pmt %i : time in ns %f time in channels %i ",
i, timeGaus[i],trCFD ));
AliDebug(10,Form(" qt in mV %f qt in ns %f qt in channels %i ",qt,
TMath::Log(qt), qtCh));
}
} //pmt loop
if (sumMult > threshold){
fSumMult = Int_t (1000.* TMath::Log(Double_t(sumMult) / Double_t(sumMultCoeff))
/channelWidth);
AliDebug(10,Form("summult mv %i mult in chammens %i in ps %i ",
sumMult, fSumMult, fSumMult*channelWidth));
}
if ( besttimeright<99999 || besttimeleft < 99999) {
fSTART->AddDigit(bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult,
ftimeCFD,fADC,ftimeLED,fADC0);
AliDebug(10,Form(" Digits wrote bestRightTDC %i bestLeftTDC %i meanTime %i timeDiff %i fSumMult %i ", bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult ));
}
pOutStartLoader->UnloadHits();
} //input streams loop
//load digits
pOutStartLoader->LoadDigits("UPDATE");
TTree *treeD = pOutStartLoader->TreeD();
if (treeD == 0x0) {
pOutStartLoader->MakeTree("D");
treeD = pOutStartLoader->TreeD();
}
treeD->Reset();
fSTART = (AliSTART*)outRL ->GetAliRun()->GetDetector("START");
// Make a branch in the tree
fSTART->MakeBranch("D");
treeD->Fill();
pOutStartLoader->WriteDigits("OVERWRITE");
fSTART->ResetDigits();
pOutStartLoader->UnloadDigits();
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::RegisterPhotoE(Int_t ipmt,Double_t energy)
{
// Float_t hc=197.326960*1.e6; //mev*nm
Double_t hc=1.973*1.e-6; //gev*nm
Float_t lambda=hc/energy;
Float_t eff = ((TGraph*) fEffPMT.At(ipmt))->Eval(lambda);
Double_t p = gRandom->Rndm();
if (p > eff)
return kFALSE;
return kTRUE;
}
//----------------------------------------------------------------------------
<commit_msg>writing empty Digits too<commit_after>
/**************************************************************************
* Copyright(c) 1998-2000, 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. *
**************************************************************************/
#include <TTree.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include <TArrayI.h>
#include <TError.h>
#include <TH1F.h>
#include <TGraph.h>
#include "AliLog.h"
#include "AliSTARTDigitizer.h"
#include "AliSTART.h"
#include "AliSTARThit.h"
#include "AliSTARTdigit.h"
#include "AliRunDigitizer.h"
#include <AliDetector.h>
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
#include "AliSTARTParameters.h"
#include "AliCDBLocal.h"
#include "AliCDBStorage.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
ClassImp(AliSTARTDigitizer)
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager),
fSTART(0),
fHits(0),
fdigits(0),
ftimeCFD(0),
ftimeLED(0),
fADC(0),
fADC0(0)
{
// ctor which should be used
AliDebug(1,"processed");
fSTART = 0;
fHits = 0;
fdigits = 0;
ftimeCFD = new TArrayI(24);
fADC = new TArrayI(24);
ftimeLED = new TArrayI(24);
fADC0 = new TArrayI(24);
}
//------------------------------------------------------------------------
AliSTARTDigitizer::~AliSTARTDigitizer()
{
// Destructor
AliDebug(1,"START");
delete ftimeCFD;
delete fADC;
delete ftimeLED;
delete fADC0;
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::Init()
{
// Initialization
AliDebug(1," Init");
return kTRUE;
}
//---------------------------------------------------------------------
void AliSTARTDigitizer::Exec(Option_t* /*option*/)
{
/*
Produde digits from hits
digits is TObject and includes
We are writing array if left & right TDC
left & right ADC (will need for slow simulation)
TOF first particle left & right
mean time and time difference (vertex position)
*/
//output loader
AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
AliLoader * pOutStartLoader = outRL->GetLoader("STARTLoader");
AliDebug(1,"start...");
//input loader
//
// From hits to digits
//
Int_t hit, nhits;
Int_t countE[24];
Int_t volume, pmt, trCFD, trLED;
Float_t sl, qt;
Int_t bestRightTDC, bestLeftTDC, qtCh;
Float_t time[24], besttime[24], timeGaus[24] ;
//Q->T-> coefficients !!!! should be asked!!!
Float_t gain[24],timeDelayCFD[24], timeDelayLED[24];
Int_t threshold =50; //photoelectrons
Float_t zdetA, zdetC;
Int_t sumMultCoeff = 25;
TObjArray slewingLED;
TObjArray slewingRec;
AliSTARTParameters* param = AliSTARTParameters::Instance();
param->Init();
Int_t ph2Mip = param->GetPh2Mip();
Int_t channelWidth = param->GetChannelWidth() ;
Float_t delayVertex = param->GetTimeDelayTVD();
for (Int_t i=0; i<24; i++){
timeDelayCFD[i] = param->GetTimeDelayCFD(i);
timeDelayLED[i] = param->GetTimeDelayLED(i);
gain[i] = param->GetGain(i);
TGraph* gr = param ->GetSlew(i);
slewingLED.AddAtAndExpand(gr,i);
TGraph* gr1 = param ->GetSlewRec(i);
slewingRec.AddAtAndExpand(gr1,i);
TGraph* grEff = param ->GetPMTeff(i);
fEffPMT.AddAtAndExpand(grEff,i);
}
zdetC = param->GetZposition(0);
zdetA = param->GetZposition(1);
AliSTARThit *startHit;
TBranch *brHits=0;
Int_t nFiles=fManager->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {
if (inputFile < nFiles-1) {
AliWarning(Form("ignoring input stream %d", inputFile));
continue;
}
Float_t besttimeright=99999.;
Float_t besttimeleft=99999.;
Int_t pmtBestRight=9999;
Int_t pmtBestLeft=9999;
Int_t timeDiff=999, meanTime=0;
Int_t sumMult =0;// fSumMult=0;
bestRightTDC = 99999; bestLeftTDC = 99999;
ftimeCFD -> Reset();
fADC -> Reset();
fADC0 -> Reset();
ftimeLED ->Reset();
for (Int_t i0=0; i0<24; i0++)
{
time[i0]=besttime[i0]=timeGaus[i0]=99999; countE[i0]=0;
}
AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
AliLoader * pInStartLoader = inRL->GetLoader("STARTLoader");
if (!inRL->GetAliRun()) inRL->LoadgAlice();
AliSTART *fSTART = (AliSTART*)inRL ->GetAliRun()->GetDetector("START");
//read Hits
pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
TClonesArray *fHits = fSTART->Hits ();
TTree *th = pInStartLoader->TreeH();
brHits = th->GetBranch("START");
if (brHits) {
fSTART->SetHitsAddressBranch(brHits);
}else{
AliError("Branch START hit not found");
exit(111);
}
Int_t ntracks = (Int_t) th->GetEntries();
if (ntracks<=0) return;
// Start loop on tracks in the hits containers
for (Int_t track=0; track<ntracks;track++) {
brHits->GetEntry(track);
nhits = fHits->GetEntriesFast();
for (hit=0;hit<nhits;hit++)
{
startHit = (AliSTARThit*) fHits->UncheckedAt(hit);
if (!startHit) {
AliError("The unchecked hit doesn't exist");
break;
}
pmt=startHit->Pmt();
Int_t numpmt=pmt-1;
Double_t e=startHit->Etot();
volume = startHit->Volume();
if(e>0 && RegisterPhotoE(numpmt,e)) {
countE[numpmt]++;
besttime[numpmt] = startHit->Time();
if(besttime[numpmt]<time[numpmt])
{
time[numpmt]=besttime[numpmt];
}
} //photoelectron accept
} //hits loop
} //track loop
//spread time right&left by 25ps && besttime
Float_t c = 0.0299792; // cm/ps
Float_t koef=(zdetA-zdetC)/c; //correction position difference by cable
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25)+koef;
if(timeGaus[ipmt]<besttimeleft){
besttimeleft=timeGaus[ipmt]; //timeleft
pmtBestLeft=ipmt;}
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeright) {
besttimeright=timeGaus[ipmt]; //timeright
pmtBestRight=ipmt;}
}
}
//folding with alignmentz position distribution
if( besttimeleft > 10000. && besttimeleft <15000)
bestLeftTDC=Int_t ((besttimeleft+1000*timeDelayCFD[pmtBestLeft])
/channelWidth);
if( besttimeright > 10000. && besttimeright <15000)
bestRightTDC=Int_t ((besttimeright+1000*timeDelayCFD[pmtBestRight])
/channelWidth);
if (bestRightTDC < 99999 && bestLeftTDC < 99999)
{
timeDiff=Int_t (((besttimeleft-besttimeright)+1000*delayVertex)
/channelWidth);
meanTime=Int_t (((besttimeright+1000*timeDelayCFD[pmtBestLeft]+
besttimeleft+1000*timeDelayCFD[pmtBestLeft])/2.)
/channelWidth);
}
AliDebug(10,Form(" time right& left %i %i time diff && mean time in channels %i %i",bestRightTDC,bestLeftTDC, timeDiff, meanTime));
for (Int_t i=0; i<24; i++)
{
Float_t al = countE[i];
if (al>threshold && timeGaus[i]<50000 ) {
//fill ADC
// QTC procedure:
// phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
// max 200ns, HIJING mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
// channel 25ps
qt= 50.*al*gain[i]/ph2Mip; // 50mv/Mip amp in mV
// fill TDC
trCFD = Int_t (timeGaus[i] + 1000.*timeDelayCFD[i])/channelWidth;
trLED= Int_t (timeGaus[i] + 1000.*timeDelayLED[i]);
sl = ((TGraph*)slewingLED.At(i))->Eval(qt);
trLED = Int_t(( trLED + 1000*sl )/channelWidth);
qtCh=Int_t (1000.*TMath::Log(qt)) / channelWidth;
fADC0->AddAt(0,i);
fADC->AddAt(qtCh,i);
ftimeCFD->AddAt(Int_t (trCFD),i);
ftimeLED->AddAt(trLED,i);
// sumMult += Int_t ((al*gain[i]/ph2Mip)*50) ;
sumMult += Int_t (qt/sumMultCoeff) ;
AliDebug(10,Form(" pmt %i : time in ns %f time in channels %i ",
i, timeGaus[i],trCFD ));
AliDebug(10,Form(" qt in mV %f qt in ns %f qt in channels %i ",qt,
TMath::Log(qt), qtCh));
}
} //pmt loop
if (sumMult > threshold){
fSumMult = Int_t (1000.* TMath::Log(Double_t(sumMult) / Double_t(sumMultCoeff))
/channelWidth);
AliDebug(10,Form("summult mv %i mult in chammens %i in ps %i ",
sumMult, fSumMult, fSumMult*channelWidth));
}
// if ( besttimeright<99999 || besttimeleft < 99999) {
fSTART->AddDigit(bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult,
ftimeCFD,fADC,ftimeLED,fADC0);
// }
AliDebug(10,Form(" Digits wrote bestRightTDC %i bestLeftTDC %i meanTime %i timeDiff %i fSumMult %i ", bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult ));
pOutStartLoader->UnloadHits();
} //input streams loop
//load digits
pOutStartLoader->LoadDigits("UPDATE");
TTree *treeD = pOutStartLoader->TreeD();
if (treeD == 0x0) {
pOutStartLoader->MakeTree("D");
treeD = pOutStartLoader->TreeD();
}
treeD->Reset();
fSTART = (AliSTART*)outRL ->GetAliRun()->GetDetector("START");
// Make a branch in the tree
fSTART->MakeBranch("D");
treeD->Fill();
pOutStartLoader->WriteDigits("OVERWRITE");
fSTART->ResetDigits();
pOutStartLoader->UnloadDigits();
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::RegisterPhotoE(Int_t ipmt,Double_t energy)
{
// Float_t hc=197.326960*1.e6; //mev*nm
Double_t hc=1.973*1.e-6; //gev*nm
Float_t lambda=hc/energy;
Float_t eff = ((TGraph*) fEffPMT.At(ipmt))->Eval(lambda);
Double_t p = gRandom->Rndm();
if (p > eff)
return kFALSE;
return kTRUE;
}
//----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/**
* @file Dtw.cpp
*
* An implementation of the Dynamic Time Warping algorithm.
*
* 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.5.7
*/
#include "Dtw.h"
namespace Aquila
{
/**
* Computes the distance between two sets of data.
*
* @param from first vector of features
* @param to second vector of features
* @return double DTW distance
*/
double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to)
{
m_fromSize = from.size();
m_toSize = to.size();
// fill the local distances array
m_points.resize(m_fromSize);
for (std::size_t i = 0; i < m_fromSize; ++i)
{
m_points[i].reserve(m_toSize);
for (std::size_t j = 0; j < m_toSize; ++j)
{
// use emplace_back, once all compilers support it correctly
m_points[i].push_back(
DtwPoint(i, j, m_distanceFunction(from[i], to[j])
));
}
}
// the actual pathfinding algorithm
DtwPoint *top = 0, *center = 0, *bottom = 0, *previous = 0;
for (std::size_t i = 1; i < m_fromSize; ++i)
{
for (std::size_t j = 1; j < m_toSize; ++j)
{
center = &m_points[i - 1][j - 1];
if (Neighbors == m_passType)
{
top = &m_points[i - 1][j];
bottom = &m_points[i][j - 1];
}
else // Diagonals
{
if (i > 1 && j > 1)
{
top = &m_points[i - 2][j - 1];
bottom = &m_points[i - 1][j - 2];
}
else
{
top = &m_points[i - 1][j];
bottom = &m_points[i][j - 1];
}
}
if (top->dAccumulated < center->dAccumulated)
previous = top;
else
previous = center;
if (bottom->dAccumulated < previous->dAccumulated)
previous = bottom;
m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated;
m_points[i][j].previous = previous;
}
}
return getFinalPoint().dAccumulated;
}
}
<commit_msg>Dtw class should clear points array.<commit_after>/**
* @file Dtw.cpp
*
* An implementation of the Dynamic Time Warping algorithm.
*
* 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.5.7
*/
#include "Dtw.h"
namespace Aquila
{
/**
* Computes the distance between two sets of data.
*
* @param from first vector of features
* @param to second vector of features
* @return double DTW distance
*/
double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to)
{
m_fromSize = from.size();
m_toSize = to.size();
// fill the local distances array
m_points.clear();
m_points.resize(m_fromSize);
for (std::size_t i = 0; i < m_fromSize; ++i)
{
m_points[i].reserve(m_toSize);
for (std::size_t j = 0; j < m_toSize; ++j)
{
// use emplace_back, once all compilers support it correctly
m_points[i].push_back(
DtwPoint(i, j, m_distanceFunction(from[i], to[j])
));
}
}
// the actual pathfinding algorithm
DtwPoint *top = 0, *center = 0, *bottom = 0, *previous = 0;
for (std::size_t i = 1; i < m_fromSize; ++i)
{
for (std::size_t j = 1; j < m_toSize; ++j)
{
center = &m_points[i - 1][j - 1];
if (Neighbors == m_passType)
{
top = &m_points[i - 1][j];
bottom = &m_points[i][j - 1];
}
else // Diagonals
{
if (i > 1 && j > 1)
{
top = &m_points[i - 2][j - 1];
bottom = &m_points[i - 1][j - 2];
}
else
{
top = &m_points[i - 1][j];
bottom = &m_points[i][j - 1];
}
}
if (top->dAccumulated < center->dAccumulated)
previous = top;
else
previous = center;
if (bottom->dAccumulated < previous->dAccumulated)
previous = bottom;
m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated;
m_points[i][j].previous = previous;
}
}
return getFinalPoint().dAccumulated;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merconnection.h"
#include "merconstants.h"
#include "mervirtualboxmanager.h"
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
#include <ssh/sshconnection.h>
#include <ssh/sshremoteprocessrunner.h>
#include <utils/qtcassert.h>
#include <projectexplorer/taskhub.h>
#include <projectexplorer/projectexplorer.h>
#include <QAction>
#include <QTimer>
namespace Mer {
namespace Internal {
using namespace QSsh;
using namespace ProjectExplorer;
const QSize iconSize = QSize(24, 20);
static int VM_TIMEOUT = 3000;
MerRemoteConnection::MerRemoteConnection(QObject *parent)
: QObject(parent)
, m_action(new QAction(this))
, m_initalized(false)
, m_visible(false)
, m_enabled(false)
, m_connection(0)
, m_state(Disconnected)
{
}
MerRemoteConnection::~MerRemoteConnection()
{
if (m_connection)
m_connection->deleteLater();
m_connection = 0;
}
void MerRemoteConnection::setName(const QString &name)
{
m_name = name;
}
void MerRemoteConnection::setIcon(const QIcon &icon)
{
m_icon = icon;
}
void MerRemoteConnection::setStartTip(const QString &tip)
{
m_startTip = tip;
}
void MerRemoteConnection::setStopTip(const QString &tip)
{
m_stopTip = tip;
}
void MerRemoteConnection::setVisible(bool visible)
{
m_visible = visible;
}
void MerRemoteConnection::setEnabled(bool enabled)
{
m_enabled = enabled;
}
void MerRemoteConnection::initialize()
{
if (m_initalized)
return;
m_action->setText(m_name);
m_action->setIcon(m_icon.pixmap(iconSize));
m_action->setToolTip(m_startTip);
connect(m_action, SIGNAL(triggered()), this, SLOT(handleTriggered()));
Core::Command *command =
Core::ActionManager::registerAction(m_action, Core::Id(m_name),
Core::Context(Core::Constants::C_GLOBAL));
command->setAttribute(Core::Command::CA_UpdateText);
command->setAttribute(Core::Command::CA_UpdateIcon);
Core::ModeManager::addAction(command->action(), 1);
m_action->setEnabled(m_enabled);
m_action->setVisible(m_visible);
m_initalized = true;
}
bool MerRemoteConnection::isConnected() const
{
return m_state == Connected;
}
SshConnectionParameters MerRemoteConnection::sshParameters() const
{
if (m_connection)
return m_connection->connectionParameters();
return SshConnectionParameters();
}
void MerRemoteConnection::setConnectionParameters(const QString &virtualMachine, const SshConnectionParameters &sshParameters)
{
if (m_connection && m_connection->connectionParameters() == sshParameters && virtualMachine == m_vmName)
return;
if (m_connection)
m_connection->deleteLater();
m_vmName = virtualMachine;
m_connection = createConnection(sshParameters);
m_state = Disconnected;
}
QString MerRemoteConnection::virtualMachine() const
{
return m_vmName;
}
void MerRemoteConnection::update()
{
QIcon::State state;
QString toolTip;
bool enabled = m_enabled;
switch (m_state) {
case Connected:
state = QIcon::On;
toolTip = m_stopTip;
break;
case Disconnected:
state = QIcon::Off;
toolTip = m_startTip;
break;
default:
enabled = false;
break;
}
m_action->setEnabled(enabled);
m_action->setVisible(m_visible);
m_action->setToolTip(toolTip);
m_action->setIcon(m_icon.pixmap(iconSize, QIcon::Normal, state));
}
QSsh::SshConnection* MerRemoteConnection::createConnection(const SshConnectionParameters ¶ms)
{
SshConnection *connection = new SshConnection(params);
connect(connection, SIGNAL(connected()), this, SLOT(changeState()));
connect(connection, SIGNAL(error(QSsh::SshError)), this, SLOT(changeState()));
connect(connection, SIGNAL(disconnected()), this, SLOT(changeState()));
return connection;
}
void MerRemoteConnection::handleConnection()
{
//TODO: this can be removed
SshConnection *connection = qobject_cast<SshConnection*>(sender());
if (connection) {
QTC_ASSERT(connection == m_connection, return);
changeState();
}
}
void MerRemoteConnection::changeState(State stateTrigger)
{
QTC_ASSERT(!m_vmName.isEmpty(), return);
if (stateTrigger != NoStateTrigger)
m_state = stateTrigger;
switch (m_state) {
case StartingVm:
if (MerVirtualBoxManager::isVirtualMachineRunning(m_vmName)) {
m_state = Connecting;
m_connection->connectToHost();
} else {
MerVirtualBoxManager::startVirtualMachine(m_vmName);
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case Connecting:
if (m_connection->state() == SshConnection::Connected) {
m_state = Connected;
} else if (m_connection->state() == SshConnection::Unconnected) {
m_state = Disconnected; //broken
if (m_connection->errorState() != SshNoError)
createConnectionErrorTask(m_vmName, m_connection->errorString());
} else {
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case Connected:
if(m_connection->state() == SshConnection::Unconnected)
{
m_state = Disconnected;
}
break;
case Disconneting:
if (m_connection->state() == SshConnection::Connected) {
m_connection->disconnectFromHost();
} else if (m_connection->state() == SshConnection::Unconnected) {
MerVirtualBoxManager::shutVirtualMachine(m_vmName);
QSsh::SshConnectionParameters sshParams = m_connection->connectionParameters();
sshParams.userName = QLatin1String("root");
QSsh::SshRemoteProcessRunner *runner = new QSsh::SshRemoteProcessRunner(m_connection);
connect(runner, SIGNAL(processClosed(int)), runner, SLOT(deleteLater()));
runner->run("shutdown now", sshParams);
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
m_state = ClosingVm;
} else {
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case ClosingVm:
if (MerVirtualBoxManager::isVirtualMachineRunning(m_vmName))
qWarning() << "Could not close virtual machine" << m_vmName;
m_state = Disconnected;
break;
case Disconnected:
break;
default:
break;
}
update();
}
void MerRemoteConnection::connectTo()
{
if (!m_connection)
return;
if (m_state == Disconnected)
changeState(StartingVm);
}
void MerRemoteConnection::handleTriggered()
{
if (!m_connection)
return;
if (m_state == Disconnected) {
changeState(StartingVm);
} else if (m_state == Connected) {
changeState(Disconneting);
}
}
void MerRemoteConnection::createConnectionErrorTask(const QString &vmName, const QString &error)
{
TaskHub *th = ProjectExplorerPlugin::instance()->taskHub();
th->addTask(Task(Task::Error,
tr("%1: %2").arg(vmName, error),
Utils::FileName() /* filename */,
-1 /* linenumber */,
Core::Id(Constants::MER_TASKHUB_CATEGORY)));
}
} // Internal
} // Mer
<commit_msg>Jolla: Adds sdk-shutdown to merconnection<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merconnection.h"
#include "merconstants.h"
#include "mervirtualboxmanager.h"
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
#include <ssh/sshconnection.h>
#include <ssh/sshremoteprocessrunner.h>
#include <utils/qtcassert.h>
#include <projectexplorer/taskhub.h>
#include <projectexplorer/projectexplorer.h>
#include <QAction>
#include <QTimer>
namespace Mer {
namespace Internal {
using namespace QSsh;
using namespace ProjectExplorer;
const QSize iconSize = QSize(24, 20);
static int VM_TIMEOUT = 3000;
MerRemoteConnection::MerRemoteConnection(QObject *parent)
: QObject(parent)
, m_action(new QAction(this))
, m_initalized(false)
, m_visible(false)
, m_enabled(false)
, m_connection(0)
, m_state(Disconnected)
{
}
MerRemoteConnection::~MerRemoteConnection()
{
if (m_connection)
m_connection->deleteLater();
m_connection = 0;
}
void MerRemoteConnection::setName(const QString &name)
{
m_name = name;
}
void MerRemoteConnection::setIcon(const QIcon &icon)
{
m_icon = icon;
}
void MerRemoteConnection::setStartTip(const QString &tip)
{
m_startTip = tip;
}
void MerRemoteConnection::setStopTip(const QString &tip)
{
m_stopTip = tip;
}
void MerRemoteConnection::setVisible(bool visible)
{
m_visible = visible;
}
void MerRemoteConnection::setEnabled(bool enabled)
{
m_enabled = enabled;
}
void MerRemoteConnection::initialize()
{
if (m_initalized)
return;
m_action->setText(m_name);
m_action->setIcon(m_icon.pixmap(iconSize));
m_action->setToolTip(m_startTip);
connect(m_action, SIGNAL(triggered()), this, SLOT(handleTriggered()));
Core::Command *command =
Core::ActionManager::registerAction(m_action, Core::Id(m_name),
Core::Context(Core::Constants::C_GLOBAL));
command->setAttribute(Core::Command::CA_UpdateText);
command->setAttribute(Core::Command::CA_UpdateIcon);
Core::ModeManager::addAction(command->action(), 1);
m_action->setEnabled(m_enabled);
m_action->setVisible(m_visible);
m_initalized = true;
}
bool MerRemoteConnection::isConnected() const
{
return m_state == Connected;
}
SshConnectionParameters MerRemoteConnection::sshParameters() const
{
if (m_connection)
return m_connection->connectionParameters();
return SshConnectionParameters();
}
void MerRemoteConnection::setConnectionParameters(const QString &virtualMachine, const SshConnectionParameters &sshParameters)
{
if (m_connection && m_connection->connectionParameters() == sshParameters && virtualMachine == m_vmName)
return;
if (m_connection)
m_connection->deleteLater();
m_vmName = virtualMachine;
m_connection = createConnection(sshParameters);
m_state = Disconnected;
}
QString MerRemoteConnection::virtualMachine() const
{
return m_vmName;
}
void MerRemoteConnection::update()
{
QIcon::State state;
QString toolTip;
bool enabled = m_enabled;
switch (m_state) {
case Connected:
state = QIcon::On;
toolTip = m_stopTip;
break;
case Disconnected:
state = QIcon::Off;
toolTip = m_startTip;
break;
default:
enabled = false;
break;
}
m_action->setEnabled(enabled);
m_action->setVisible(m_visible);
m_action->setToolTip(toolTip);
m_action->setIcon(m_icon.pixmap(iconSize, QIcon::Normal, state));
}
QSsh::SshConnection* MerRemoteConnection::createConnection(const SshConnectionParameters ¶ms)
{
SshConnection *connection = new SshConnection(params);
connect(connection, SIGNAL(connected()), this, SLOT(changeState()));
connect(connection, SIGNAL(error(QSsh::SshError)), this, SLOT(changeState()));
connect(connection, SIGNAL(disconnected()), this, SLOT(changeState()));
return connection;
}
void MerRemoteConnection::handleConnection()
{
//TODO: this can be removed
SshConnection *connection = qobject_cast<SshConnection*>(sender());
if (connection) {
QTC_ASSERT(connection == m_connection, return);
changeState();
}
}
void MerRemoteConnection::changeState(State stateTrigger)
{
QTC_ASSERT(!m_vmName.isEmpty(), return);
if (stateTrigger != NoStateTrigger)
m_state = stateTrigger;
switch (m_state) {
case StartingVm:
if (MerVirtualBoxManager::isVirtualMachineRunning(m_vmName)) {
m_state = Connecting;
m_connection->connectToHost();
} else {
MerVirtualBoxManager::startVirtualMachine(m_vmName);
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case Connecting:
if (m_connection->state() == SshConnection::Connected) {
m_state = Connected;
} else if (m_connection->state() == SshConnection::Unconnected) {
m_state = Disconnected; //broken
if (m_connection->errorState() != SshNoError)
createConnectionErrorTask(m_vmName, m_connection->errorString());
} else {
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case Connected:
if(m_connection->state() == SshConnection::Unconnected)
{
m_state = Disconnected;
}
break;
case Disconneting:
if (m_connection->state() == SshConnection::Connected) {
m_connection->disconnectFromHost();
} else if (m_connection->state() == SshConnection::Unconnected) {
MerVirtualBoxManager::shutVirtualMachine(m_vmName);
QSsh::SshConnectionParameters sshParams = m_connection->connectionParameters();
QSsh::SshRemoteProcessRunner *runner = new QSsh::SshRemoteProcessRunner(m_connection);
connect(runner, SIGNAL(processClosed(int)), runner, SLOT(deleteLater()));
runner->run("sdk-shutdown", sshParams);
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
m_state = ClosingVm;
} else {
QTimer::singleShot(VM_TIMEOUT, this, SLOT(changeState()));
}
break;
case ClosingVm:
if (MerVirtualBoxManager::isVirtualMachineRunning(m_vmName))
qWarning() << "Could not close virtual machine" << m_vmName;
m_state = Disconnected;
break;
case Disconnected:
break;
default:
break;
}
update();
}
void MerRemoteConnection::connectTo()
{
if (!m_connection)
return;
if (m_state == Disconnected)
changeState(StartingVm);
}
void MerRemoteConnection::handleTriggered()
{
if (!m_connection)
return;
if (m_state == Disconnected) {
changeState(StartingVm);
} else if (m_state == Connected) {
changeState(Disconneting);
}
}
void MerRemoteConnection::createConnectionErrorTask(const QString &vmName, const QString &error)
{
TaskHub *th = ProjectExplorerPlugin::instance()->taskHub();
th->addTask(Task(Task::Error,
tr("%1: %2").arg(vmName, error),
Utils::FileName() /* filename */,
-1 /* linenumber */,
Core::Id(Constants::MER_TASKHUB_CATEGORY)));
}
} // Internal
} // Mer
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FILTERS_IMPL_SHADOW_POINTS_FILTER_H_
#define PCL_FILTERS_IMPL_SHADOW_POINTS_FILTER_H_
#include <pcl/filters/shadowpoints.h>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::ShadowPoints<PointT, NormalT>::applyFilter (PointCloud &output)
{
assert (input_normals_ != NULL);
for (unsigned int i = 0; i < input_->points.size (); i++)
{
float *normal = input_normals_->points[(*indices_)[i]].normal;
PointT pt = input_->points[i];
if (!normal)
{
continue;
}
float val = fabsf (normal[0] * pt.x + normal[1] * pt.y + normal[2] * pt.z);
if (val > threshold_)
{
output.points.push_back (pt);
}
}
output.width = 1;
output.height = static_cast<uint32_t> (output.points.size ());
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::ShadowPoints<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
assert (input_normals_ != NULL);
indices.resize (input_->points.size ());
removed_indices_->resize (indices_->size ());
unsigned int k = 0;
unsigned int z = 0;
for (unsigned int i = 0; i < (*indices_).size (); i++)
{
float *normal = input_normals_->points[(*indices_)[i]].normal;
PointT pt = input_->points[(*indices_)[i]];
if (!normal)
{
continue;
}
float val = fabsf (normal[0] * pt.x + normal[1] * pt.y + normal[2] * pt.z);
if (val > threshold_)
{
indices[k++] = (*indices_)[i];
}
else
{
(*removed_indices_)[z++] = (*indices_)[i];
}
}
indices.resize (k);
removed_indices_->resize (z);
}
#define PCL_INSTANTIATE_ShadowPoints(T,NT) template class PCL_EXPORTS pcl::ShadowPoints<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<commit_msg>bugfix<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FILTERS_IMPL_SHADOW_POINTS_FILTER_H_
#define PCL_FILTERS_IMPL_SHADOW_POINTS_FILTER_H_
#include <pcl/filters/shadowpoints.h>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::ShadowPoints<PointT, NormalT>::applyFilter (PointCloud &output)
{
assert (input_normals_ != NULL);
output.points.resize (input_->points.size ());
unsigned int cp = 0;
for (unsigned int i = 0; i < input_->points.size (); i++)
{
const NormalT &normal = input_normals_->points[i];
const PointT &pt = input_->points[i];
float val = fabsf (normal.normal_x * pt.x + normal.normal_y * pt.y + normal.normal_z * pt.z);
if (val >= threshold_)
output.points[cp++] = pt;
}
output.points.resize (cp);
output.width = 1;
output.height = static_cast<uint32_t> (output.points.size ());
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::ShadowPoints<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
assert (input_normals_ != NULL);
indices.resize (input_->points.size ());
removed_indices_->resize (indices_->size ());
unsigned int k = 0;
unsigned int z = 0;
for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
{
const NormalT &normal = input_normals_->points[*idx];
const PointT &pt = input_->points[*idx];
float val = fabsf (normal.normal_x * pt.x + normal.normal_y * pt.y + normal.normal_z * pt.z);
if (val >= threshold_)
indices[k++] = *idx;
else
(*removed_indices_)[z++] = *idx;
}
indices.resize (k);
removed_indices_->resize (z);
}
#define PCL_INSTANTIATE_ShadowPoints(T,NT) template class PCL_EXPORTS pcl::ShadowPoints<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS mbafixesfor22 (1.113.108); FILE MERGED 2007/01/16 11:31:02 mba 1.113.108.1: #i64552#: pass bIsAPI to every print call<commit_after><|endoftext|> |
<commit_before>#include <algorithm>
#include "Graphics.h"
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480 //minimum size to allow for 64x64 maps
Graphics::Graphics(uint16_t xSize, uint16_t tileOffset, uint16_t tileAmount) {
this->selXMin = std::min(8*64, 8*xSize) + 1;
this->xDisplaySize = std::min(64, 0+xSize);
this->tileOffset = tileOffset;
this->tileAmount = tileAmount;
this->currentPal = 0;
this->highPriorityDisplay = true;
this->lowPriorityDisplay = true;
this->screenTileYOffset = 0;
this->screenTileXOffset = 0;
this->selTileYOffset = 0;
/* calculate selector width */
this->selectorWidth = 8;
while (8*tileAmount / selectorWidth > SCREEN_HEIGHT) {
if (8 * (xSize+selectorWidth) < SCREEN_WIDTH) selectorWidth += 8;
else break;
}
if (SDL_Init(SDL_INIT_VIDEO)<0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL video", SDL_GetError(), NULL);
exit(1);
}
atexit(SDL_Quit);
window = SDL_CreateWindow("Captain PlaneEd", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (window == NULL)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL Window", SDL_GetError(), NULL);
exit(1);
}
render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (render == NULL)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL Renderer", SDL_GetError(), NULL);
exit(1);
}
SDL_RenderSetLogicalSize(render, SCREEN_WIDTH, SCREEN_HEIGHT);
screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);
if (screen==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init screen SDL Surface", SDL_GetError(), NULL);
exit(1);
}
texture = SDL_CreateTextureFromSurface(render, screen);
if (texture==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init screen SDL Texture", SDL_GetError(), NULL);
exit(1);
}
}
void Graphics::ReadPalette(const char* const filename) {
FILE* palfile = fopen(filename,"rb");
if (palfile==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Palette file not found. Are you sure the path is correct?", NULL);
exit(1);
}
fseek(palfile, 0, SEEK_END);
paletteLines = ftell(palfile)/0x20;
if (paletteLines > 4) paletteLines = 4;
rewind(palfile);
if (paletteLines == 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Palette file too small. It must contain at least one palette line.", NULL);
exit(1);
}
palette = new uint16_t[paletteLines][16];
for (int i=0; i < paletteLines; ++i)
fread(palette[i], sizeof(unsigned char), 32, palfile);
fclose(palfile);
remove(filename);
}
#define getrgb(v) ((v&0xF000)>>8)|(v&0x0F0F|0xF000) // Corrects G value, and sets alpha to max, so we can see
void Graphics::ReadTiles(const char* const filename) {
FILE* tilefile = fopen(filename,"rb");
if (tilefile==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Art file not found. Are you sure the path is correct?", NULL);
exit(1);
}
unsigned char tilebuffer[32]; //space for one tile
tileData = new uint16_t***[tileAmount];
for (int t=0; t < tileAmount; ++t) {
fread(tilebuffer, sizeof(unsigned char), 32, tilefile);
tileData[t] = new uint16_t**[paletteLines];
for (int p=0; p < paletteLines; ++p) {
tileData[t][p] = new uint16_t*[4];
for (int f=0; f < 4; ++f) tileData[t][p][f] = new uint16_t[64];
for (int i=0; i < 32; ++i) {
tileData[t][p][0][2*i] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]);
tileData[t][p][0][2*i+1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][1][8*(i/4)+7-2*(i%4)] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //X-flip
tileData[t][p][1][8*(i/4)+7-2*(i%4)-1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][2][56-8*(i/4)+2*(i%4)] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //Y-flip
tileData[t][p][2][56-8*(i/4)+2*(i%4)+1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][3][63-2*i] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //XY-flip
tileData[t][p][3][63-2*i-1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
}
}
}
fclose(tilefile);
remove(filename);
}
void Graphics::CreateTiles(){
tiles = new SDL_Surface***[tileAmount];
for (int t=0; t < tileAmount; ++t)
{
tiles[t] = new SDL_Surface**[paletteLines];
for (int p=0; p < paletteLines; ++p)
{
tiles[t][p] = new SDL_Surface*[4];
for (int f=0; f < 4; ++f)
tiles[t][p][f] = InitSurface(tileData[t][p][f], 8, 8, 16);
}
}
}
SDL_Surface* Graphics::InitSurface(uint16_t *pixelsT, int width, int height, int bbp) {
void* pixels = pixelsT;
SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (pixels, width,
height, bbp, width*((bbp+7)/8), 0x0F00, 0x00F0, 0x000F, 0xF000);
if (surface == NULL)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Cannot make SDL Surface from tiles", SDL_GetError(), NULL);
return(surface);
}
void Graphics::DrawSurface(SDL_Surface *img, SDL_Surface *screen, int x, int y) {
SDL_Rect RectTemp;
RectTemp.x = x;
RectTemp.y = y;
SDL_BlitSurface(img, NULL, screen, &RectTemp);
}
void Graphics::ClearMap() {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
SDL_Rect RectTemp;
RectTemp.x = 0;
RectTemp.y = 0;
RectTemp.w = selXMin-1;
RectTemp.h = SCREEN_HEIGHT;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::ClearSelector() {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
SDL_Rect RectTemp;
RectTemp.x = selXMin;
RectTemp.y = 0;
RectTemp.w = 8*selectorWidth;
RectTemp.h = SCREEN_HEIGHT;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::DrawSelector() {
ClearSelector();
for (int i=0; i < tileAmount; ++i)
DrawSurface(tiles[i][currentPal][0], this->screen, selXMin + 8*(i%selectorWidth), 8*(i/selectorWidth - selTileYOffset));
//SDL_Flip(screen);
ProcessDisplay();
}
void Graphics::ProcessDisplay()
{
SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch);
SDL_RenderClear(render);
SDL_RenderCopy(render, texture, NULL, NULL);
SDL_RenderPresent(render);
}
/* map coords */
void Graphics::DrawTileSingle(int x, int y, Tile tile) {
y -= screenTileYOffset;
x -= screenTileXOffset;
if (x >= xDisplaySize) return;
if ((tile.priority && highPriorityDisplay) || (!tile.priority && lowPriorityDisplay)) {
if ((tile.tileID) - tileOffset >= this->tileAmount) {
DrawTileNone(x, y);
DrawTileInvalid(x, y);
} else if ((tile.tileID || !this->tileOffset) && tile.paletteLine < paletteLines)
DrawSurface(tiles[(tile.tileID) - tileOffset][tile.paletteLine][tile.xFlip | (tile.yFlip<<1)], screen, 8*x, 8*y);
else DrawTileBlank(x, y, tile);
} else DrawTileNone(x, y);
}
bool Graphics::CheckSelValidPos(int x, int y) {
if (x>=selXMin && x<selXMin+8*selectorWidth && y>=0 && (x-selXMin)/8+selectorWidth*(y/8 + selTileYOffset)<GetTileAmount()) return true;
else return false;
}
void Graphics::DrawTileNone(int x, int y) {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
DrawTileFullColor(x, y, color);
}
void Graphics::DrawTileBlank(int x, int y, Tile tile) {
Uint32 color = SDL_MapRGB(
screen->format,
(palette[tile.paletteLine][0] & 0x0F00)>>4,
(palette[tile.paletteLine][0] & 0x00F0),
(palette[tile.paletteLine][0] & 0x000F)<<4
);
DrawTileFullColor(x, y, color);
}
void Graphics::DrawTileFullColor(int x, int y, Uint32 color) {
SDL_Rect RectTemp;
RectTemp.x = 8*x;
RectTemp.y = 8*y;
RectTemp.w = 8;
RectTemp.h = 8;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::DrawTileInvalid(int x, int y) {
//PosTileToScreen(&x, &y);
for (int i=0; i < 8; ++i) {
DrawPixel(8*x+i, 8*y+i);
DrawPixel(8*x+i, 8*y+7-i);
}
}
void Graphics::DrawPixel(int x, int y) {
if (x<0 || x>=SCREEN_WIDTH || y<0 || y>=SCREEN_HEIGHT) return;
Uint32 color = SDL_MapRGB(screen->format, 0xE0, 0xB0, 0xD0);
Uint32 *pixel;
pixel = (Uint32*) screen->pixels + y*screen->pitch/4 + x;
*pixel = color;
}
/* map coords */
void Graphics::DrawRect(int x, int y) {
PosTileToScreen(&x, &y);
for (int i=0; i < 8; ++i) {
DrawPixel(x+i, y);
DrawPixel(x+i, y+7);
DrawPixel(x, y+i);
DrawPixel(x+7, y+i);
}
}
/* map coords */
void Graphics::DrawFreeRect(int x, int y, int xSize, int ySize) {
PosTileToScreen(&x, &y);
for (int i=0; i < 8*ySize; ++i) {
DrawPixel(x, y+i);
DrawPixel(x + 8*xSize - 1, y+i);
}
for (int i=0; i < 8*xSize; ++i) {
DrawPixel(x+i, y);
DrawPixel(x+i, y + 8*ySize - 1);
}
}
void Graphics::PosScreenToTile(int* x, int* y) {
*x /= 8;
*y /= 8;
*y += screenTileYOffset;
*x += screenTileXOffset;
}
void Graphics::PosScreenToTileRound(int* x, int* y) {
*x = ((*x)+4)/8;
*y = ((*y)+4)/8;
*y += screenTileYOffset;
*x += screenTileXOffset;
}
void Graphics::PosTileToScreen(int* x, int* y) {
*y -= screenTileYOffset;
*x -= screenTileXOffset;
*x *= 8;
*y *= 8;
}
<commit_msg>Cleaning up palette-loading code<commit_after>#include <algorithm>
#include "Graphics.h"
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480 //minimum size to allow for 64x64 maps
Graphics::Graphics(uint16_t xSize, uint16_t tileOffset, uint16_t tileAmount) {
this->selXMin = std::min(8*64, 8*xSize) + 1;
this->xDisplaySize = std::min(64, 0+xSize);
this->tileOffset = tileOffset;
this->tileAmount = tileAmount;
this->currentPal = 0;
this->highPriorityDisplay = true;
this->lowPriorityDisplay = true;
this->screenTileYOffset = 0;
this->screenTileXOffset = 0;
this->selTileYOffset = 0;
/* calculate selector width */
this->selectorWidth = 8;
while (8*tileAmount / selectorWidth > SCREEN_HEIGHT) {
if (8 * (xSize+selectorWidth) < SCREEN_WIDTH) selectorWidth += 8;
else break;
}
if (SDL_Init(SDL_INIT_VIDEO)<0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL video", SDL_GetError(), NULL);
exit(1);
}
atexit(SDL_Quit);
window = SDL_CreateWindow("Captain PlaneEd", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (window == NULL)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL Window", SDL_GetError(), NULL);
exit(1);
}
render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (render == NULL)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init SDL Renderer", SDL_GetError(), NULL);
exit(1);
}
SDL_RenderSetLogicalSize(render, SCREEN_WIDTH, SCREEN_HEIGHT);
screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);
if (screen==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init screen SDL Surface", SDL_GetError(), NULL);
exit(1);
}
texture = SDL_CreateTextureFromSurface(render, screen);
if (texture==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unable to init screen SDL Texture", SDL_GetError(), NULL);
exit(1);
}
}
void Graphics::ReadPalette(const char* const filename) {
FILE* palfile = fopen(filename,"rb");
if (palfile==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Internal Error", "Decompressed palette file not found.", NULL);
exit(1);
}
fseek(palfile, 0, SEEK_END);
paletteLines = ftell(palfile)/0x20;
rewind(palfile);
if (paletteLines > 4) {
paletteLines = 4;
}
else if (paletteLines == 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Palette file too small. It must contain at least one palette line.", NULL);
exit(1);
}
palette = new uint16_t[paletteLines][16];
for (int i=0; i < paletteLines; ++i)
fread(palette[i], sizeof(unsigned char), 32, palfile);
fclose(palfile);
remove(filename);
}
#define getrgb(v) ((v&0xF000)>>8)|(v&0x0F0F|0xF000) // Corrects G value, and sets alpha to max, so we can see
void Graphics::ReadTiles(const char* const filename) {
FILE* tilefile = fopen(filename,"rb");
if (tilefile==NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Art file not found. Are you sure the path is correct?", NULL);
exit(1);
}
unsigned char tilebuffer[32]; //space for one tile
tileData = new uint16_t***[tileAmount];
for (int t=0; t < tileAmount; ++t) {
fread(tilebuffer, sizeof(unsigned char), 32, tilefile);
tileData[t] = new uint16_t**[paletteLines];
for (int p=0; p < paletteLines; ++p) {
tileData[t][p] = new uint16_t*[4];
for (int f=0; f < 4; ++f) tileData[t][p][f] = new uint16_t[64];
for (int i=0; i < 32; ++i) {
tileData[t][p][0][2*i] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]);
tileData[t][p][0][2*i+1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][1][8*(i/4)+7-2*(i%4)] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //X-flip
tileData[t][p][1][8*(i/4)+7-2*(i%4)-1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][2][56-8*(i/4)+2*(i%4)] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //Y-flip
tileData[t][p][2][56-8*(i/4)+2*(i%4)+1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
tileData[t][p][3][63-2*i] = getrgb(palette[p][(tilebuffer[i] & 0xF0)>>4]); //XY-flip
tileData[t][p][3][63-2*i-1] = getrgb(palette[p][(tilebuffer[i] & 0x0F)]);
}
}
}
fclose(tilefile);
remove(filename);
}
void Graphics::CreateTiles(){
tiles = new SDL_Surface***[tileAmount];
for (int t=0; t < tileAmount; ++t)
{
tiles[t] = new SDL_Surface**[paletteLines];
for (int p=0; p < paletteLines; ++p)
{
tiles[t][p] = new SDL_Surface*[4];
for (int f=0; f < 4; ++f)
tiles[t][p][f] = InitSurface(tileData[t][p][f], 8, 8, 16);
}
}
}
SDL_Surface* Graphics::InitSurface(uint16_t *pixelsT, int width, int height, int bbp) {
void* pixels = pixelsT;
SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (pixels, width,
height, bbp, width*((bbp+7)/8), 0x0F00, 0x00F0, 0x000F, 0xF000);
if (surface == NULL)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Cannot make SDL Surface from tiles", SDL_GetError(), NULL);
return(surface);
}
void Graphics::DrawSurface(SDL_Surface *img, SDL_Surface *screen, int x, int y) {
SDL_Rect RectTemp;
RectTemp.x = x;
RectTemp.y = y;
SDL_BlitSurface(img, NULL, screen, &RectTemp);
}
void Graphics::ClearMap() {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
SDL_Rect RectTemp;
RectTemp.x = 0;
RectTemp.y = 0;
RectTemp.w = selXMin-1;
RectTemp.h = SCREEN_HEIGHT;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::ClearSelector() {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
SDL_Rect RectTemp;
RectTemp.x = selXMin;
RectTemp.y = 0;
RectTemp.w = 8*selectorWidth;
RectTemp.h = SCREEN_HEIGHT;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::DrawSelector() {
ClearSelector();
for (int i=0; i < tileAmount; ++i)
DrawSurface(tiles[i][currentPal][0], this->screen, selXMin + 8*(i%selectorWidth), 8*(i/selectorWidth - selTileYOffset));
//SDL_Flip(screen);
ProcessDisplay();
}
void Graphics::ProcessDisplay()
{
SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch);
SDL_RenderClear(render);
SDL_RenderCopy(render, texture, NULL, NULL);
SDL_RenderPresent(render);
}
/* map coords */
void Graphics::DrawTileSingle(int x, int y, Tile tile) {
y -= screenTileYOffset;
x -= screenTileXOffset;
if (x >= xDisplaySize) return;
if ((tile.priority && highPriorityDisplay) || (!tile.priority && lowPriorityDisplay)) {
if ((tile.tileID) - tileOffset >= this->tileAmount) {
DrawTileNone(x, y);
DrawTileInvalid(x, y);
} else if ((tile.tileID || !this->tileOffset) && tile.paletteLine < paletteLines)
DrawSurface(tiles[(tile.tileID) - tileOffset][tile.paletteLine][tile.xFlip | (tile.yFlip<<1)], screen, 8*x, 8*y);
else DrawTileBlank(x, y, tile);
} else DrawTileNone(x, y);
}
bool Graphics::CheckSelValidPos(int x, int y) {
if (x>=selXMin && x<selXMin+8*selectorWidth && y>=0 && (x-selXMin)/8+selectorWidth*(y/8 + selTileYOffset)<GetTileAmount()) return true;
else return false;
}
void Graphics::DrawTileNone(int x, int y) {
Uint32 color = SDL_MapRGB(screen->format, 0, 0, 0);
DrawTileFullColor(x, y, color);
}
void Graphics::DrawTileBlank(int x, int y, Tile tile) {
Uint32 color = SDL_MapRGB(
screen->format,
(palette[tile.paletteLine][0] & 0x0F00)>>4,
(palette[tile.paletteLine][0] & 0x00F0),
(palette[tile.paletteLine][0] & 0x000F)<<4
);
DrawTileFullColor(x, y, color);
}
void Graphics::DrawTileFullColor(int x, int y, Uint32 color) {
SDL_Rect RectTemp;
RectTemp.x = 8*x;
RectTemp.y = 8*y;
RectTemp.w = 8;
RectTemp.h = 8;
SDL_FillRect(this->screen, &RectTemp, color);
}
void Graphics::DrawTileInvalid(int x, int y) {
//PosTileToScreen(&x, &y);
for (int i=0; i < 8; ++i) {
DrawPixel(8*x+i, 8*y+i);
DrawPixel(8*x+i, 8*y+7-i);
}
}
void Graphics::DrawPixel(int x, int y) {
if (x<0 || x>=SCREEN_WIDTH || y<0 || y>=SCREEN_HEIGHT) return;
Uint32 color = SDL_MapRGB(screen->format, 0xE0, 0xB0, 0xD0);
Uint32 *pixel;
pixel = (Uint32*) screen->pixels + y*screen->pitch/4 + x;
*pixel = color;
}
/* map coords */
void Graphics::DrawRect(int x, int y) {
PosTileToScreen(&x, &y);
for (int i=0; i < 8; ++i) {
DrawPixel(x+i, y);
DrawPixel(x+i, y+7);
DrawPixel(x, y+i);
DrawPixel(x+7, y+i);
}
}
/* map coords */
void Graphics::DrawFreeRect(int x, int y, int xSize, int ySize) {
PosTileToScreen(&x, &y);
for (int i=0; i < 8*ySize; ++i) {
DrawPixel(x, y+i);
DrawPixel(x + 8*xSize - 1, y+i);
}
for (int i=0; i < 8*xSize; ++i) {
DrawPixel(x+i, y);
DrawPixel(x+i, y + 8*ySize - 1);
}
}
void Graphics::PosScreenToTile(int* x, int* y) {
*x /= 8;
*y /= 8;
*y += screenTileYOffset;
*x += screenTileXOffset;
}
void Graphics::PosScreenToTileRound(int* x, int* y) {
*x = ((*x)+4)/8;
*y = ((*y)+4)/8;
*y += screenTileYOffset;
*x += screenTileXOffset;
}
void Graphics::PosTileToScreen(int* x, int* y) {
*y -= screenTileYOffset;
*x -= screenTileXOffset;
*x *= 8;
*y *= 8;
}
<|endoftext|> |
<commit_before>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int main(int /*argc*/, const char** /* argv */ )
{
Mat framebuffer( 160 * 2, 160 * 5, CV_8UC3, cv::Scalar::all(255) );
Mat img( 160, 160, CV_8UC3, cv::Scalar::all(255) );
// Create test image.
{
const Point center( img.rows / 2 , img.cols /2 );
for( int radius = 5; radius < img.rows ; radius += 3.5 )
{
cv::circle( img, center, radius, Scalar(255,0,255) );
}
cv::rectangle( img, Point(0,0), Point(img.rows-1, img.cols-1), Scalar::all(0), 2 );
}
// Draw original image(s).
int top = 0; // Upper images
{
for( int left = 0 ; left < img.rows * 5 ; left += img.rows ){
Mat roi = framebuffer( Rect( left, top, img.rows, img.cols ) );
img.copyTo(roi);
cv::putText( roi, "original", Point(5,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
}
}
// Draw lossy images
top += img.cols; // Lower images
{
struct test_config{
string comment;
uint32_t sampling_factor;
} config [] = {
{ "411", IMWRITE_JPEG_SAMPLING_FACTOR_411 },
{ "420", IMWRITE_JPEG_SAMPLING_FACTOR_420 },
{ "422", IMWRITE_JPEG_SAMPLING_FACTOR_422 },
{ "440", IMWRITE_JPEG_SAMPLING_FACTOR_440 },
{ "444", IMWRITE_JPEG_SAMPLING_FACTOR_444 },
};
const int config_num = 5;
int left = 0;
for ( int i = 0 ; i < config_num; i++ )
{
// Compress images with sampling factor parameter.
vector<int> param;
param.push_back( IMWRITE_JPEG_SAMPLING_FACTOR );
param.push_back( config[i].sampling_factor );
vector<uint8_t> jpeg;
(void) imencode(".jpg", img, jpeg, param );
// Decompress it.
Mat jpegMat(jpeg);
Mat lossy_img = imdecode(jpegMat, -1);
// Copy into framebuffer and comment
Mat roi = framebuffer( Rect( left, top, lossy_img.rows, lossy_img.cols ) );
lossy_img.copyTo(roi);
cv::putText( roi, config[i].comment, Point(5,155), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
left += lossy_img.rows;
}
}
// Output framebuffer(as lossless).
imwrite( "imgcodecs_jpeg_samplingfactor_result.png", framebuffer );
return 0;
}
<commit_msg>build: fix warnings<commit_after>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int main(int /*argc*/, const char** /* argv */ )
{
Mat framebuffer( 160 * 2, 160 * 5, CV_8UC3, cv::Scalar::all(255) );
Mat img( 160, 160, CV_8UC3, cv::Scalar::all(255) );
// Create test image.
{
const Point center( img.rows / 2 , img.cols /2 );
for( int radius = 5; radius < img.rows ; radius += 3 )
{
cv::circle( img, center, radius, Scalar(255,0,255) );
}
cv::rectangle( img, Point(0,0), Point(img.rows-1, img.cols-1), Scalar::all(0), 2 );
}
// Draw original image(s).
int top = 0; // Upper images
{
for( int left = 0 ; left < img.rows * 5 ; left += img.rows ){
Mat roi = framebuffer( Rect( left, top, img.rows, img.cols ) );
img.copyTo(roi);
cv::putText( roi, "original", Point(5,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
}
}
// Draw lossy images
top += img.cols; // Lower images
{
struct test_config{
string comment;
uint32_t sampling_factor;
} config [] = {
{ "411", IMWRITE_JPEG_SAMPLING_FACTOR_411 },
{ "420", IMWRITE_JPEG_SAMPLING_FACTOR_420 },
{ "422", IMWRITE_JPEG_SAMPLING_FACTOR_422 },
{ "440", IMWRITE_JPEG_SAMPLING_FACTOR_440 },
{ "444", IMWRITE_JPEG_SAMPLING_FACTOR_444 },
};
const int config_num = 5;
int left = 0;
for ( int i = 0 ; i < config_num; i++ )
{
// Compress images with sampling factor parameter.
vector<int> param;
param.push_back( IMWRITE_JPEG_SAMPLING_FACTOR );
param.push_back( config[i].sampling_factor );
vector<uint8_t> jpeg;
(void) imencode(".jpg", img, jpeg, param );
// Decompress it.
Mat jpegMat(jpeg);
Mat lossy_img = imdecode(jpegMat, -1);
// Copy into framebuffer and comment
Mat roi = framebuffer( Rect( left, top, lossy_img.rows, lossy_img.cols ) );
lossy_img.copyTo(roi);
cv::putText( roi, config[i].comment, Point(5,155), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
left += lossy_img.rows;
}
}
// Output framebuffer(as lossless).
imwrite( "imgcodecs_jpeg_samplingfactor_result.png", framebuffer );
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) [2014-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "storage/Utils/XmlFile.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Filesystems/MountableImpl.h"
#include "storage/Filesystems/BlkFilesystemImpl.h"
#include "storage/Filesystems/FilesystemImpl.h"
#include "storage/Filesystems/MountPointImpl.h"
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Holders/User.h"
#include "storage/Devicegraph.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/StorageImpl.h"
#include "storage/Redirect.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Mountable>::classname = "Mountable";
// strings must match /etc/fstab
const vector<string> EnumTraits<FsType>::names({
"unknown", "reiserfs", "ext2", "ext3", "ext4", "btrfs", "vfat", "xfs", "jfs", "hfs",
"ntfs", "swap", "hfsplus", "nfs", "nfs4", "tmpfs", "iso9660", "udf", "nilfs2"
});
const vector<string> EnumTraits<MountByType>::names({
"device", "uuid", "label", "id", "path"
});
Mountable::Impl::Impl(const xmlNode* node)
: Device::Impl(node)
{
}
void
Mountable::Impl::save(xmlNode* node) const
{
Device::Impl::save(node);
}
MountPoint*
Mountable::Impl::create_mount_point(const string& path)
{
Devicegraph* devicegraph = get_devicegraph();
MountPoint* mount_point = MountPoint::create(devicegraph, path);
User::create(devicegraph, get_device(), mount_point);
mount_point->set_default_mount_by();
mount_point->set_default_mount_options();
return mount_point;
}
bool
Mountable::Impl::has_mount_point() const
{
return num_children_of_type<const MountPoint>() > 0;
}
MountPoint*
Mountable::Impl::get_mount_point()
{
vector<MountPoint*> tmp = get_children_of_type<MountPoint>();
if (tmp.empty())
ST_THROW(Exception("no mount point"));
return tmp.front();
}
const MountPoint*
Mountable::Impl::get_mount_point() const
{
vector<const MountPoint*> tmp = get_children_of_type<const MountPoint>();
if (tmp.empty())
ST_THROW(Exception("no mount point"));
return tmp.front();
}
MountOpts
Mountable::Impl::get_default_mount_options() const
{
return MountOpts();
}
FstabEntry*
Mountable::Impl::find_etc_fstab_entry(EtcFstab& etc_fstab, const vector<string>& names) const
{
return etc_fstab.find_device(names);
}
const FstabEntry*
Mountable::Impl::find_etc_fstab_entry(const EtcFstab& etc_fstab, const vector<string>& names) const
{
return etc_fstab.find_device(names);
}
Text
Mountable::Impl::do_mount_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Mount %1$s at %2$s"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Mounting %1$s at %2$s"));
return sformat(text, get_mount_name().c_str(), mount_point->get_path().c_str());
}
void
Mountable::Impl::do_mount(CommitData& commit_data, const MountPoint* mount_point) const
{
const Storage& storage = commit_data.actiongraph.get_storage();
string real_mount_point = storage.get_impl().prepend_rootprefix(mount_point->get_path());
if (access(real_mount_point.c_str(), R_OK ) != 0)
{
createPath(real_mount_point);
}
string cmd_line = MOUNTBIN " -t " + toString(get_mount_type());
if (!mount_point->get_mount_options().empty())
cmd_line += " -o " + quote(mount_point->get_impl().get_mount_options().format());
cmd_line += " " + quote(get_mount_name()) + " " + quote(real_mount_point);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("mount failed"));
if (mount_point->get_path() == "/")
{
string path = get_storage()->prepend_rootprefix("/etc");
if (access(path.c_str(), R_OK) != 0)
createPath(path);
}
}
Text
Mountable::Impl::do_umount_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Unmount %1$s at %2$s"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Unmounting %1$s at %2$s"));
return sformat(text, get_mount_name().c_str(), mount_point->get_path().c_str());
}
void
Mountable::Impl::do_umount(CommitData& commit_data, const MountPoint* mount_point) const
{
const Storage& storage = commit_data.actiongraph.get_storage();
string real_mountpoint = storage.get_impl().prepend_rootprefix(mount_point->get_path());
string cmd_line = UMOUNTBIN " " + quote(real_mountpoint);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("umount failed"));
}
Text
Mountable::Impl::do_add_to_etc_fstab_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Add mount point %1$s of %2$s to /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Adding mount point %1$s of %2$s to /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_add_to_etc_fstab(CommitData& commit_data, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = new FstabEntry();
entry->set_device(get_mount_by_name());
entry->set_mount_point(mount_point->get_path());
entry->set_mount_opts(mount_point->get_impl().get_mount_options());
entry->set_fs_type(get_mount_type());
entry->set_fsck_pass(mount_point->get_passno());
entry->set_dump_pass(mount_point->get_freq());
etc_fstab.add(entry);
etc_fstab.log_diff();
etc_fstab.write();
}
Text
Mountable::Impl::do_update_in_etc_fstab_text(const MountPoint* mount_point, const Device* lhs, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Update mount point %1$s of %2$s in /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Updating mount point %1$s of %2$s in /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_update_in_etc_fstab(CommitData& commit_data, const Device* lhs, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = find_etc_fstab_entry(etc_fstab, { mount_point->get_impl().get_fstab_device_name() });
if (entry)
{
entry->set_device(get_mount_by_name());
entry->set_mount_point(mount_point->get_path());
entry->set_mount_opts(mount_point->get_impl().get_mount_options());
entry->set_fs_type(get_mount_type());
entry->set_fsck_pass(mount_point->get_passno());
entry->set_dump_pass(mount_point->get_freq());
etc_fstab.log_diff();
etc_fstab.write();
}
}
Text
Mountable::Impl::do_remove_from_etc_fstab_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Remove mount point %1$s of %2$s from /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Removing mount point %1$s of %2$s from /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_remove_from_etc_fstab(CommitData& commit_data, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = find_etc_fstab_entry(etc_fstab, { mount_point->get_impl().get_fstab_device_name() });
if (entry)
{
etc_fstab.remove(entry);
etc_fstab.log_diff();
etc_fstab.write();
}
}
EnsureMounted::EnsureMounted(const Mountable* mountable, bool read_only)
: mountable(mountable), read_only(read_only), tmp_mount()
{
y2mil("EnsureMounted " << *mountable);
bool need_mount = false;
if (mountable->get_impl().get_devicegraph()->get_impl().is_probed())
{
// Called on probed devicegraph.
need_mount = !mountable_has_active_mount_point();
}
else
{
// Not called on probed devicegraph.
if (is_blk_filesystem(mountable))
{
// The names of BlkDevices may have changed so redirect to the
// Mountable in the probed devicegraph.
mountable = redirect_to_probed(mountable);
need_mount = !mountable_has_active_mount_point();
}
else
{
// Nfs can be temporarily mounted on any devicegraph. But the
// list of mountpoints is only useful for the probed
// devicegraph, so redirect if the mountable exists there to
// avoid unnecessary temporary mounts.
if (mountable->exists_in_probed())
{
mountable = redirect_to_probed(mountable);
need_mount = !mountable_has_active_mount_point();
}
else
{
need_mount = true;
}
}
}
y2mil("EnsureMounted need_mount:" << need_mount);
if (!need_mount)
return;
const Storage* storage = mountable->get_impl().get_storage();
if (is_blk_filesystem(mountable))
{
const BlkFilesystem* blk_filesystem = to_blk_filesystem(mountable);
for (const BlkDevice* blk_device : blk_filesystem->get_blk_devices())
blk_device->get_impl().wait_for_device();
}
tmp_mount.reset(new TmpMount(storage->get_impl().get_tmp_dir().get_fullname(),
"tmp-mount-XXXXXX", mountable->get_impl().get_mount_name(),
read_only, mountable->get_impl().get_mount_options()));
}
string
EnsureMounted::get_any_mount_point() const
{
if (tmp_mount)
return tmp_mount->get_fullname();
else
return mountable->get_mount_point()->get_path();
}
bool
EnsureMounted::mountable_has_active_mount_point() const
{
if (!mountable->has_mount_point())
return false;
return mountable->get_mount_point()->is_active();
}
}
<commit_msg>- consistent naming<commit_after>/*
* Copyright (c) [2014-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "storage/Utils/XmlFile.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Filesystems/MountableImpl.h"
#include "storage/Filesystems/BlkFilesystemImpl.h"
#include "storage/Filesystems/FilesystemImpl.h"
#include "storage/Filesystems/MountPointImpl.h"
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Holders/User.h"
#include "storage/Devicegraph.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/StorageImpl.h"
#include "storage/Redirect.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Mountable>::classname = "Mountable";
// strings must match /etc/fstab
const vector<string> EnumTraits<FsType>::names({
"unknown", "reiserfs", "ext2", "ext3", "ext4", "btrfs", "vfat", "xfs", "jfs", "hfs",
"ntfs", "swap", "hfsplus", "nfs", "nfs4", "tmpfs", "iso9660", "udf", "nilfs2"
});
const vector<string> EnumTraits<MountByType>::names({
"device", "uuid", "label", "id", "path"
});
Mountable::Impl::Impl(const xmlNode* node)
: Device::Impl(node)
{
}
void
Mountable::Impl::save(xmlNode* node) const
{
Device::Impl::save(node);
}
MountPoint*
Mountable::Impl::create_mount_point(const string& path)
{
Devicegraph* devicegraph = get_devicegraph();
MountPoint* mount_point = MountPoint::create(devicegraph, path);
User::create(devicegraph, get_device(), mount_point);
mount_point->set_default_mount_by();
mount_point->set_default_mount_options();
return mount_point;
}
bool
Mountable::Impl::has_mount_point() const
{
return num_children_of_type<const MountPoint>() > 0;
}
MountPoint*
Mountable::Impl::get_mount_point()
{
vector<MountPoint*> tmp = get_children_of_type<MountPoint>();
if (tmp.empty())
ST_THROW(Exception("no mount point"));
return tmp.front();
}
const MountPoint*
Mountable::Impl::get_mount_point() const
{
vector<const MountPoint*> tmp = get_children_of_type<const MountPoint>();
if (tmp.empty())
ST_THROW(Exception("no mount point"));
return tmp.front();
}
MountOpts
Mountable::Impl::get_default_mount_options() const
{
return MountOpts();
}
FstabEntry*
Mountable::Impl::find_etc_fstab_entry(EtcFstab& etc_fstab, const vector<string>& names) const
{
return etc_fstab.find_device(names);
}
const FstabEntry*
Mountable::Impl::find_etc_fstab_entry(const EtcFstab& etc_fstab, const vector<string>& names) const
{
return etc_fstab.find_device(names);
}
Text
Mountable::Impl::do_mount_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Mount %1$s at %2$s"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Mounting %1$s at %2$s"));
return sformat(text, get_mount_name().c_str(), mount_point->get_path().c_str());
}
void
Mountable::Impl::do_mount(CommitData& commit_data, const MountPoint* mount_point) const
{
const Storage& storage = commit_data.actiongraph.get_storage();
string real_mount_point = storage.get_impl().prepend_rootprefix(mount_point->get_path());
if (access(real_mount_point.c_str(), R_OK ) != 0)
{
createPath(real_mount_point);
}
string cmd_line = MOUNTBIN " -t " + toString(get_mount_type());
if (!mount_point->get_mount_options().empty())
cmd_line += " -o " + quote(mount_point->get_impl().get_mount_options().format());
cmd_line += " " + quote(get_mount_name()) + " " + quote(real_mount_point);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("mount failed"));
if (mount_point->get_path() == "/")
{
string path = get_storage()->prepend_rootprefix("/etc");
if (access(path.c_str(), R_OK) != 0)
createPath(path);
}
}
Text
Mountable::Impl::do_umount_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Unmount %1$s at %2$s"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by device name (e.g. /dev/sda1),
// %2$s is replaced by size (e.g. 2GiB)
_("Unmounting %1$s at %2$s"));
return sformat(text, get_mount_name().c_str(), mount_point->get_path().c_str());
}
void
Mountable::Impl::do_umount(CommitData& commit_data, const MountPoint* mount_point) const
{
const Storage& storage = commit_data.actiongraph.get_storage();
string real_mount_point = storage.get_impl().prepend_rootprefix(mount_point->get_path());
string cmd_line = UMOUNTBIN " " + quote(real_mount_point);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("umount failed"));
}
Text
Mountable::Impl::do_add_to_etc_fstab_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Add mount point %1$s of %2$s to /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Adding mount point %1$s of %2$s to /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_add_to_etc_fstab(CommitData& commit_data, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = new FstabEntry();
entry->set_device(get_mount_by_name());
entry->set_mount_point(mount_point->get_path());
entry->set_mount_opts(mount_point->get_impl().get_mount_options());
entry->set_fs_type(get_mount_type());
entry->set_fsck_pass(mount_point->get_passno());
entry->set_dump_pass(mount_point->get_freq());
etc_fstab.add(entry);
etc_fstab.log_diff();
etc_fstab.write();
}
Text
Mountable::Impl::do_update_in_etc_fstab_text(const MountPoint* mount_point, const Device* lhs, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Update mount point %1$s of %2$s in /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Updating mount point %1$s of %2$s in /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_update_in_etc_fstab(CommitData& commit_data, const Device* lhs, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = find_etc_fstab_entry(etc_fstab, { mount_point->get_impl().get_fstab_device_name() });
if (entry)
{
entry->set_device(get_mount_by_name());
entry->set_mount_point(mount_point->get_path());
entry->set_mount_opts(mount_point->get_impl().get_mount_options());
entry->set_fs_type(get_mount_type());
entry->set_fsck_pass(mount_point->get_passno());
entry->set_dump_pass(mount_point->get_freq());
etc_fstab.log_diff();
etc_fstab.write();
}
}
Text
Mountable::Impl::do_remove_from_etc_fstab_text(const MountPoint* mount_point, Tense tense) const
{
Text text = tenser(tense,
// TRANSLATORS: displayed before action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Remove mount point %1$s of %2$s from /etc/fstab"),
// TRANSLATORS: displayed during action,
// %1$s is replaced by mount point (e.g. /home),
// %2$s is replaced by device name (e.g. /dev/sda1)
_("Removing mount point %1$s of %2$s from /etc/fstab"));
return sformat(text, mount_point->get_path().c_str(), get_mount_name().c_str());
}
void
Mountable::Impl::do_remove_from_etc_fstab(CommitData& commit_data, const MountPoint* mount_point) const
{
EtcFstab& etc_fstab = commit_data.get_etc_fstab();
FstabEntry* entry = find_etc_fstab_entry(etc_fstab, { mount_point->get_impl().get_fstab_device_name() });
if (entry)
{
etc_fstab.remove(entry);
etc_fstab.log_diff();
etc_fstab.write();
}
}
EnsureMounted::EnsureMounted(const Mountable* mountable, bool read_only)
: mountable(mountable), read_only(read_only), tmp_mount()
{
y2mil("EnsureMounted " << *mountable);
bool need_mount = false;
if (mountable->get_impl().get_devicegraph()->get_impl().is_probed())
{
// Called on probed devicegraph.
need_mount = !mountable_has_active_mount_point();
}
else
{
// Not called on probed devicegraph.
if (is_blk_filesystem(mountable))
{
// The names of BlkDevices may have changed so redirect to the
// Mountable in the probed devicegraph.
mountable = redirect_to_probed(mountable);
need_mount = !mountable_has_active_mount_point();
}
else
{
// Nfs can be temporarily mounted on any devicegraph. But the
// list of mountpoints is only useful for the probed
// devicegraph, so redirect if the mountable exists there to
// avoid unnecessary temporary mounts.
if (mountable->exists_in_probed())
{
mountable = redirect_to_probed(mountable);
need_mount = !mountable_has_active_mount_point();
}
else
{
need_mount = true;
}
}
}
y2mil("EnsureMounted need_mount:" << need_mount);
if (!need_mount)
return;
const Storage* storage = mountable->get_impl().get_storage();
if (is_blk_filesystem(mountable))
{
const BlkFilesystem* blk_filesystem = to_blk_filesystem(mountable);
for (const BlkDevice* blk_device : blk_filesystem->get_blk_devices())
blk_device->get_impl().wait_for_device();
}
tmp_mount.reset(new TmpMount(storage->get_impl().get_tmp_dir().get_fullname(),
"tmp-mount-XXXXXX", mountable->get_impl().get_mount_name(),
read_only, mountable->get_impl().get_mount_options()));
}
string
EnsureMounted::get_any_mount_point() const
{
if (tmp_mount)
return tmp_mount->get_fullname();
else
return mountable->get_mount_point()->get_path();
}
bool
EnsureMounted::mountable_has_active_mount_point() const
{
if (!mountable->has_mount_point())
return false;
return mountable->get_mount_point()->is_active();
}
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of audio output
*
* @author Lorenz Meier <[email protected]>
*
*/
#include <QApplication>
#include <QSettings>
#include <QTemporaryFile>
#include "GAudioOutput.h"
#include "MG.h"
#include <QDebug>
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
//using System;
//using System.Speech.Synthesis;
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
espeak_POSITION_TYPE espeak_position_type;
espeak_AUDIO_OUTPUT espeak_output = AUDIO_OUTPUT_PLAYBACK;
int espeak_buflength = 500;
int espeak_options = 0;
char *espeak_path = NULL;
unsigned int espeak_flags=espeakCHARS_AUTO;
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
ISpVoice *GAudioOutput::pVoice = NULL;
#endif
/**
* This class follows the singleton design pattern
* @see http://en.wikipedia.org/wiki/Singleton_pattern
* A call to this function thus returns the only instance of this object
* the call can occur at any place in the code, no reference to the
* GAudioOutput object has to be passed.
*/
GAudioOutput *GAudioOutput::instance()
{
static GAudioOutput *_instance = 0;
if (_instance == 0)
{
_instance = new GAudioOutput();
// Set the application as parent to ensure that this object
// will be destroyed when the main application exits
_instance->setParent(qApp);
}
return _instance;
}
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
GAudioOutput::GAudioOutput(QObject *parent) : QObject(parent),
voiceIndex(0),
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
settings.sync();
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(espeak_output, espeak_buflength, espeak_path, espeak_options );
const char *espeak_langNativeString = "en-uk"; //Default to US English
espeak_VOICE espeak_voice;
memset(&espeak_voice, 0, sizeof(espeak_VOICE)); // Zero out the voice first
espeak_voice.languages = espeak_langNativeString;
espeak_voice.name = "klatt";
espeak_voice.variant = 0;
espeak_voice.gender = 2;
espeak_SetVoiceByProperties(&espeak_voice);
espeak_PARAMETER rateParam = espeakRATE;
// espeak_SetParameter(rateParam , 150, 0);
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//hr = pVoice->Speak(L"QGC audio output active!", 0, NULL);
//pVoice->Release();
//pVoice = NULL;
}
}
#endif
// Initialize audio output
m_media = new Phonon::MediaObject(this);
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
createPath(m_media, audioOutput);
// Prepare regular emergency signal, will be fired off on calling startEmergency()
emergencyTimer = new QTimer();
connect(emergencyTimer, SIGNAL(timeout()), this, SLOT(beep()));
switch (voiceIndex)
{
case 0:
selectFemaleVoice();
break;
default:
selectMaleVoice();
break;
}
}
GAudioOutput::~GAudioOutput()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice->Release();
pVoice = NULL;
::CoUninitialize();
#endif
}
void GAudioOutput::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
settings.sync();
emit mutedChanged(muted);
}
}
bool GAudioOutput::isMuted()
{
return this->muted;
}
bool GAudioOutput::say(QString text, int severity)
{
if (!muted)
{
// TODO Add severity filter
Q_UNUSED(severity);
bool res = false;
if (!emergency)
{
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
/*SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SelectVoice("Microsoft Anna");
synth.SpeakText(text.toStdString().c_str());
res = true;*/
/*ISpVoice * pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if( SUCCEEDED( hr ) )
{
hr = */pVoice->Speak(text.toStdWString().c_str(), SPF_ASYNC, NULL);
/*pVoice->WaitUntilDone(5000);
pVoice->Release();
pVoice = NULL;
}
}*/
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
unsigned int espeak_size, espeak_position = 0, espeak_end_position = 0, *espeak_unique_identifier = NULL;
void* espeak_user_data = NULL;
espeak_size = strlen(text.toStdString().c_str());
// qDebug() << "eSpeak: Saying " << text;
espeak_Synth( text.toStdString().c_str(), espeak_size, espeak_position, espeak_position_type, espeak_end_position, espeak_flags,
espeak_unique_identifier, espeak_user_data );
// qDebug() << "Done talking " << text;
#endif
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
QStdWString str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toAscii().data(), str.length());
SpeakString(str2);
res = true;
#endif
}
return res;
}
else
{
return false;
}
}
/**
* @param text This message will be played after the alert beep
*/
bool GAudioOutput::alert(QString text)
{
if (!emergency || !muted)
{
// Play alert sound
beep();
// Say alert message
say(text, 2);
return true;
}
else
{
return false;
}
}
void GAudioOutput::notifyPositive()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/double_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::notifyNegative()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/flat_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
/**
* The emergency sound will be played continously during the emergency.
* call stopEmergency() to disable it again. No speech synthesis or other
* audio output is available during the emergency.
*
* @return true if the emergency could be started, false else
*/
bool GAudioOutput::startEmergency()
{
if (!emergency)
{
emergency = true;
// Beep immediately and then start timer
if (!muted) beep();
emergencyTimer->start(1500);
QTimer::singleShot(5000, this, SLOT(stopEmergency()));
}
return true;
}
/**
* Stops the continous emergency sound. Use startEmergency() to start
* the emergency sound.
*
* @return true if the emergency could be stopped, false else
*/
bool GAudioOutput::stopEmergency()
{
if (emergency)
{
emergency = false;
emergencyTimer->stop();
}
return true;
}
void GAudioOutput::beep()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/alert.wav"));
qDebug() << "FILE:" << f.fileName();
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::selectFemaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_slt(NULL);
#endif
}
void GAudioOutput::selectMaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_rms(NULL);
#endif
}
/*
void GAudioOutput::selectNeutralVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
this->voice = register_cmu_us_awb(NULL);
#endif
}*/
QStringList GAudioOutput::listVoices(void)
{
QStringList l;
return l;
}
<commit_msg>fix merge errors and unused-variable error<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of audio output
*
* @author Lorenz Meier <[email protected]>
*
*/
#include <QApplication>
#include <QSettings>
#include <QTemporaryFile>
#include "GAudioOutput.h"
#include "MG.h"
#include <QDebug>
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
#include <ApplicationServices/ApplicationServices.h>
#endif
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
// Documentation: http://msdn.microsoft.com/en-us/library/ee125082%28v=VS.85%29.aspx
#include <sapi.h>
//using System;
//using System.Speech.Synthesis;
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
// Using eSpeak for speech synthesis: following https://github.com/mondhs/espeak-sample/blob/master/sampleSpeak.cpp
#include <espeak/speak_lib.h>
espeak_POSITION_TYPE espeak_position_type;
espeak_AUDIO_OUTPUT espeak_output = AUDIO_OUTPUT_PLAYBACK;
int espeak_buflength = 500;
int espeak_options = 0;
char *espeak_path = NULL;
unsigned int espeak_flags=espeakCHARS_AUTO;
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
ISpVoice *GAudioOutput::pVoice = NULL;
#endif
/**
* This class follows the singleton design pattern
* @see http://en.wikipedia.org/wiki/Singleton_pattern
* A call to this function thus returns the only instance of this object
* the call can occur at any place in the code, no reference to the
* GAudioOutput object has to be passed.
*/
GAudioOutput *GAudioOutput::instance()
{
static GAudioOutput *_instance = 0;
if (_instance == 0)
{
_instance = new GAudioOutput();
// Set the application as parent to ensure that this object
// will be destroyed when the main application exits
_instance->setParent(qApp);
}
return _instance;
}
#define QGC_GAUDIOOUTPUT_KEY QString("QGC_AUDIOOUTPUT_")
GAudioOutput::GAudioOutput(QObject *parent) : QObject(parent),
voiceIndex(0),
emergency(false),
muted(false)
{
// Load settings
QSettings settings;
settings.sync();
muted = settings.value(QGC_GAUDIOOUTPUT_KEY + "muted", muted).toBool();
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
espeak_Initialize(espeak_output, espeak_buflength, espeak_path, espeak_options );
const char *espeak_langNativeString = "en-uk"; //Default to US English
espeak_VOICE espeak_voice;
memset(&espeak_voice, 0, sizeof(espeak_VOICE)); // Zero out the voice first
espeak_voice.languages = espeak_langNativeString;
espeak_voice.name = "klatt";
espeak_voice.variant = 0;
espeak_voice.gender = 2;
espeak_SetVoiceByProperties(&espeak_voice);
// Rate of eSpeak can be changed if needed:
// espeak_PARAMETER rateParam = espeakRATE;
// espeak_SetParameter(rateParam , 150, 0);
#endif
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//hr = pVoice->Speak(L"QGC audio output active!", 0, NULL);
//pVoice->Release();
//pVoice = NULL;
}
}
#endif
// Initialize audio output
m_media = new Phonon::MediaObject(this);
Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
createPath(m_media, audioOutput);
// Prepare regular emergency signal, will be fired off on calling startEmergency()
emergencyTimer = new QTimer();
connect(emergencyTimer, SIGNAL(timeout()), this, SLOT(beep()));
switch (voiceIndex)
{
case 0:
selectFemaleVoice();
break;
default:
selectMaleVoice();
break;
}
}
GAudioOutput::~GAudioOutput()
{
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
pVoice->Release();
pVoice = NULL;
::CoUninitialize();
#endif
}
void GAudioOutput::mute(bool mute)
{
if (mute != muted)
{
this->muted = mute;
QSettings settings;
settings.setValue(QGC_GAUDIOOUTPUT_KEY + "muted", this->muted);
settings.sync();
emit mutedChanged(muted);
}
}
bool GAudioOutput::isMuted()
{
return this->muted;
}
bool GAudioOutput::say(QString text, int severity)
{
if (!muted)
{
// TODO Add severity filter
Q_UNUSED(severity);
bool res = false;
if (!emergency)
{
// Speech synthesis is only supported with MSVC compiler
#if defined _MSC_VER && defined QGC_SPEECH_ENABLED
/*SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SelectVoice("Microsoft Anna");
synth.SpeakText(text.toStdString().c_str());
res = true;*/
/*ISpVoice * pVoice = NULL;
if (FAILED(::CoInitialize(NULL)))
{
qDebug("Creating COM object for audio output failed!");
}
else
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if( SUCCEEDED( hr ) )
{
hr = */pVoice->Speak(text.toStdWString().c_str(), SPF_ASYNC, NULL);
/*pVoice->WaitUntilDone(5000);
pVoice->Release();
pVoice = NULL;
}
}*/
#endif
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
unsigned int espeak_size, espeak_position = 0, espeak_end_position = 0, *espeak_unique_identifier = NULL;
void* espeak_user_data = NULL;
espeak_size = strlen(text.toStdString().c_str());
// qDebug() << "eSpeak: Saying " << text;
espeak_Synth( text.toStdString().c_str(), espeak_size, espeak_position, espeak_position_type, espeak_end_position, espeak_flags,
espeak_unique_identifier, espeak_user_data );
// qDebug() << "Done talking " << text;
#endif
#if defined Q_OS_MAC && defined QGC_SPEECH_ENABLED
// Slashes necessary to have the right start to the sentence
// copying data prevents SpeakString from reading additional chars
text = "\\" + text;
QStdWString str = text.toStdWString();
unsigned char str2[1024] = {};
memcpy(str2, text.toAscii().data(), str.length());
SpeakString(str2);
res = true;
#endif
}
return res;
}
else
{
return false;
}
}
/**
* @param text This message will be played after the alert beep
*/
bool GAudioOutput::alert(QString text)
{
if (!emergency || !muted)
{
// Play alert sound
beep();
// Say alert message
say(text, 2);
return true;
}
else
{
return false;
}
}
void GAudioOutput::notifyPositive()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/double_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::notifyNegative()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/flat_notify.wav"));
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
/**
* The emergency sound will be played continously during the emergency.
* call stopEmergency() to disable it again. No speech synthesis or other
* audio output is available during the emergency.
*
* @return true if the emergency could be started, false else
*/
bool GAudioOutput::startEmergency()
{
if (!emergency)
{
emergency = true;
// Beep immediately and then start timer
if (!muted) beep();
emergencyTimer->start(1500);
QTimer::singleShot(5000, this, SLOT(stopEmergency()));
}
return true;
}
/**
* Stops the continous emergency sound. Use startEmergency() to start
* the emergency sound.
*
* @return true if the emergency could be stopped, false else
*/
bool GAudioOutput::stopEmergency()
{
if (emergency)
{
emergency = false;
emergencyTimer->stop();
}
return true;
}
void GAudioOutput::beep()
{
if (!muted)
{
// Use QFile to transform path for all OS
QFile f(QCoreApplication::applicationDirPath() + QString("/files/audio/alert.wav"));
qDebug() << "FILE:" << f.fileName();
//m_media->setCurrentSource(Phonon::MediaSource(f.fileName().toStdString().c_str()));
//m_media->play();
}
}
void GAudioOutput::selectFemaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_slt(NULL);
#endif
}
void GAudioOutput::selectMaleVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
//this->voice = register_cmu_us_rms(NULL);
#endif
}
/*
void GAudioOutput::selectNeutralVoice()
{
#if defined Q_OS_LINUX && defined QGC_SPEECH_ENABLED
this->voice = register_cmu_us_awb(NULL);
#endif
}*/
QStringList GAudioOutput::listVoices(void)
{
QStringList l;
return l;
}
<|endoftext|> |
<commit_before>#include "Client.hpp"
#include <functional>
#include <utility>
#include <exception>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <iostream>
#include "events/IncomingMessage.hpp"
#include "events/OutcomingMessage.hpp"
#include "events/Terminate.hpp"
using tin::network::bsdsocket::wrapper::Client;
namespace events = tin::network::bsdsocket::wrapper::events;
Client::Client():
receiverHelperThread(*this, this->receiverQueue),
transmitterHelperThread(*this, this->transmitterQueue),
visitor(*this)
{
this->run();
}
Client::~Client()
{
this->terminate();
}
void Client::run()
{
this->receiverThread = this->receiverHelperThread.createThread();
this->transmitterThread = this->transmitterHelperThread.createThread();
this->receiverThread.detach();
this->transmitterThread.detach();
}
void Client::terminate()
{
this->receiverHelperThread.terminate();
this->transmitterHelperThread.terminate();
this->receiverQueue.push(
EventPtr(new events::Terminate())
);
this->transmitterQueue.push(
EventPtr(new events::Terminate())
);
}
unsigned int Client::attachResponseReceivedHandler(
std::function<void(const std::string&, const unsigned int&, const std::string&)>& handler
)
{
return this->messageReceivedHandlers.insert(handler);
}
unsigned int Client::attachResponseReceivedHandler(
std::function<void(const std::string&, const unsigned int&, const std::string&)>&& handler
)
{
return this->messageReceivedHandlers.insert(
std::forward<std::function<void(const std::string&, const unsigned int&, const std::string&)>>(handler)
);
}
void Client::sendMessage(
const std::string& ip,
const unsigned int& port,
const std::string& message,
const bool& waitForResponse
)
{
this->transmitterQueue.push(
EventPtr(new events::OutcomingMessage(ip, port, message, waitForResponse))
);
}
void Client::runMessageReceivedHandlers(
const std::string& ip,
const unsigned int& port,
const std::string& message
)
{
for (auto iter: this->messageReceivedHandlers)
{
iter.second(ip, port, message);
}
}
void Client::onMessageRequest(
const std::string& ip,
const unsigned int& port,
const std::string& message,
const bool& waitForResponse
)
{
std::string temp;
int readBufSize = 1024;
char buf[readBufSize + 1];
int rval;
struct sockaddr_in server;
struct hostent *hp;
// Setup
server.sin_family = AF_INET;
// Get IP from name
hp = gethostbyname(ip.c_str());
if (hp == (struct hostent *) 0)
{
return;
// Throw unknown host error
}
memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);
// Get port
server.sin_port = htons(port);
// Create socket
this->socketHandle = socket(AF_INET, SOCK_STREAM, 0);
if (this->socketHandle == -1)
{
return;
// Throw socket open error
}
// Connect to server with created socket
if (connect(this->socketHandle, (struct sockaddr *) &server, sizeof server) == -1)
{
return;
// Throw connection error
}
if (write(this->socketHandle, message.c_str(), message.length() + 1) == -1)
{
return;
// Throw write error
}
if (!waitForResponse)
{
close(this->socketHandle);
return;
}
// Receiving a new message, clear temp
temp.clear();
while(true)
{
// Clear buf
memset(buf, 0, sizeof buf);
// FIXME: when message surpasses buflength, we truncate it
// try to read in chunks
if ((rval = read(this->socketHandle, buf, readBufSize)) == -1)
{
return;
// Throw message read error
}
if (rval == 0)
{
// Reading completed, send message to queue
this->onResponseReceive(ip, port, temp);
break;
}
else
{
// Reading completed, send message to queue
temp.append(buf);
if (buf[rval - 1] != 0)
{
continue;
}
this->onResponseReceive(ip, port, temp);
break;
}
}
close(this->socketHandle);
return;
}
void Client::onResponseReceive(
const std::string& ip,
const unsigned int& port,
const std::string& message
)
{
this->receiverQueue.push(
EventPtr(new events::IncomingMessage(ip, port, message))
);
}
<commit_msg>Handled no Connection case<commit_after>#include "Client.hpp"
#include <functional>
#include <utility>
#include <exception>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <iostream>
#include "events/IncomingMessage.hpp"
#include "events/OutcomingMessage.hpp"
#include "events/Terminate.hpp"
#include "../../../utils/JSON.hpp"
using tin::network::bsdsocket::wrapper::Client;
using nlohmann::json;
namespace events = tin::network::bsdsocket::wrapper::events;
Client::Client():
receiverHelperThread(*this, this->receiverQueue),
transmitterHelperThread(*this, this->transmitterQueue),
visitor(*this)
{
this->run();
}
Client::~Client()
{
this->terminate();
}
void Client::run()
{
this->receiverThread = this->receiverHelperThread.createThread();
this->transmitterThread = this->transmitterHelperThread.createThread();
this->receiverThread.detach();
this->transmitterThread.detach();
}
void Client::terminate()
{
this->receiverHelperThread.terminate();
this->transmitterHelperThread.terminate();
this->receiverQueue.push(
EventPtr(new events::Terminate())
);
this->transmitterQueue.push(
EventPtr(new events::Terminate())
);
}
unsigned int Client::attachResponseReceivedHandler(
std::function<void(const std::string&, const unsigned int&, const std::string&)>& handler
)
{
return this->messageReceivedHandlers.insert(handler);
}
unsigned int Client::attachResponseReceivedHandler(
std::function<void(const std::string&, const unsigned int&, const std::string&)>&& handler
)
{
return this->messageReceivedHandlers.insert(
std::forward<std::function<void(const std::string&, const unsigned int&, const std::string&)>>(handler)
);
}
void Client::sendMessage(
const std::string& ip,
const unsigned int& port,
const std::string& message,
const bool& waitForResponse
)
{
this->transmitterQueue.push(
EventPtr(new events::OutcomingMessage(ip, port, message, waitForResponse))
);
}
void Client::runMessageReceivedHandlers(
const std::string& ip,
const unsigned int& port,
const std::string& message
)
{
for (auto iter: this->messageReceivedHandlers)
{
iter.second(ip, port, message);
}
}
void Client::onMessageRequest(
const std::string& ip,
const unsigned int& port,
const std::string& message,
const bool& waitForResponse
)
{
std::string temp;
int readBufSize = 1024;
char buf[readBufSize + 1];
int rval;
struct sockaddr_in server;
struct hostent *hp;
// Setup
server.sin_family = AF_INET;
// Get IP from name
hp = gethostbyname(ip.c_str());
if (hp == (struct hostent *) 0)
{
return;
// Throw unknown host error
}
memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);
// Get port
server.sin_port = htons(port);
// Create socket
this->socketHandle = socket(AF_INET, SOCK_STREAM, 0);
if (this->socketHandle == -1)
{
return;
// Throw socket open error
}
// Connect to server with created socket
if (connect(this->socketHandle, (struct sockaddr *) &server, sizeof server) == -1)
{
std::string temp2 = message;
temp2.erase(0,8);
temp2.pop_back();
temp2.pop_back();
json j;
j["cmd"] = temp2;
j["error"] = {{"notConnected", true}};
std::string temp3 = j.dump();
this->onResponseReceive(ip, port, temp3);
return;
// Throw connection error
}
if (write(this->socketHandle, message.c_str(), message.length() + 1) == -1)
{
return;
// Throw write error
}
if (!waitForResponse)
{
close(this->socketHandle);
return;
}
// Receiving a new message, clear temp
temp.clear();
while(true)
{
// Clear buf
memset(buf, 0, sizeof buf);
// FIXME: when message surpasses buflength, we truncate it
// try to read in chunks
if ((rval = read(this->socketHandle, buf, readBufSize)) == -1)
{
return;
// Throw message read error
}
if (rval == 0)
{
// Reading completed, send message to queue
this->onResponseReceive(ip, port, temp);
break;
}
else
{
// Reading completed, send message to queue
temp.append(buf);
if (buf[rval - 1] != 0)
{
continue;
}
this->onResponseReceive(ip, port, temp);
break;
}
}
close(this->socketHandle);
return;
}
void Client::onResponseReceive(
const std::string& ip,
const unsigned int& port,
const std::string& message
)
{
this->receiverQueue.push(
EventPtr(new events::IncomingMessage(ip, port, message))
);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.