text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_file.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/features/feature.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace {
FilePath GetTestDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
test_dir = test_dir.AppendASCII("native_messaging");
return test_dir;
}
} // namespace
namespace extensions {
class FakeLauncher : public NativeProcessLauncher {
public:
FakeLauncher(FilePath read_file, FilePath write_file) {
read_file_ = base::CreatePlatformFile(
read_file,
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
NULL, NULL);
write_file_ = base::CreatePlatformFile(
write_file,
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_WRITE,
NULL, NULL);
}
virtual bool LaunchNativeProcess(
const FilePath& path,
base::ProcessHandle* native_process_handle,
NativeMessageProcessHost::FileHandle* read_file,
NativeMessageProcessHost::FileHandle* write_file) const OVERRIDE {
*native_process_handle = base::kNullProcessHandle;
*read_file = read_file_;
*write_file = write_file_;
return true;
}
private:
base::PlatformFile read_file_;
base::PlatformFile write_file_;
};
class NativeMessagingTest : public ::testing::Test,
public NativeMessageProcessHost::Client,
public base::SupportsWeakPtr<NativeMessagingTest> {
public:
NativeMessagingTest() : current_channel_(chrome::VersionInfo::CHANNEL_DEV) {
}
virtual void SetUp() {
// Change the user data dir so native apps will be looked for in the test
// directory.
ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_));
ASSERT_TRUE(PathService::Override(chrome::DIR_USER_DATA, GetTestDir()));
ui_thread_.reset(new content::TestBrowserThread(BrowserThread::UI,
&message_loop_));
file_thread_.reset(new content::TestBrowserThread(BrowserThread::FILE,
&message_loop_));
}
virtual void TearDown() {
// Change the user data dir back for other tests.
ASSERT_TRUE(PathService::Override(chrome::DIR_USER_DATA, user_data_dir_));
BrowserThread::DeleteSoon(BrowserThread::FILE, FROM_HERE,
native_message_process_host_);
message_loop_.RunAllPending();
}
void PostMessageFromNativeProcess(int port_id, const std::string& message) {
last_posted_message_ = message;
}
void CloseChannel(int port_id, bool error) {
}
void AcquireProcess(NativeMessageProcessHost::ScopedHost process) {
native_message_process_host_ = process.release();
}
protected:
// Force the channel to be dev.
Feature::ScopedCurrentChannel current_channel_;
NativeMessageProcessHost* native_message_process_host_;
FilePath user_data_dir_;
MessageLoopForIO message_loop_;
scoped_ptr<content::TestBrowserThread> ui_thread_;
scoped_ptr<content::TestBrowserThread> file_thread_;
std::string last_posted_message_;
};
// Read a single message from a local file (single_message_response.msg).
TEST_F(NativeMessagingTest, SingleSendMessageRead) {
FilePath temp_file;
file_util::CreateTemporaryFile(&temp_file);
FakeLauncher launcher(GetTestDir().AppendASCII("single_message_response.msg"),
temp_file);
NativeMessageProcessHost::CreateWithLauncher(
AsWeakPtr(), "empty_app.py", "{}", 0,
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()),
launcher);
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_, "{\"text\": \"Hi There!.\"}");
file_util::Delete(temp_file, false /* non-recursive */);
}
// Tests sending a single message. The message should get written to
// |temp_file| and should match the contents of single_message_request.msg.
TEST_F(NativeMessagingTest, SingleSendMessageWrite) {
FilePath temp_file;
file_util::CreateTemporaryFile(&temp_file);
FakeLauncher launcher(GetTestDir().AppendASCII("single_message_response.msg"),
temp_file);
NativeMessageProcessHost::CreateWithLauncher(
AsWeakPtr(), "empty_app.py", "{\"text\": \"Hello.\"}", 0,
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()),
launcher);
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
EXPECT_TRUE(file_util::ContentsEqual(
temp_file, GetTestDir().AppendASCII("single_message_request.msg")));
file_util::Delete(temp_file, false /* non-recursive */);
}
// Test send message with a real client. The client just echo's back the text
// it recieved.
TEST_F(NativeMessagingTest, EchoConnect) {
NativeMessageProcessHost::Create(
AsWeakPtr(), "echo.py", "{\"text\": \"Hello.\"}", 0,
NativeMessageProcessHost::TYPE_CONNECT, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()));
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_,
"{\"id\": 1, \"echo\": {\"text\": \"Hello.\"}}");
native_message_process_host_->Send("{\"foo\": \"bar\"}");
message_loop_.RunAllPending();
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_, "{\"id\": 2, \"echo\": {\"foo\": \"bar\"}}");
}
} // namespace extensions
<commit_msg>Speculatively disable POSIX NativeMessagingTests all together to fix random unit_tests hangs.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_file.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/features/feature.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace {
FilePath GetTestDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
test_dir = test_dir.AppendASCII("native_messaging");
return test_dir;
}
} // namespace
namespace extensions {
class FakeLauncher : public NativeProcessLauncher {
public:
FakeLauncher(FilePath read_file, FilePath write_file) {
read_file_ = base::CreatePlatformFile(
read_file,
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
NULL, NULL);
write_file_ = base::CreatePlatformFile(
write_file,
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_WRITE,
NULL, NULL);
}
virtual bool LaunchNativeProcess(
const FilePath& path,
base::ProcessHandle* native_process_handle,
NativeMessageProcessHost::FileHandle* read_file,
NativeMessageProcessHost::FileHandle* write_file) const OVERRIDE {
*native_process_handle = base::kNullProcessHandle;
*read_file = read_file_;
*write_file = write_file_;
return true;
}
private:
base::PlatformFile read_file_;
base::PlatformFile write_file_;
};
class NativeMessagingTest : public ::testing::Test,
public NativeMessageProcessHost::Client,
public base::SupportsWeakPtr<NativeMessagingTest> {
public:
NativeMessagingTest() : current_channel_(chrome::VersionInfo::CHANNEL_DEV) {
}
virtual void SetUp() {
// Change the user data dir so native apps will be looked for in the test
// directory.
ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_));
ASSERT_TRUE(PathService::Override(chrome::DIR_USER_DATA, GetTestDir()));
ui_thread_.reset(new content::TestBrowserThread(BrowserThread::UI,
&message_loop_));
file_thread_.reset(new content::TestBrowserThread(BrowserThread::FILE,
&message_loop_));
}
virtual void TearDown() {
// Change the user data dir back for other tests.
ASSERT_TRUE(PathService::Override(chrome::DIR_USER_DATA, user_data_dir_));
BrowserThread::DeleteSoon(BrowserThread::FILE, FROM_HERE,
native_message_process_host_);
message_loop_.RunAllPending();
}
void PostMessageFromNativeProcess(int port_id, const std::string& message) {
last_posted_message_ = message;
}
void CloseChannel(int port_id, bool error) {
}
void AcquireProcess(NativeMessageProcessHost::ScopedHost process) {
native_message_process_host_ = process.release();
}
protected:
// Force the channel to be dev.
Feature::ScopedCurrentChannel current_channel_;
NativeMessageProcessHost* native_message_process_host_;
FilePath user_data_dir_;
MessageLoopForIO message_loop_;
scoped_ptr<content::TestBrowserThread> ui_thread_;
scoped_ptr<content::TestBrowserThread> file_thread_;
std::string last_posted_message_;
};
// Read a single message from a local file (single_message_response.msg).
TEST_F(NativeMessagingTest, DISABLED_SingleSendMessageRead) {
FilePath temp_file;
file_util::CreateTemporaryFile(&temp_file);
FakeLauncher launcher(GetTestDir().AppendASCII("single_message_response.msg"),
temp_file);
NativeMessageProcessHost::CreateWithLauncher(
AsWeakPtr(), "empty_app.py", "{}", 0,
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()),
launcher);
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_, "{\"text\": \"Hi There!.\"}");
file_util::Delete(temp_file, false /* non-recursive */);
}
// Tests sending a single message. The message should get written to
// |temp_file| and should match the contents of single_message_request.msg.
TEST_F(NativeMessagingTest, DISABLED_SingleSendMessageWrite) {
FilePath temp_file;
file_util::CreateTemporaryFile(&temp_file);
FakeLauncher launcher(GetTestDir().AppendASCII("single_message_response.msg"),
temp_file);
NativeMessageProcessHost::CreateWithLauncher(
AsWeakPtr(), "empty_app.py", "{\"text\": \"Hello.\"}", 0,
NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()),
launcher);
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
EXPECT_TRUE(file_util::ContentsEqual(
temp_file, GetTestDir().AppendASCII("single_message_request.msg")));
file_util::Delete(temp_file, false /* non-recursive */);
}
// Test send message with a real client. The client just echo's back the text
// it recieved.
TEST_F(NativeMessagingTest, DISABLED_EchoConnect) {
NativeMessageProcessHost::Create(
AsWeakPtr(), "echo.py", "{\"text\": \"Hello.\"}", 0,
NativeMessageProcessHost::TYPE_CONNECT, base::Bind(
&NativeMessagingTest::AcquireProcess, AsWeakPtr()));
message_loop_.RunAllPending();
ASSERT_TRUE(native_message_process_host_);
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_,
"{\"id\": 1, \"echo\": {\"text\": \"Hello.\"}}");
native_message_process_host_->Send("{\"foo\": \"bar\"}");
message_loop_.RunAllPending();
native_message_process_host_->ReadNowForTesting();
message_loop_.RunAllPending();
EXPECT_EQ(last_posted_message_, "{\"id\": 2, \"echo\": {\"foo\": \"bar\"}}");
}
} // namespace extensions
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Writer.h"
Writer::Writer()
{
Filing* file = new Filing();
file->Startup();
string path;
//setup converter
using convert_type = codecvt_utf8<wchar_t>;
wstring_convert<convert_type, wchar_t> converter;
path = converter.to_bytes(*file->LogDirectoryPath);
path.append("\\");
path.append(*this->GetTime());
path.pop_back();
path.pop_back();
path.append(".txt");
this->Log.open(path, fstream::out);
if (!Log)
{
throw new exception("Can't access file!");
}
else
{
string message = "Log has initialized successfully";
this->WriteLine(&message);
}
ToDelete->push_back(file);
}
Writer::~Writer()
{
this->Log.close();
}
void Writer::WriteLine(string *Str)
{
if (Str != NULL && Str->size() > 0)
{
cout << *Str;
cout << "\r\n";
cout.flush();
this->LogLine(Str);
}
else
{
string a = "Someone attempted to write a null or empty string to the console!";
this->WriteLine(&a);
}
}
void Writer::WriteLine(const char* Str)
{
string* Msg = new string(Str);
this->WriteLine(Msg);
delete Msg;
}
void Writer::putLine(const char * Str)
{
puts(Str);
this->Log << *this->GetTime();
this->Log << Str;
this->Log << "\r\n";
this->Log.flush();
}
void Writer::LogLine(string *Str)
{
this->Log << *this->GetTime();
this->Log << *Str;
this->Log << "\r\n";
this->Log.flush();
}
string* Writer::GetTime()
{
string* Formatted = new string("[");
time_t rawtime;
tm* timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = std::localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
Formatted->append(buffer);
Formatted->append("]: ");
return Formatted;
}<commit_msg>Increased tree time immensely.<commit_after>#include "stdafx.h"
#include "Writer.h"
Writer::Writer()
{
Filing* file = new Filing();
file->Startup();
string path;
//setup converter
using convert_type = codecvt_utf8<wchar_t>;
wstring_convert<convert_type, wchar_t> converter;
path = converter.to_bytes(*file->LogDirectoryPath);
path.append("\\");
path.append(*this->GetTime());
path.pop_back();
path.pop_back();
path.append(".txt");
this->Log.open(path, fstream::out);
if (!Log)
{
throw new exception("Can't access file!");
}
else
{
string message = "Log has initialized successfully";
this->WriteLine(&message);
}
ToDelete->push_back(file);
}
Writer::~Writer()
{
this->Log.close();
}
void Writer::WriteLine(string *Str)
{
if (Str != NULL && Str->size() > 0)
{
cout << *Str;
cout << "\r\n";
cout.flush();
this->LogLine(Str);
}
else
{
string a = "Someone attempted to write a null or empty string to the console!";
this->WriteLine(&a);
}
}
void Writer::WriteLine(const char* Str)
{
string* Msg = new string(Str);
this->WriteLine(Msg);
delete Msg;
}
void Writer::putLine(const char * Str)
{
this->Log << *this->GetTime();
this->Log << Str;
this->Log << "\r\n";
this->Log.flush();
}
void Writer::LogLine(string *Str)
{
this->Log << *this->GetTime();
this->Log << *Str;
this->Log << "\r\n";
this->Log.flush();
}
string* Writer::GetTime()
{
string* Formatted = new string("[");
time_t rawtime;
tm* timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = std::localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
Formatted->append(buffer);
Formatted->append("]: ");
return Formatted;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <cstdint>
#include <cassert>
#include <vector>
#include <array>
#include <random>
#include <memory>
#include <set>
// utility class
void VectorRandomInitialize(std::vector<float>& input)
{
std::cout << "Random Initializing Weights: " << input.size() << std::endl;
assert(input.size() > 0);
// initialize to random floats in range [0,1]
std::uniform_real_distribution<float> distribution(0.0f, 1.0f); //Values between 0 and 1
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
std::generate_n(input.begin(), input.size(), generator);
}
///////////////////////////////////////////////////
// Layer Implementations
// inputDimension - number of neurons in previous layer
// outputDimension - number of neurons in the current layer
//////////////////////////////////////////////////
// Base Layer that all layers should inherit
class BaseLayer
{
public:
BaseLayer(
int32_t inputDim,
int32_t outputDim)
: _inputDim(inputDim),
_outputDim(outputDim)
{}
virtual void initializeWeights() = 0;
virtual void forwardProp(std::vector<float>& input, std::vector<float>& output) = 0;
virtual void backProp() = 0;
int32_t InputDim() { return _inputDim; }
int32_t OutputDim() { return _outputDim; }
protected:
std::vector<float> _weights;
int32_t _inputDim;
int32_t _outputDim;
};
// For InputLayer, inputDim = outputDim
// and there are no weights shared.
class InputLayer : public BaseLayer
{
public:
InputLayer(int32_t inputDim)
: BaseLayer(inputDim, inputDim)
{}
void initializeWeights()
{
// Nothing to Do for the input layer.
}
// simply return the input as output.
void forwardProp(std::vector<float>& input, std::vector<float>& output)
{
std::cout << "forward prop from Input Layer" << std::endl;
output.resize(input.size());
// copy input to output, as the input layer does not apply any transformation.
std::copy(input.begin(), input.end(), output.begin());
}
void backProp()
{
}
};
class FullyConnectedHiddenLayer : public BaseLayer
{
public:
FullyConnectedHiddenLayer(
int32_t inputDim,
int32_t outputDim)
: BaseLayer(inputDim, outputDim)
{
}
protected:
void initializeWeights()
{
_weights.reserve(_inputDim * _outputDim);
_weights.assign(_inputDim * _outputDim, 0.0);
VectorRandomInitialize(_weights);
}
void forwardProp(std::vector<float>& input, std::vector<float>& output)
{
std::cout << "Forward prop from Fully Connected Layer" << std::endl;
// perform forward propagation
// initialize a vector to hold the sigma
std::vector<float> sigma(_outputDim, 0.0);
// this holds the activations / output
output.resize(_outputDim);
for (int i = 0; i < input.size(); ++i)
{
int32_t startWeightIndex = i * _outputDim;
int32_t endWeightIndex = startWeightIndex + _outputDim;
// for ith neuron, perform a dot product with all the weights that are coming from that neuron
for (int j = startWeightIndex; j < endWeightIndex; ++j)
{
assert(j - startWeightIndex >= 0 && j - startWeightIndex < _outputDim);
assert((j - startWeightIndex) < sigma.size());
assert(j < _weights.size());
sigma[j - startWeightIndex] += _weights[j] * input[i];
}
}
// apply the sigmoid function on the sigma to get the activations.
for (int i = 0; i < sigma.size(); ++i)
{
output[i] = 1 / 1 + exp(-sigma[i]);
double param, fractpart, intpart;
fractpart = modf (output[i] , &intpart);
if (fractpart == 0.0)
{
std::cout << "Fract Part is 0 : " << output[i] << std::endl;
}
assert(output[i] >= 0);
}
for (auto elem : sigma)
{
std::cout << elem << ":";
}
std::cout << " " << std::endl;
for (auto elem : output)
{
std::cout << elem << ":";
}
std::cout << " " << std::endl;
}
void backProp()
{
}
};
class FullyConnectedOutputLayer : public FullyConnectedHiddenLayer
{
public:
FullyConnectedOutputLayer(int32_t inputDim, int32_t outputDim)
: FullyConnectedHiddenLayer(inputDim, outputDim)
{
}
protected:
/*
void initializeWeights()
{
_weights.reserve(_inputDim * _outputDim);
_weights.assign(_inputDim * _outputDim, 0.0);
VectorRandomInitialize(_weights);
}
*/
/*
void forwardProp(std::vector<float>& input, std::vector<float>& output)
{
std::cout << "forward prop from Output Layer" << std::endl;
}
void backProp()
{
}
*/
};
typedef std::vector<std::shared_ptr<BaseLayer>> LayerSet;
////////////////////////////////////////
// Input Data and Data Source Related Stuff
////////////////////////////////////////
struct InputData
{
std::vector<float> _input;
std::vector<float> _target;
};
// source for the input data to neural network
// This is a generic class that exposes an interface to fetch input sample
// one by one. Concrete implementations can be backed by either a database, or a static dataset
class IDataFeed
{
public:
virtual bool getNext(InputData& input) = 0;
};
class StaticDataFeed : public IDataFeed
{
public:
StaticDataFeed(std::vector<InputData> dataset)
: _dataset(dataset),
_currentOffset(0)
{
std::cout << "dataset size: " << _dataset.size() << " " << _dataset[0]._input.size() << std::endl;
}
bool getNext(InputData& input)
{
if (_currentOffset < _dataset.size())
{
input = _dataset[_currentOffset++];
return true;
}
return false;
}
private:
std::vector<InputData> _dataset;
int32_t _currentOffset;
};
/////////////////////////////////////////////
// Trainer - This class does the actual training
////////////////////////////////////////////
class Trainer
{
public:
Trainer(
std::shared_ptr<LayerSet> layerSet,
std::shared_ptr<IDataFeed> dataFeed
) : _layers(layerSet),
_dataFeed(dataFeed)
{
validate();
initializeWeights();
}
void validate()
{
std::cout << "Validating Layer Set" << std::endl;
// ensure that there are atleast two layers.
assert(_layers->size() >= 2);
int32_t prevLayerSize = (*_layers)[0]->InputDim();
for (auto layer : *_layers)
{
assert(prevLayerSize == layer->InputDim());
prevLayerSize = layer->OutputDim();
}
}
void initializeWeights()
{
// this initializes weights to random,
// in future, we can possibly import the weights from a file / dump etc.
for (auto layer : *_layers)
{
layer->initializeWeights();
}
}
void train()
{
InputData input;
while(_dataFeed->getNext(input))
{
forwardProp(input);
}
}
void forwardProp(InputData& input)
{
std::vector<float> currentInput = input._input;
std::vector<float> output;
for (auto layer : *_layers)
{
layer->forwardProp(currentInput, output);
currentInput = output;
}
}
private:
std::shared_ptr<LayerSet> _layers;
std::shared_ptr<IDataFeed> _dataFeed;
};
// basic sanity tests
void tests()
{
// Test 1
}
int main()
{
// create layers
std::shared_ptr<LayerSet> layers(new LayerSet({
std::make_shared<InputLayer>(3),
std::make_shared<FullyConnectedHiddenLayer>(3, 20),
std::make_shared<FullyConnectedOutputLayer>(20, 2)
}));
// create a dummy data set
std::vector<InputData> staticData = {
{{0.5,0.5,0.5}, {0.4,0.4}},
{{0.4,0.6,0.9}, {0.3,0.7}}
};
std::cout << staticData.size() << " " << staticData[0]._input.size() << std::endl;
std::shared_ptr<IDataFeed> dataFeed(new StaticDataFeed(staticData));
auto trainer = std::make_shared<Trainer>(layers, dataFeed);
trainer->train();
return 0;
}
<commit_msg>add override keyword wherever necessary<commit_after>///////////////////////
// author:
// koby becker,
// beckerkoby@gmail.com,
// 2015
///////////////////////
#include <iostream>
#include <algorithm>
#include <cstdint>
#include <cassert>
#include <vector>
#include <array>
#include <random>
#include <memory>
#include <set>
#define DEBUG_PRINT
// utility class
void VectorRandomInitialize(std::vector<float>& input)
{
std::cout << "Random Initializing Weights: " << input.size() << std::endl;
assert(input.size() > 0);
// initialize to random floats in range [0,1]
std::uniform_real_distribution<float> distribution(0.0f, 1.0f); //Values between 0 and 1
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
std::generate_n(input.begin(), input.size(), generator);
}
///////////////////////////////////////////////////
// Layer Implementations
// inputDimension - number of neurons in previous layer
// outputDimension - number of neurons in the current layer
//
// In this implementation, the weights are owned by the layers.
// All the layers implement a common interface and provide implementation
// to the forward and backward propagation operations on the weights in those layers
//////////////////////////////////////////////////
// Base Layer that all layers should inherit
class BaseLayer
{
public:
BaseLayer(
int32_t inputDim,
int32_t outputDim)
: _inputDim(inputDim),
_outputDim(outputDim)
{}
virtual void initializeWeights() = 0;
virtual void forwardProp(std::vector<float>& input, std::vector<float>& output) = 0;
virtual void backProp() = 0;
int32_t InputDim() { return _inputDim; }
int32_t OutputDim() { return _outputDim; }
protected:
std::vector<float> _weights;
int32_t _inputDim;
int32_t _outputDim;
};
// For InputLayer, inputDim = outputDim
// and there are no weights shared.
class InputLayer : public BaseLayer
{
public:
InputLayer(int32_t inputDim)
: BaseLayer(inputDim, inputDim)
{}
void initializeWeights()
{
// Nothing to Do for the input layer.
}
// simply return the input as output.
void forwardProp(std::vector<float>& input, std::vector<float>& output)
{
std::cout << "forward prop from Input Layer" << std::endl;
output.resize(input.size());
// copy input to output, as the input layer does not apply any transformation.
std::copy(input.begin(), input.end(), output.begin());
}
void backProp()
{
}
};
// Implementation of a Fully Connected Layer
class FullyConnectedHiddenLayer : public BaseLayer
{
public:
FullyConnectedHiddenLayer(
int32_t inputDim,
int32_t outputDim)
: BaseLayer(inputDim, outputDim)
{
}
protected:
virtual void initializeWeights() override
{
_weights.reserve(_inputDim * _outputDim);
_weights.assign(_inputDim * _outputDim, 0.0);
VectorRandomInitialize(_weights);
}
virtual void forwardProp(std::vector<float>& input, std::vector<float>& output) override
{
std::cout << "Forward prop from Fully Connected Layer" << std::endl;
// perform forward propagation
// initialize a vector to hold the sigma
std::vector<float> sigma(_outputDim, 0.0);
// this holds the activations / output
output.resize(_outputDim);
for (int i = 0; i < input.size(); ++i)
{
int32_t startWeightIndex = i * _outputDim;
int32_t endWeightIndex = startWeightIndex + _outputDim;
// for ith neuron, perform a dot product with all the weights that are coming from that neuron
for (int j = startWeightIndex; j < endWeightIndex; ++j)
{
assert(j - startWeightIndex >= 0 && j - startWeightIndex < _outputDim);
assert((j - startWeightIndex) < sigma.size());
assert(j < _weights.size());
sigma[j - startWeightIndex] += _weights[j] * input[i];
}
}
// apply the sigmoid function on the sigma to get the activations.
for (int i = 0; i < sigma.size(); ++i)
{
output[i] = 1 / 1 + exp(-sigma[i]);
#ifdef DEBUG_PRINT
double param, fractpart, intpart;
fractpart = modf(output[i] , &intpart);
if (fractpart == 0.0)
{
std::cout << "Fract Part is 0 : " << output[i] << std::endl;
}
#endif
assert(output[i] >= 0);
}
#ifdef DEBUG_PRINT
for (auto elem : sigma)
{
std::cout << elem << ":";
}
std::cout << " " << std::endl;
for (auto elem : output)
{
std::cout << elem << ":";
}
std::cout << " " << std::endl;
#endif
}
virtual void backProp() override
{
}
};
class FullyConnectedOutputLayer : public FullyConnectedHiddenLayer
{
public:
FullyConnectedOutputLayer(int32_t inputDim, int32_t outputDim)
: FullyConnectedHiddenLayer(inputDim, outputDim)
{
}
protected:
void backProp() override
{
// First Calculate the Cost Function
}
};
typedef std::vector<std::shared_ptr<BaseLayer>> LayerSet;
////////////////////////////////////////
// Input Data and Data Source Related Stuff
////////////////////////////////////////
struct InputData
{
std::vector<float> _input;
std::vector<float> _target;
};
// source for the input data to neural network
// This is a generic class that exposes an interface to fetch input sample
// one by one. Concrete implementations can be backed by either a database, or a static dataset
class IDataFeed
{
public:
virtual bool getNext(InputData& input) = 0;
};
class StaticDataFeed : public IDataFeed
{
public:
StaticDataFeed(std::vector<InputData> dataset)
: _dataset(dataset),
_currentOffset(0)
{
std::cout << "dataset size: " << _dataset.size() << " " << _dataset[0]._input.size() << std::endl;
}
bool getNext(InputData& input) override
{
if (_currentOffset < _dataset.size())
{
input = _dataset[_currentOffset++];
return true;
}
return false;
}
private:
std::vector<InputData> _dataset;
int32_t _currentOffset;
};
/////////////////////////////////////////////
// Trainer - This class does the actual training
////////////////////////////////////////////
class Trainer
{
public:
Trainer(
std::shared_ptr<LayerSet> layerSet,
std::shared_ptr<IDataFeed> dataFeed
) : _layers(layerSet),
_dataFeed(dataFeed)
{
validate();
initializeWeights();
}
void validate()
{
std::cout << "Validating Layer Set" << std::endl;
// ensure that there are atleast two layers.
assert(_layers->size() >= 2);
int32_t prevLayerSize = (*_layers)[0]->InputDim();
for (auto layer : *_layers)
{
assert(prevLayerSize == layer->InputDim());
prevLayerSize = layer->OutputDim();
}
}
void initializeWeights()
{
// this initializes weights to random,
// in future, we can possibly import the weights from a file / dump etc.
for (auto layer : *_layers)
{
layer->initializeWeights();
}
}
void train()
{
InputData input;
while(_dataFeed->getNext(input))
{
forwardProp(input);
}
}
void forwardProp(InputData& input)
{
std::vector<float> currentInput = input._input;
std::vector<float> output;
for (auto layer : *_layers)
{
layer->forwardProp(currentInput, output);
currentInput = output;
}
}
private:
std::shared_ptr<LayerSet> _layers;
std::shared_ptr<IDataFeed> _dataFeed;
};
// basic sanity tests
void tests()
{
// Test 1
}
int main()
{
// create layers
std::shared_ptr<LayerSet> layers(new LayerSet({
std::make_shared<InputLayer>(3),
std::make_shared<FullyConnectedHiddenLayer>(3, 20),
std::make_shared<FullyConnectedOutputLayer>(20, 2)
}));
// create a dummy data set
std::vector<InputData> staticData = {
{{0.5,0.5,0.5}, {0.4,0.4}},
{{0.4,0.6,0.9}, {0.3,0.7}}
};
std::cout << staticData.size() << " " << staticData[0]._input.size() << std::endl;
std::shared_ptr<IDataFeed> dataFeed(new StaticDataFeed(staticData));
auto trainer = std::make_shared<Trainer>(layers, dataFeed);
trainer->train();
return 0;
}
<|endoftext|> |
<commit_before>/* pocl-ptx-gen.c - PTX code generation functions
Copyright (c) 2016 James Price / University of Bristol
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 "config.h"
#include "common.h"
#include "pocl.h"
#include "pocl-ptx-gen.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Utils/Cloning.h"
// TODO: Should these be proper passes?
void pocl_add_kernel_annotations(llvm::Module *module);
void pocl_gen_local_mem_args(llvm::Module *module);
void pocl_insert_ptx_intrinsics(llvm::Module *module);
int pocl_ptx_gen(const char *bc_filename,
const char *ptx_filename,
const char *gpu_arch)
{
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
llvm::MemoryBuffer::getFile(bc_filename);
if (!buffer)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to open bitcode file\n");
return 1;
}
// Load bitcode
llvm::ErrorOr<std::unique_ptr<llvm::Module>> module =
parseBitcodeFile(buffer->get()->getMemBufferRef(),
llvm::getGlobalContext());
if (!module)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to load bitcode\n");
return 1;
}
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmPrinters();
// Apply transforms to prepare for lowering to PTX
pocl_gen_local_mem_args(module->get());
pocl_insert_ptx_intrinsics(module->get());
pocl_add_kernel_annotations(module->get());
//(*module)->dump();
// TODO: support 32-bit?
llvm::StringRef triple = "nvptx64-nvidia-cuda";
// Get NVPTX target
std::string error;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(
triple, error);
if (!target)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to get target\n");
POCL_MSG_ERR("%s\n", error.c_str());
return 1;
}
// TODO: set options
llvm::TargetOptions options;
// TODO: CPU and features?
std::unique_ptr<llvm::TargetMachine> machine(
target->createTargetMachine(triple, gpu_arch, "", options));
llvm::legacy::PassManager passes;
// Add pass to emit PTX
std::error_code ec;
llvm::raw_fd_ostream *ptx =
new llvm::raw_fd_ostream(ptx_filename, ec, llvm::sys::fs::F_Text);
if (machine->addPassesToEmitFile(passes, *ptx,
llvm::TargetMachine::CGFT_AssemblyFile))
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to add passes\n");
return 1;
}
// Run passes
passes.run(**module);
return 0;
}
void pocl_add_kernel_annotations(llvm::Module *module)
{
llvm::LLVMContext& context = llvm::getGlobalContext();
// Remove nvvm.annotations metadata since it is sometimes corrupt
llvm::NamedMDNode *nvvm_annotations =
module->getNamedMetadata("nvvm.annotations");
if (nvvm_annotations)
nvvm_annotations->eraseFromParent();
llvm::NamedMDNode *md_kernels = module->getNamedMetadata("opencl.kernels");
if (!md_kernels)
return;
// Add nvvm.annotations metadata to mark kernel entry points
nvvm_annotations = module->getOrInsertNamedMetadata("nvvm.annotations");
for (auto K = md_kernels->op_begin(); K != md_kernels->op_end(); K++)
{
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>((*K)->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = llvm::dyn_cast<llvm::Function>(cam->getValue());
llvm::Constant *one =
llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(context), 1);
llvm::Metadata *md_f = llvm::ValueAsMetadata::get(function);
llvm::Metadata *md_n = llvm::MDString::get(context, "kernel");
llvm::Metadata *md_1 = llvm::ConstantAsMetadata::get(one);
std::vector<llvm::Metadata*> v_md = {md_f, md_n, md_1};
llvm::MDNode *node = llvm::MDNode::get(context, v_md);
nvvm_annotations->addOperand(node);
}
}
void pocl_gen_local_mem_args(llvm::Module *module)
{
// TODO: Deal with non-kernel functions that take local memory arguments
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::NamedMDNode *md_kernels = module->getNamedMetadata("opencl.kernels");
if (!md_kernels)
return;
// Create global variable for local memory allocations
llvm::Type *byte_array_type =
llvm::ArrayType::get(llvm::Type::getInt8Ty(context), 0);
llvm::GlobalVariable *shared_ptr =
new llvm::GlobalVariable(*module, byte_array_type,
false, llvm::GlobalValue::ExternalLinkage,
NULL, "_shared_memory_region_", NULL,
llvm::GlobalValue::NotThreadLocal,
3, false);
// Loop over kernels
for (auto K = md_kernels->op_begin(); K != md_kernels->op_end(); K++)
{
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>((*K)->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = llvm::dyn_cast<llvm::Function>(cam->getValue());
// Argument info for creating new function
std::vector<llvm::Argument*> arguments;
std::vector<llvm::Type*> argument_types;
// Loop over arguments
bool has_local_args = false;
for (auto arg = function->arg_begin(); arg != function->arg_end(); arg++)
{
// Check for local memory pointer
llvm::Type *arg_type = arg->getType();
if (arg_type->getPointerAddressSpace() == POCL_ADDRESS_SPACE_LOCAL)
{
has_local_args = true;
// Create new argument for offset into shared memory allocation
llvm::Type *i32ty = llvm::Type::getInt32Ty(context);
llvm::Argument *offset =
new llvm::Argument(i32ty, arg->getName() + "_offset");
arguments.push_back(offset);
argument_types.push_back(i32ty);
// Cast shared memory pointer to generic address space
llvm::AddrSpaceCastInst *generic_ptr =
new llvm::AddrSpaceCastInst(shared_ptr,
byte_array_type->getPointerTo(0));
generic_ptr->insertBefore(&*function->begin()->begin());
// Insert GEP to add offset
llvm::Value *zero = llvm::ConstantInt::getSigned(i32ty, 0);
llvm::GetElementPtrInst *gep =
llvm::GetElementPtrInst::Create(byte_array_type, generic_ptr,
{zero, offset});
gep->insertAfter(generic_ptr);
// Cast pointer to correct type
llvm::Type *final_type =
arg_type->getPointerElementType()->getPointerTo(0);
llvm::BitCastInst *cast = new llvm::BitCastInst(gep, final_type);
cast->insertAfter(gep);
cast->takeName(&*arg);
arg->replaceAllUsesWith(cast);
// Update users of this new cast to use generic address space
auto cast_users = cast->users();
std::vector<llvm::Value*> users(cast_users.begin(), cast_users.end());
for (auto U = users.begin(); U != users.end(); U++)
{
// TODO: Do we need to do this for anything other than GEPs?
llvm::GetElementPtrInst *gep_user =
llvm::dyn_cast<llvm::GetElementPtrInst>(*U);
if (!gep_user)
continue;
// Create and insert new GEP instruction
auto ops = gep_user->operands();
std::vector<llvm::Value*> indices(ops.begin()+1, ops.end());
llvm::GetElementPtrInst *new_gep_user =
llvm::GetElementPtrInst::Create(NULL, cast, indices);
new_gep_user->insertAfter(gep_user);
gep_user->replaceAllUsesWith(new_gep_user);
gep_user->eraseFromParent();
}
}
else
{
// No change to other arguments
arguments.push_back(&*arg);
argument_types.push_back(arg->getType());
}
}
if (!has_local_args)
continue;
// Create new function with offsets instead of local memory pointers
llvm::FunctionType *new_func_type =
llvm::FunctionType::get(function->getReturnType(), argument_types, false);
llvm::Function *new_func =
llvm::Function::Create(new_func_type, function->getLinkage(),
function->getName(), module);
new_func->takeName(function);
// Take function body from old function
new_func->getBasicBlockList().splice(new_func->begin(),
function->getBasicBlockList());
// TODO: Copy attributes from old function
// Update function body with new arguments
std::vector<llvm::Argument*>::iterator old_arg;
llvm::Function::arg_iterator new_arg;
for (old_arg = arguments.begin(), new_arg = new_func->arg_begin();
new_arg != new_func->arg_end();
new_arg++, old_arg++)
{
new_arg->takeName(*old_arg);
(*old_arg)->replaceAllUsesWith(&*new_arg);
}
// Remove old function
function->replaceAllUsesWith(new_func);
function->eraseFromParent();
}
}
void pocl_insert_ptx_intrinsics(llvm::Module *module)
{
struct ptx_intrinsic_map_entry
{
const char *varname;
const char *intrinsic;
};
struct ptx_intrinsic_map_entry intrinsic_map[] =
{
{"_local_id_x", "llvm.nvvm.read.ptx.sreg.tid.x"},
{"_local_id_y", "llvm.nvvm.read.ptx.sreg.tid.y"},
{"_local_id_z", "llvm.nvvm.read.ptx.sreg.tid.z"},
{"_local_size_x", "llvm.nvvm.read.ptx.sreg.ntid.x"},
{"_local_size_y", "llvm.nvvm.read.ptx.sreg.ntid.y"},
{"_local_size_z", "llvm.nvvm.read.ptx.sreg.ntid.z"},
{"_group_id_x", "llvm.nvvm.read.ptx.sreg.ctaid.x"},
{"_group_id_y", "llvm.nvvm.read.ptx.sreg.ctaid.y"},
{"_group_id_z", "llvm.nvvm.read.ptx.sreg.ctaid.z"},
{"_num_groups_x", "llvm.nvvm.read.ptx.sreg.nctaid.x"},
{"_num_groups_y", "llvm.nvvm.read.ptx.sreg.nctaid.y"},
{"_num_groups_z", "llvm.nvvm.read.ptx.sreg.nctaid.z"},
};
size_t num_intrinsics = sizeof(intrinsic_map)/sizeof(ptx_intrinsic_map_entry);
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::Type *int32Ty = llvm::Type::getInt32Ty(context);
llvm::FunctionType *intrinsic_type = llvm::FunctionType::get(int32Ty, false);
for (unsigned i = 0; i < num_intrinsics; i++)
{
ptx_intrinsic_map_entry entry = intrinsic_map[i];
llvm::GlobalVariable *var = module->getGlobalVariable(entry.varname);
if (!var)
continue;
for (auto U = var->user_begin(); U != var->user_end(); U++)
{
// Look for loads from the global variable
llvm::LoadInst *load = llvm::dyn_cast<llvm::LoadInst>(*U);
if (load)
{
// Replace load with intrinsic
llvm::Constant *func =
module->getOrInsertFunction(entry.intrinsic, intrinsic_type);
llvm::CallInst *call = llvm::CallInst::Create(func, {}, load);
load->replaceAllUsesWith(call);
load->eraseFromParent();
}
}
var->eraseFromParent();
}
}
<commit_msg>[CUDA] Fix intrinsic replacement<commit_after>/* pocl-ptx-gen.c - PTX code generation functions
Copyright (c) 2016 James Price / University of Bristol
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 "config.h"
#include "common.h"
#include "pocl.h"
#include "pocl-ptx-gen.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Utils/Cloning.h"
// TODO: Should these be proper passes?
void pocl_add_kernel_annotations(llvm::Module *module);
void pocl_gen_local_mem_args(llvm::Module *module);
void pocl_insert_ptx_intrinsics(llvm::Module *module);
int pocl_ptx_gen(const char *bc_filename,
const char *ptx_filename,
const char *gpu_arch)
{
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
llvm::MemoryBuffer::getFile(bc_filename);
if (!buffer)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to open bitcode file\n");
return 1;
}
// Load bitcode
llvm::ErrorOr<std::unique_ptr<llvm::Module>> module =
parseBitcodeFile(buffer->get()->getMemBufferRef(),
llvm::getGlobalContext());
if (!module)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to load bitcode\n");
return 1;
}
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmPrinters();
// Apply transforms to prepare for lowering to PTX
pocl_gen_local_mem_args(module->get());
pocl_insert_ptx_intrinsics(module->get());
pocl_add_kernel_annotations(module->get());
//(*module)->dump();
// TODO: support 32-bit?
llvm::StringRef triple = "nvptx64-nvidia-cuda";
// Get NVPTX target
std::string error;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(
triple, error);
if (!target)
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to get target\n");
POCL_MSG_ERR("%s\n", error.c_str());
return 1;
}
// TODO: set options
llvm::TargetOptions options;
// TODO: CPU and features?
std::unique_ptr<llvm::TargetMachine> machine(
target->createTargetMachine(triple, gpu_arch, "", options));
llvm::legacy::PassManager passes;
// Add pass to emit PTX
std::error_code ec;
llvm::raw_fd_ostream *ptx =
new llvm::raw_fd_ostream(ptx_filename, ec, llvm::sys::fs::F_Text);
if (machine->addPassesToEmitFile(passes, *ptx,
llvm::TargetMachine::CGFT_AssemblyFile))
{
POCL_MSG_ERR("[CUDA] ptx-gen: failed to add passes\n");
return 1;
}
// Run passes
passes.run(**module);
return 0;
}
void pocl_add_kernel_annotations(llvm::Module *module)
{
llvm::LLVMContext& context = llvm::getGlobalContext();
// Remove nvvm.annotations metadata since it is sometimes corrupt
llvm::NamedMDNode *nvvm_annotations =
module->getNamedMetadata("nvvm.annotations");
if (nvvm_annotations)
nvvm_annotations->eraseFromParent();
llvm::NamedMDNode *md_kernels = module->getNamedMetadata("opencl.kernels");
if (!md_kernels)
return;
// Add nvvm.annotations metadata to mark kernel entry points
nvvm_annotations = module->getOrInsertNamedMetadata("nvvm.annotations");
for (auto K = md_kernels->op_begin(); K != md_kernels->op_end(); K++)
{
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>((*K)->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = llvm::dyn_cast<llvm::Function>(cam->getValue());
llvm::Constant *one =
llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(context), 1);
llvm::Metadata *md_f = llvm::ValueAsMetadata::get(function);
llvm::Metadata *md_n = llvm::MDString::get(context, "kernel");
llvm::Metadata *md_1 = llvm::ConstantAsMetadata::get(one);
std::vector<llvm::Metadata*> v_md = {md_f, md_n, md_1};
llvm::MDNode *node = llvm::MDNode::get(context, v_md);
nvvm_annotations->addOperand(node);
}
}
void pocl_gen_local_mem_args(llvm::Module *module)
{
// TODO: Deal with non-kernel functions that take local memory arguments
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::NamedMDNode *md_kernels = module->getNamedMetadata("opencl.kernels");
if (!md_kernels)
return;
// Create global variable for local memory allocations
llvm::Type *byte_array_type =
llvm::ArrayType::get(llvm::Type::getInt8Ty(context), 0);
llvm::GlobalVariable *shared_ptr =
new llvm::GlobalVariable(*module, byte_array_type,
false, llvm::GlobalValue::ExternalLinkage,
NULL, "_shared_memory_region_", NULL,
llvm::GlobalValue::NotThreadLocal,
3, false);
// Loop over kernels
for (auto K = md_kernels->op_begin(); K != md_kernels->op_end(); K++)
{
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>((*K)->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = llvm::dyn_cast<llvm::Function>(cam->getValue());
// Argument info for creating new function
std::vector<llvm::Argument*> arguments;
std::vector<llvm::Type*> argument_types;
// Loop over arguments
bool has_local_args = false;
for (auto arg = function->arg_begin(); arg != function->arg_end(); arg++)
{
// Check for local memory pointer
llvm::Type *arg_type = arg->getType();
if (arg_type->getPointerAddressSpace() == POCL_ADDRESS_SPACE_LOCAL)
{
has_local_args = true;
// Create new argument for offset into shared memory allocation
llvm::Type *i32ty = llvm::Type::getInt32Ty(context);
llvm::Argument *offset =
new llvm::Argument(i32ty, arg->getName() + "_offset");
arguments.push_back(offset);
argument_types.push_back(i32ty);
// Cast shared memory pointer to generic address space
llvm::AddrSpaceCastInst *generic_ptr =
new llvm::AddrSpaceCastInst(shared_ptr,
byte_array_type->getPointerTo(0));
generic_ptr->insertBefore(&*function->begin()->begin());
// Insert GEP to add offset
llvm::Value *zero = llvm::ConstantInt::getSigned(i32ty, 0);
llvm::GetElementPtrInst *gep =
llvm::GetElementPtrInst::Create(byte_array_type, generic_ptr,
{zero, offset});
gep->insertAfter(generic_ptr);
// Cast pointer to correct type
llvm::Type *final_type =
arg_type->getPointerElementType()->getPointerTo(0);
llvm::BitCastInst *cast = new llvm::BitCastInst(gep, final_type);
cast->insertAfter(gep);
cast->takeName(&*arg);
arg->replaceAllUsesWith(cast);
// Update users of this new cast to use generic address space
auto cast_users = cast->users();
std::vector<llvm::Value*> users(cast_users.begin(), cast_users.end());
for (auto U = users.begin(); U != users.end(); U++)
{
// TODO: Do we need to do this for anything other than GEPs?
llvm::GetElementPtrInst *gep_user =
llvm::dyn_cast<llvm::GetElementPtrInst>(*U);
if (!gep_user)
continue;
// Create and insert new GEP instruction
auto ops = gep_user->operands();
std::vector<llvm::Value*> indices(ops.begin()+1, ops.end());
llvm::GetElementPtrInst *new_gep_user =
llvm::GetElementPtrInst::Create(NULL, cast, indices);
new_gep_user->insertAfter(gep_user);
gep_user->replaceAllUsesWith(new_gep_user);
gep_user->eraseFromParent();
}
}
else
{
// No change to other arguments
arguments.push_back(&*arg);
argument_types.push_back(arg->getType());
}
}
if (!has_local_args)
continue;
// Create new function with offsets instead of local memory pointers
llvm::FunctionType *new_func_type =
llvm::FunctionType::get(function->getReturnType(), argument_types, false);
llvm::Function *new_func =
llvm::Function::Create(new_func_type, function->getLinkage(),
function->getName(), module);
new_func->takeName(function);
// Take function body from old function
new_func->getBasicBlockList().splice(new_func->begin(),
function->getBasicBlockList());
// TODO: Copy attributes from old function
// Update function body with new arguments
std::vector<llvm::Argument*>::iterator old_arg;
llvm::Function::arg_iterator new_arg;
for (old_arg = arguments.begin(), new_arg = new_func->arg_begin();
new_arg != new_func->arg_end();
new_arg++, old_arg++)
{
new_arg->takeName(*old_arg);
(*old_arg)->replaceAllUsesWith(&*new_arg);
}
// Remove old function
function->replaceAllUsesWith(new_func);
function->eraseFromParent();
}
}
void pocl_insert_ptx_intrinsics(llvm::Module *module)
{
struct ptx_intrinsic_map_entry
{
const char *varname;
const char *intrinsic;
};
struct ptx_intrinsic_map_entry intrinsic_map[] =
{
{"_local_id_x", "llvm.nvvm.read.ptx.sreg.tid.x"},
{"_local_id_y", "llvm.nvvm.read.ptx.sreg.tid.y"},
{"_local_id_z", "llvm.nvvm.read.ptx.sreg.tid.z"},
{"_local_size_x", "llvm.nvvm.read.ptx.sreg.ntid.x"},
{"_local_size_y", "llvm.nvvm.read.ptx.sreg.ntid.y"},
{"_local_size_z", "llvm.nvvm.read.ptx.sreg.ntid.z"},
{"_group_id_x", "llvm.nvvm.read.ptx.sreg.ctaid.x"},
{"_group_id_y", "llvm.nvvm.read.ptx.sreg.ctaid.y"},
{"_group_id_z", "llvm.nvvm.read.ptx.sreg.ctaid.z"},
{"_num_groups_x", "llvm.nvvm.read.ptx.sreg.nctaid.x"},
{"_num_groups_y", "llvm.nvvm.read.ptx.sreg.nctaid.y"},
{"_num_groups_z", "llvm.nvvm.read.ptx.sreg.nctaid.z"},
};
size_t num_intrinsics = sizeof(intrinsic_map)/sizeof(ptx_intrinsic_map_entry);
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::Type *int32Ty = llvm::Type::getInt32Ty(context);
llvm::FunctionType *intrinsic_type = llvm::FunctionType::get(int32Ty, false);
for (unsigned i = 0; i < num_intrinsics; i++)
{
ptx_intrinsic_map_entry entry = intrinsic_map[i];
llvm::GlobalVariable *var = module->getGlobalVariable(entry.varname);
if (!var)
continue;
auto var_users = var->users();
std::vector<llvm::Value*> users(var_users.begin(), var_users.end());
for (auto U = users.begin(); U != users.end(); U++)
{
// Look for loads from the global variable
llvm::LoadInst *load = llvm::dyn_cast<llvm::LoadInst>(*U);
if (load)
{
// Replace load with intrinsic
llvm::Constant *func =
module->getOrInsertFunction(entry.intrinsic, intrinsic_type);
llvm::CallInst *call = llvm::CallInst::Create(func, {}, load);
load->replaceAllUsesWith(call);
load->eraseFromParent();
}
}
var->eraseFromParent();
}
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef RAZ_FLOATUTILS_HPP
#define RAZ_FLOATUTILS_HPP
#include <algorithm>
#include <cmath>
#include <limits>
#include <type_traits>
namespace Raz {
namespace FloatUtils {
// Near-equality floating point check
template <typename T>
inline constexpr bool areNearlyEqual(T val1, T val2) {
static_assert(std::is_floating_point<T>::value, "Error: Values' type must be floating point.");
// Using absolute & relative tolerances for floating points types: http://www.realtimecollisiondetection.net/pubs/Tolerances/
// Could be a better idea to use ULPs checking. May be slower though?
const T absDiff = std::abs(val1 - val2);
return (absDiff <= std::numeric_limits<T>::epsilon() * std::max({ static_cast<T>(1), std::abs(val1), std::abs(val2) }));
}
} // namespace FloatUtils
} // namespace Raz
#endif // RAZ_FLOATUTILS_HPP
<commit_msg>[Utils/FloatUtils] Added documentation for FloatUtils<commit_after>#pragma once
#ifndef RAZ_FLOATUTILS_HPP
#define RAZ_FLOATUTILS_HPP
#include <algorithm>
#include <cmath>
#include <limits>
#include <type_traits>
namespace Raz {
namespace FloatUtils {
/// Checks if two given floating point values are nearly equal to each other.
/// \tparam T Type of both values to check; it must be a floating point type.
/// \param val1 First value to compare.
/// \param val2 Second value to compare.
/// \return True if values are nearly equal, false otherwise.
template <typename T>
inline constexpr bool areNearlyEqual(T val1, T val2) {
static_assert(std::is_floating_point<T>::value, "Error: Values' type must be floating point.");
// Using absolute & relative tolerances for floating points types: http://www.realtimecollisiondetection.net/pubs/Tolerances/
// Could be a better idea to use ULPs checking. May be slower though?
const T absDiff = std::abs(val1 - val2);
return (absDiff <= std::numeric_limits<T>::epsilon() * std::max({ static_cast<T>(1), std::abs(val1), std::abs(val2) }));
}
} // namespace FloatUtils
} // namespace Raz
#endif // RAZ_FLOATUTILS_HPP
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
////////////////////////////////////////////////////////////////////////////////
#include "PhysicsFS.hpp"
#include "LuaState.hpp"
#include "App.hpp"
#include "State.hpp"
#include <cmath>
////////////////////////////////////////////////////////////////////////////////
class PauseState : public State
{
public:
PauseState() {}
protected:
void onUpdate(sf::Time delta)
{
}
bool onEvent(const sf::Event &event)
{
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Return)
{
throw App::Exit;
}
else if (event.key.code == sf::Keyboard::Escape)
{
exit();
}
}
return false;
}
void draw(sf::RenderTarget &target, sf::RenderStates states) const
{
sf::RectangleShape rect(sf::Vector2f(target.getSize()));
rect.setFillColor(sf::Color(0,0,0,128));
target.draw(rect, states);
}
bool isOpaque() const { return false; }
};
////////////////////////////////////////////////////////////////////////////////
class MyState : public State
{
public:
MyState()
{
static const unsigned int numSides[10] = {
90, 3, 4, 5, 6, 7, 8, 10, 12, 20
};
m_shapes.resize(10);
for (unsigned int i = 0; i < 10; i++)
{
int r = ((i+9)/5)%2, c = (i+9)%5;
initShape(m_shapes[i], sf::Vector2f(80+150*c, 270+150*r), 50, numSides[i]);
}
}
protected:
void initShape(sf::ConvexShape &shape, const sf::Vector2f &position, float radius, unsigned int sides = 0)
{
if (sides < 3) sides = 3;
static const float PI = 3.14159265359f;
float angle = PI / float(sides);
float step = angle * 2.f;
shape.setPointCount(sides);
for (unsigned int i = 0; i < sides; i++)
{
shape.setPoint(i, sf::Vector2f(radius*std::cos(angle), radius*std::sin(angle)));
angle += step;
}
shape.setOutlineThickness(5);
shape.setOutlineColor(sf::Color::Black);
shape.setFillColor(sf::Color(160,160,160));
shape.setPosition(position);
}
void onUpdate(sf::Time delta)
{
for (sf::Shape &shape : m_shapes)
{
shape.rotate(90.f * delta.asSeconds());
}
}
bool onEvent(const sf::Event &event)
{
switch (event.type)
{
case sf::Event::KeyPressed:
{
switch (event.key.code)
{
case sf::Keyboard::Num0:
case sf::Keyboard::Num1:
case sf::Keyboard::Num2:
case sf::Keyboard::Num3:
case sf::Keyboard::Num4:
case sf::Keyboard::Num5:
case sf::Keyboard::Num6:
case sf::Keyboard::Num7:
case sf::Keyboard::Num8:
case sf::Keyboard::Num9:
{
m_shapes[event.key.code - sf::Keyboard::Num0].
setFillColor(sf::Color::Red);
return true;
}
default: break;
}
break;
}
case sf::Event::KeyReleased:
{
switch (event.key.code)
{
case sf::Keyboard::Num0:
case sf::Keyboard::Num1:
case sf::Keyboard::Num2:
case sf::Keyboard::Num3:
case sf::Keyboard::Num4:
case sf::Keyboard::Num5:
case sf::Keyboard::Num6:
case sf::Keyboard::Num7:
case sf::Keyboard::Num8:
case sf::Keyboard::Num9:
{
m_shapes[event.key.code - sf::Keyboard::Num0].
setFillColor(sf::Color::Green);
return true;
}
default: break;
}
break;
}
default: break;
}
return false;
}
void draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.clear(sf::Color(0x6688aa));
for (const sf::Shape &shape : m_shapes)
{
target.draw(shape, states);
}
}
private:
std::vector < sf::ConvexShape > m_shapes;
};
class MyApp : public App
{
public:
MyApp()
{
setTargetFPS(120.f);
setWindowStyle(sf::Style::Titlebar | sf::Style::Close);
}
protected:
void onStart()
{
createWindow();
pushState(m_myState);
}
bool onEvent(const sf::Event &event)
{
switch (event.type)
{
case sf::Event::KeyPressed:
{
if (event.key.code == sf::Keyboard::Escape)
{
if (getState() != &m_pauseState)
{
pushState(m_pauseState);
return true;
}
}
break;
}
default: break;
}
return false;
}
private:
PauseState m_pauseState;
MyState m_myState;
};
////////////////////////////////////////////////////////////////////////////////
extern "C"
int main (int argc, char **argv)
{
PhysicsFS physfs(argv[0]);
try
{
LuaState lua;
try
{
lua.doFile("config.lua");
}
catch (LuaState::Error &exc)
{
sf::err() << "Config script error: " << exc.what() << "\n";
}
lua.loadSafeLibs();
try
{
lua.doFile("init.lua");
}
catch (LuaState::Error &exc)
{
sf::err() << "Init script error: " << exc.what() << "\n";
throw;
}
MyApp app;
app.run();
}
catch (std::exception &exc)
{
sf::err() << "Unhandled exception: " << exc.what() << "\n";
}
return(0);
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Rework error handling in main<commit_after>////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
////////////////////////////////////////////////////////////////////////////////
#include "PhysicsFS.hpp"
#include "LuaState.hpp"
#include "App.hpp"
#include "State.hpp"
#include <cmath>
////////////////////////////////////////////////////////////////////////////////
class PauseState : public State
{
public:
PauseState() {}
protected:
void onUpdate(sf::Time delta)
{
}
bool onEvent(const sf::Event &event)
{
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Return)
{
throw App::Exit;
}
else if (event.key.code == sf::Keyboard::Escape)
{
exit();
}
}
return false;
}
void draw(sf::RenderTarget &target, sf::RenderStates states) const
{
sf::RectangleShape rect(sf::Vector2f(target.getSize()));
rect.setFillColor(sf::Color(0,0,0,128));
target.draw(rect, states);
}
bool isOpaque() const { return false; }
};
////////////////////////////////////////////////////////////////////////////////
class MyState : public State
{
public:
MyState()
{
static const unsigned int numSides[10] = {
90, 3, 4, 5, 6, 7, 8, 10, 12, 20
};
m_shapes.resize(10);
for (unsigned int i = 0; i < 10; i++)
{
int r = ((i+9)/5)%2, c = (i+9)%5;
initShape(m_shapes[i], sf::Vector2f(80+150*c, 270+150*r), 50, numSides[i]);
}
}
protected:
void initShape(sf::ConvexShape &shape, const sf::Vector2f &position, float radius, unsigned int sides = 0)
{
if (sides < 3) sides = 3;
static const float PI = 3.14159265359f;
float angle = PI / float(sides);
float step = angle * 2.f;
shape.setPointCount(sides);
for (unsigned int i = 0; i < sides; i++)
{
shape.setPoint(i, sf::Vector2f(radius*std::cos(angle), radius*std::sin(angle)));
angle += step;
}
shape.setOutlineThickness(5);
shape.setOutlineColor(sf::Color::Black);
shape.setFillColor(sf::Color(160,160,160));
shape.setPosition(position);
}
void onUpdate(sf::Time delta)
{
for (sf::Shape &shape : m_shapes)
{
shape.rotate(90.f * delta.asSeconds());
}
}
bool onEvent(const sf::Event &event)
{
switch (event.type)
{
case sf::Event::KeyPressed:
{
switch (event.key.code)
{
case sf::Keyboard::Num0:
case sf::Keyboard::Num1:
case sf::Keyboard::Num2:
case sf::Keyboard::Num3:
case sf::Keyboard::Num4:
case sf::Keyboard::Num5:
case sf::Keyboard::Num6:
case sf::Keyboard::Num7:
case sf::Keyboard::Num8:
case sf::Keyboard::Num9:
{
m_shapes[event.key.code - sf::Keyboard::Num0].
setFillColor(sf::Color::Red);
return true;
}
default: break;
}
break;
}
case sf::Event::KeyReleased:
{
switch (event.key.code)
{
case sf::Keyboard::Num0:
case sf::Keyboard::Num1:
case sf::Keyboard::Num2:
case sf::Keyboard::Num3:
case sf::Keyboard::Num4:
case sf::Keyboard::Num5:
case sf::Keyboard::Num6:
case sf::Keyboard::Num7:
case sf::Keyboard::Num8:
case sf::Keyboard::Num9:
{
m_shapes[event.key.code - sf::Keyboard::Num0].
setFillColor(sf::Color::Green);
return true;
}
default: break;
}
break;
}
default: break;
}
return false;
}
void draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.clear(sf::Color(0x6688aa));
for (const sf::Shape &shape : m_shapes)
{
target.draw(shape, states);
}
}
private:
std::vector < sf::ConvexShape > m_shapes;
};
class MyApp : public App
{
public:
MyApp()
{
setTargetFPS(120.f);
setWindowStyle(sf::Style::Titlebar | sf::Style::Close);
}
protected:
void onStart()
{
createWindow();
pushState(m_myState);
}
bool onEvent(const sf::Event &event)
{
switch (event.type)
{
case sf::Event::KeyPressed:
{
if (event.key.code == sf::Keyboard::Escape)
{
if (getState() != &m_pauseState)
{
pushState(m_pauseState);
return true;
}
}
break;
}
default: break;
}
return false;
}
private:
PauseState m_pauseState;
MyState m_myState;
};
////////////////////////////////////////////////////////////////////////////////
extern "C"
int main (int argc, char **argv)
{
try
{
PhysicsFS physfs(argv[0]);
try
{
physfs.mount("data.zip");
}
catch (PhysicsFS::Error)
{
physfs.mount("data/");
}
LuaState lua;
if (!lua.tryDoFile("config.lua"))
{
sf::err() << "Config script error: " << lua.toString() << "\n";
}
try
{
lua.loadSafeLibs();
lua.doFile("data/scripts/init.lua");
MyApp app;
app.run();
}
catch (PhysicsFS::Error &exc)
{
sf::err() << "PhysFS error: " << exc.what() << "\n";
}
catch (LuaState::Error &exc)
{
sf::err() << "Lua error: " << exc.what() << "\n";
}
}
catch (std::exception &exc)
{
sf::err() << "Unhandled exception: " << exc.what() << "\n";
}
return(0);
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/**
* @file modifier.cpp
* @author partio
*/
#include "modifier.h"
using namespace himan;
modifier::modifier()
: itsMissingValuesAllowed(false)
, itsFindNthValue(1) // first
{
}
const std::vector<double>& modifier::Result() const
{
assert(itsResult.size());
return itsResult;
}
bool modifier::CalculationFinished() const
{
return false;
}
void modifier::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
}
bool modifier::IsMissingValue(double theValue) const
{
if (theValue == kFloatMissing)
{
return true;
}
return false;
}
void modifier::FindValue(const std::vector<double>& theFindValue)
{
itsFindValue = theFindValue;
}
size_t modifier::FindNth() const
{
return itsFindNthValue;
}
void modifier::FindNth(size_t theNth)
{
itsFindNthValue = theNth;
}
double modifier::Value() const
{
assert(itsIndex < itsResult.size());
return itsResult[itsIndex];
}
void modifier::Value(double theValue)
{
assert(itsIndex < itsResult.size());
itsResult[itsIndex] = theValue;
}
void modifier::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
}
}
void modifier::Process(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
Init(theData, theHeights);
assert(itsResult.size() == theData.size() && itsResult.size() == theHeights.size());
for (itsIndex = 0; itsIndex < itsResult.size(); itsIndex++)
{
Calculate(theData[itsIndex], theHeights[itsIndex]);
}
}
std::ostream& modifier::Write(std::ostream& file) const
{
file << "<" << ClassName() << ">" << std::endl;
file << "__itsMissingValuesAllowed__ " << itsMissingValuesAllowed << std::endl;
file << "__itsFindValue__ size " << itsFindValue.size() << std::endl;
file << "__itsFindNthValue__ " << itsFindNthValue << std::endl;
file << "__itsResult__ size " << itsResult.size() << std::endl;
file << "__itsIndex__ " << itsIndex << std::endl;
return file;
}
/* ----------------- */
void modifier_max::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value()) || theValue > Value())
{
Value(theValue);
}
}
/* ----------------- */
void modifier_min::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value()) || theValue < Value())
{
Value(theValue);
}
}
/* ----------------- */
void modifier_maxmin::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsMaximumResult.resize(theData.size(), kFloatMissing);
}
}
const std::vector<double>& modifier_maxmin::Result() const
{
itsResult.insert(itsResult.end(), itsMaximumResult.begin(), itsMaximumResult.end());
return itsResult;
}
void modifier_maxmin::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
// Set min == max
if (IsMissingValue(Value()))
{
itsResult[itsIndex] = theValue;
itsMaximumResult[itsIndex] = theValue;
}
else
{
if (theValue > itsMaximumResult[itsIndex])
{
itsMaximumResult[itsIndex] = theValue;
}
if (theValue < itsResult[itsIndex])
{
itsResult[itsIndex] = theValue;
}
}
}
/* ----------------- */
void modifier_sum::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value())) // First value
{
Value(theValue);
}
else
{
double val = Value();
Value(theValue+val);
}
}
/* ----------------- */
void modifier_mean::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsValuesCount.resize(itsResult.size(), 0);
}
}
void modifier_mean::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
itsValuesCount[itsIndex] += 1;
if (IsMissingValue(Value())) // First value
{
Value(theValue);
}
else
{
double val = Value();
Value(val + theValue);
}
}
const std::vector<double>& modifier_mean::Result() const
{
for (size_t i = 0; i < itsResult.size(); i++)
{
double val = itsResult[i];
size_t count = itsValuesCount[i];
if (!IsMissingValue(val) && count != 0)
{
itsResult[i] = val / static_cast<double> (count);
}
}
return itsResult;
}
/* ----------------- */
void modifier_count::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), 0);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
}
}
void modifier_count::Calculate(double theValue, double theHeight)
{
assert(itsFindValue.size());
double findValue = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || IsMissingValue(findValue))
{
return;
}
double previousValue = itsPreviousValue[itsIndex];
itsPreviousValue[itsIndex] = theValue;
// First level
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower value is found and current value is above wanted value, wanted value
* is found.
*
* Made up example
*
* How many times does value 11 exist inside a value range
*
* Input data set:
*
* Value
*
* 10
* --- Value 11 is found between these levels" --
* 12
* 9
* 9
* --- Value 11 is found between these levels! --
* 16
* 17
*
* The answer is: two times (as far as we know).
*/
if ((previousValue <= findValue && theValue >= findValue) // updward trend
||
(previousValue >= findValue && theValue <= findValue)) // downward trend
{
Value() == kFloatMissing ? Value(1) : Value(Value() + 1);
}
}
/* ----------------- */
void modifier_findheight::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
std::fill(itsPreviousValue.begin(), itsPreviousValue.end(), fillValue);
std::fill(itsPreviousHeight.begin(), itsPreviousHeight.end(), fillValue);
std::fill(itsFoundNValues.begin(), itsFoundNValues.end(), 0);
}
bool modifier_findheight::CalculationFinished() const
{
return itsValuesFound == itsResult.size();
}
void modifier_findheight::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
assert(theData.size());
itsResult.resize(theData.size(), kFloatMissing);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
itsPreviousHeight.resize(itsResult.size(), kFloatMissing);
itsFoundNValues.resize(itsResult.size(), 0);
itsValuesFound = 0;
}
}
void modifier_findheight::Calculate(double theValue, double theHeight)
{
assert(itsFindValue.size());
double findValue = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || IsMissingValue(findValue) || (itsFindNthValue > 0 && !IsMissingValue(Value())))
{
return;
}
if (fabs(theValue - findValue) < 1e-5)
{
Value(theHeight);
return;
}
double previousValue = itsPreviousValue[itsIndex];
double previousHeight = itsPreviousHeight[itsIndex];
itsPreviousValue[itsIndex] = theValue;
itsPreviousHeight[itsIndex] = theHeight;
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower value is found and current value is above wanted value, do the interpolation.
*
* Made up example
*
* Hight range: 120 - 125
* What is the height when parameter value is 15?
*
* Input data set:
*
* Height / Value
*
* 120 / 11
* 121 / 13
* 122 / 14
* --- Height of value 15 is found somewhere between these two levels! ---
* 123 / 16
* 124 / 19
* 125 / 19
*
* --> lowerValueThreshold = 14
* --> lowerHeightThreshold = 122
*
* --> theValue (== upperValueThreshold) = 16
* --> theHeight (== upperHeightThreshold) = 123
*
* Interpolate between (122,14),(123,16) to get the exact value !
*
*/
if ((previousValue <= findValue && theValue >= findValue) || (previousValue >= findValue && theValue <= findValue))
{
double actualHeight = NFmiInterpolation::Linear(findValue, previousValue, theValue, previousHeight, theHeight);
if (actualHeight != kFloatMissing)
{
if (itsFindNthValue != 0)
{
itsFoundNValues[itsIndex] += 1;
if (itsFindNthValue == itsFoundNValues[itsIndex])
{
Value(actualHeight);
itsValuesFound++;
}
}
else
{
// Search for the last value
Value(actualHeight);
}
}
}
}
/* ----------------- */
void modifier_findvalue::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
std::fill(itsPreviousValue.begin(), itsPreviousValue.end(), fillValue);
std::fill(itsPreviousHeight.begin(), itsPreviousHeight.end(), fillValue);
}
void modifier_findvalue::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
itsPreviousHeight.resize(itsResult.size(), kFloatMissing);
itsValuesFound = 0;
}
}
bool modifier_findvalue::CalculationFinished() const
{
return itsValuesFound == itsResult.size();
}
void modifier_findvalue::Calculate(double theValue, double theHeight)
{
double findHeight = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || !IsMissingValue(Value()) || IsMissingValue(findHeight))
{
return;
}
double previousValue = itsPreviousValue[itsIndex];
double previousHeight = itsPreviousHeight[itsIndex];
itsPreviousValue[itsIndex] = theValue;
itsPreviousHeight[itsIndex] = theHeight;
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower height is found and current height is above wanted height,
* do the interpolation.
*
* Made up example
*
* Height: 124
* What is the parameter value?
*
* Input data set:
*
* Height / Value
*
* 120 / 11
* 121 / 13
* 122 / 14
* 123 / 16
* --- Value of height 124 is found somewhere between these two levels! ---
* 126 / 19
* 128 / 19
*
* --> lowerValueThreshold = 16
* --> lowerHeightThreshold = 123
*
* --> theValue (== upperValueThreshold) = 19
* --> theHeight (== upperHeightThreshold) = 126
*
* Interpolate between (123,16),(126,19) to get the exact value !
*
*/
if ((previousHeight <= findHeight && theHeight >= findHeight) // upward trend
||
(previousHeight >= findHeight && theHeight <= findHeight)) // downward trend
{
double actualValue = NFmiInterpolation::Linear(findHeight, previousHeight, theHeight, previousValue, theValue);
if (actualValue != kFloatMissing)
{
Value(actualValue);
itsValuesFound++;
}
}
}
<commit_msg>small fixes<commit_after>/**
* @file modifier.cpp
* @author partio
*/
#include "modifier.h"
using namespace himan;
modifier::modifier()
: itsMissingValuesAllowed(false)
, itsFindNthValue(1) // first
{
}
const std::vector<double>& modifier::Result() const
{
assert(itsResult.size());
return itsResult;
}
bool modifier::CalculationFinished() const
{
return false;
}
void modifier::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
}
bool modifier::IsMissingValue(double theValue) const
{
if (theValue == kFloatMissing)
{
return true;
}
return false;
}
void modifier::FindValue(const std::vector<double>& theFindValue)
{
itsFindValue = theFindValue;
}
size_t modifier::FindNth() const
{
return itsFindNthValue;
}
void modifier::FindNth(size_t theNth)
{
itsFindNthValue = theNth;
}
double modifier::Value() const
{
assert(itsIndex < itsResult.size());
return itsResult[itsIndex];
}
void modifier::Value(double theValue)
{
assert(itsIndex < itsResult.size());
itsResult[itsIndex] = theValue;
}
void modifier::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
}
}
void modifier::Process(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
Init(theData, theHeights);
assert(itsResult.size() == theData.size() && itsResult.size() == theHeights.size());
for (itsIndex = 0; itsIndex < itsResult.size(); itsIndex++)
{
Calculate(theData[itsIndex], theHeights[itsIndex]);
}
}
std::ostream& modifier::Write(std::ostream& file) const
{
file << "<" << ClassName() << ">" << std::endl;
file << "__itsMissingValuesAllowed__ " << itsMissingValuesAllowed << std::endl;
file << "__itsFindValue__ size " << itsFindValue.size() << std::endl;
file << "__itsFindNthValue__ " << itsFindNthValue << std::endl;
file << "__itsResult__ size " << itsResult.size() << std::endl;
file << "__itsIndex__ " << itsIndex << std::endl;
return file;
}
/* ----------------- */
void modifier_max::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value()) || theValue > Value())
{
Value(theValue);
}
}
/* ----------------- */
void modifier_min::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value()) || theValue < Value())
{
Value(theValue);
}
}
/* ----------------- */
void modifier_maxmin::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsMaximumResult.resize(theData.size(), kFloatMissing);
}
}
const std::vector<double>& modifier_maxmin::Result() const
{
itsResult.insert(itsResult.end(), itsMaximumResult.begin(), itsMaximumResult.end());
return itsResult;
}
void modifier_maxmin::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
// Set min == max
if (IsMissingValue(Value()))
{
itsResult[itsIndex] = theValue;
itsMaximumResult[itsIndex] = theValue;
}
else
{
if (theValue > itsMaximumResult[itsIndex])
{
itsMaximumResult[itsIndex] = theValue;
}
if (theValue < itsResult[itsIndex])
{
itsResult[itsIndex] = theValue;
}
}
}
/* ----------------- */
void modifier_sum::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
if (IsMissingValue(Value())) // First value
{
Value(theValue);
}
else
{
double val = Value();
Value(theValue+val);
}
}
/* ----------------- */
void modifier_mean::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsValuesCount.resize(itsResult.size(), 0);
}
}
void modifier_mean::Calculate(double theValue, double theHeight)
{
if (IsMissingValue(theValue))
{
return;
}
itsValuesCount[itsIndex] += 1;
if (IsMissingValue(Value())) // First value
{
Value(theValue);
}
else
{
double val = Value();
Value(val + theValue);
}
}
const std::vector<double>& modifier_mean::Result() const
{
for (size_t i = 0; i < itsResult.size(); i++)
{
double val = itsResult[i];
size_t count = itsValuesCount[i];
if (!IsMissingValue(val) && count != 0)
{
itsResult[i] = val / static_cast<double> (count);
}
}
return itsResult;
}
/* ----------------- */
void modifier_count::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), 0);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
}
}
void modifier_count::Calculate(double theValue, double theHeight)
{
assert(itsFindValue.size());
double findValue = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || IsMissingValue(findValue))
{
return;
}
double previousValue = itsPreviousValue[itsIndex];
itsPreviousValue[itsIndex] = theValue;
// First level
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower value is found and current value is above wanted value, wanted value
* is found.
*
* Made up example
*
* How many times does value 11 exist inside a value range
*
* Input data set:
*
* Value
*
* 10
* --- Value 11 is found between these levels" --
* 12
* 9
* 9
* --- Value 11 is found between these levels! --
* 16
* 17
*
* The answer is: two times (as far as we know).
*/
if ((previousValue <= findValue && theValue >= findValue) // updward trend
||
(previousValue >= findValue && theValue <= findValue)) // downward trend
{
Value() == kFloatMissing ? Value(1) : Value(Value() + 1);
}
}
/* ----------------- */
void modifier_findheight::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
std::fill(itsPreviousValue.begin(), itsPreviousValue.end(), fillValue);
std::fill(itsPreviousHeight.begin(), itsPreviousHeight.end(), fillValue);
std::fill(itsFoundNValues.begin(), itsFoundNValues.end(), 0);
}
bool modifier_findheight::CalculationFinished() const
{
return (itsResult.size() && itsValuesFound == itsResult.size());
}
void modifier_findheight::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
assert(theData.size());
itsResult.resize(theData.size(), kFloatMissing);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
itsPreviousHeight.resize(itsResult.size(), kFloatMissing);
itsFoundNValues.resize(itsResult.size(), 0);
itsValuesFound = 0;
}
}
void modifier_findheight::Calculate(double theValue, double theHeight)
{
assert(itsFindValue.size() && itsIndex < itsFindValue.size());
double findValue = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || IsMissingValue(findValue) || (itsFindNthValue > 0 && !IsMissingValue(Value())))
{
return;
}
if (fabs(theValue - findValue) < 1e-5)
{
Value(theHeight);
return;
}
double previousValue = itsPreviousValue[itsIndex];
double previousHeight = itsPreviousHeight[itsIndex];
itsPreviousValue[itsIndex] = theValue;
itsPreviousHeight[itsIndex] = theHeight;
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower value is found and current value is above wanted value, do the interpolation.
*
* Made up example
*
* Hight range: 120 - 125
* What is the height when parameter value is 15?
*
* Input data set:
*
* Height / Value
*
* 120 / 11
* 121 / 13
* 122 / 14
* --- Height of value 15 is found somewhere between these two levels! ---
* 123 / 16
* 124 / 19
* 125 / 19
*
* --> lowerValueThreshold = 14
* --> lowerHeightThreshold = 122
*
* --> theValue (== upperValueThreshold) = 16
* --> theHeight (== upperHeightThreshold) = 123
*
* Interpolate between (122,14),(123,16) to get the exact value !
*
*/
if ((previousValue <= findValue && theValue >= findValue) || (previousValue >= findValue && theValue <= findValue))
{
double actualHeight = NFmiInterpolation::Linear(findValue, previousValue, theValue, previousHeight, theHeight);
if (actualHeight != kFloatMissing)
{
if (itsFindNthValue != 0)
{
itsFoundNValues[itsIndex] += 1;
if (itsFindNthValue == itsFoundNValues[itsIndex])
{
Value(actualHeight);
itsValuesFound++;
}
}
else
{
// Search for the last value
Value(actualHeight);
}
}
}
}
/* ----------------- */
void modifier_findvalue::Clear(double fillValue)
{
std::fill(itsResult.begin(), itsResult.end(), fillValue);
std::fill(itsPreviousValue.begin(), itsPreviousValue.end(), fillValue);
std::fill(itsPreviousHeight.begin(), itsPreviousHeight.end(), fillValue);
}
void modifier_findvalue::Init(const std::vector<double>& theData, const std::vector<double>& theHeights)
{
if (itsResult.size() == 0)
{
assert(theData.size() == theHeights.size());
itsResult.resize(theData.size(), kFloatMissing);
itsPreviousValue.resize(itsResult.size(), kFloatMissing);
itsPreviousHeight.resize(itsResult.size(), kFloatMissing);
itsValuesFound = 0;
}
}
bool modifier_findvalue::CalculationFinished() const
{
return (itsResult.size() && itsValuesFound == itsResult.size());
}
void modifier_findvalue::Calculate(double theValue, double theHeight)
{
assert(itsFindValue.size() && itsIndex < itsFindValue.size());
double findHeight = itsFindValue[itsIndex];
if (IsMissingValue(theValue) || !IsMissingValue(Value()) || IsMissingValue(findHeight))
{
return;
}
double previousValue = itsPreviousValue[itsIndex];
double previousHeight = itsPreviousHeight[itsIndex];
itsPreviousValue[itsIndex] = theValue;
itsPreviousHeight[itsIndex] = theHeight;
if (IsMissingValue(previousValue))
{
return;
}
/**
*
* If lower height is found and current height is above wanted height,
* do the interpolation.
*
* Made up example
*
* Height: 124
* What is the parameter value?
*
* Input data set:
*
* Height / Value
*
* 120 / 11
* 121 / 13
* 122 / 14
* 123 / 16
* --- Value of height 124 is found somewhere between these two levels! ---
* 126 / 19
* 128 / 19
*
* --> lowerValueThreshold = 16
* --> lowerHeightThreshold = 123
*
* --> theValue (== upperValueThreshold) = 19
* --> theHeight (== upperHeightThreshold) = 126
*
* Interpolate between (123,16),(126,19) to get the exact value !
*
*/
if ((previousHeight <= findHeight && theHeight >= findHeight) // upward trend
||
(previousHeight >= findHeight && theHeight <= findHeight)) // downward trend
{
double actualValue = NFmiInterpolation::Linear(findHeight, previousHeight, theHeight, previousValue, theValue);
if (actualValue != kFloatMissing)
{
Value(actualValue);
itsValuesFound++;
}
}
}
<|endoftext|> |
<commit_before>//
// Main.cpp
// Addie
//
// Created by Joachim Wester on 22/04/16.
// Copyright © 2016 Joachim Wester, Starcounter AB.
//
#include "VM.hpp"
#include "Reader.hpp"
#include "Compiler.hpp"
#include <iostream>
using namespace Addie;
using namespace Addie::Internals;
#ifdef USE_VECTOR
extern void TestMap();
#endif
#ifdef USE_INTARRAY
#include "Optimized_IntArray.hpp"
// Used by unit tests
IntArray<int>* CreateSimpleArray() {
IntArray<int>* arr = IntArray<int>::__beginWrite();
arr->__write(123);
arr->__write(789);
arr->__endWrite();
assert( arr->Count() == 2 );
assert( arr->GetAt(0).Integer == 123 );
assert( arr->GetAt(1).Integer == 789 );
return arr;
}
void TestIntArrays() {
IntArray<int>* arr = CreateSimpleArray();
arr->RefCount += 2;
List* arr2 = arr->ReplaceAt(1,INTEGER(456));
assert( arr->GetAt(1).Integer == 789 );
assert( arr2->Count() == 2 );
assert( arr2->GetAt(0).Integer == 123 );
assert( arr2->GetAt(1).Integer == 456 );
}
#endif
void TestAppend() {
std::cout << "Test Append:";
VALUE str(QString,INTEGER(74));
str.CheckIntegrety();
VALUE str2 = str.Append(INTEGER(97));
VALUE str3 = str2.Append(INTEGER(99));
VALUE str4 = str3.Append(INTEGER(107));
std::cout << str4.Print();
std::cout << "\n";
assert( strcmp("\"Jack\"",str4.Print().c_str()) == 0 );
}
void TestPrepend() {
std::cout << "Test Prepend:";
VALUE str(QString,INTEGER(107));
str.CheckIntegrety();
VALUE str2 = str.Prepend(INTEGER(99));
VALUE str3 = str2.Prepend(INTEGER(97));
VALUE str4 = str3.Prepend(INTEGER(74));
std::cout << str4.Print();
std::cout << "\n";
assert( strcmp("\"Jack\"",str4.Print().c_str()) == 0 );
}
void TestArrays() {
#ifdef USE_INTARRAY
TestIntArrays();
#endif
TestAppend();
TestPrepend();
}
VALUE IllustrateParse( const char* str ) {
std::cout << "\n**** Parsing ****\n" << str << "\n";
std::cout << "===>\n";
auto teststr = StringReader(str,strlen(str));
VALUE v = Parser::Parse( &teststr );
std::cout << v.Print();
std::cout << "\n";
return v;
}
VALUE TestParse( const char* input, const char* expectedOutput ) {
VALUE v = IllustrateParse( input );
const char* output = v.Print().c_str();
assert( strcmp( expectedOutput, output ) == 0 );
return v;
}
VALUE TestParse( const char* input, int expectedCount, const char* expectedOutput ) {
VALUE x = IllustrateParse( input );
VALUE v;
v.Whole = x.Whole;
int actualCount = v.GetList()->Count();
const char* output = v.Print().c_str();
assert( actualCount == expectedCount );
assert( strcmp( expectedOutput, output ) == 0 );
return v;
}
VALUE TestRun( const char* input, VALUE expectedOutput ) {
Isolate isolate;
//Namespace* ns = MALLOC_HEAP(Namespace);
//new (ns) Namespace();
VALUE v = Parser::Parse( input );
MetaCompilation* mc = Compiler::Compile( &isolate, v );
std::cout << Compiler::Disassemble(&isolate, mc->compilation, mc ).ToString();
Continuation c = Interpreter::Interpret( &isolate, mc->compilation );
v = c.GetReturnValue();
c.ExitRuntimeFrame(&isolate);
std::cout << input << " == " << v.Print() << "\n";
assert( v.Equals(expectedOutput) );
return v;
}
void TestFn() {
Isolate isolate;
VALUE v;
v = TestParse("⏜\nlet* [y 6 z 5]\n ⏜\n fn* [x]\n ⏜\n let* ﹇\n a 10\n b 20\n ﹈\n (print (+ a b x y) (+ a z))\n ⏝\n ⏝\n⏝",
"(let* [y 6 z 5] (fn* [x] (let* [a 10 b 20] (print (+ a b x y) (+ a z)))))");
// Namespace ns;
MetaCompilation* mc = Compiler::Compile( &isolate, v );
STRINGOLD str = Compiler::Disassemble( &isolate, mc->compilation, mc );
std::cout << str.ToString();
Continuation c = Interpreter::Interpret( &isolate, mc->compilation );
Interpreter::Interpret( &isolate,c);
c.ExitRuntimeFrame(&isolate);
v = TestParse( "{ :FirstName \"Jack\" }", "{:FirstName \"Jack\"}" );
mc = Compiler::Compile( &isolate, v );
std::cout << Compiler::Disassemble(&isolate, mc->compilation, mc ).ToString();
c = Interpreter::Interpret( &isolate, mc->compilation );
c.ExitRuntimeFrame(&isolate);
//assert(c.HasRunToCompletion());
std::cout << "\nEvaluated:" << c.GetReturnValue().Print();
std::cout << "\n\n";
}
int main(int argc, const char * argv[]) {
Isolate isolate;
CurrentIsolate = &isolate;
VALUE v;
assert( sizeof(VALUE) == sizeof(uintptr_t) ); // If we are on a 64 bit machine we want 64
// bit values
assert( sizeof(Instruction) == 4 ); // Our byte instructions are 32 bit
TestArrays();
TestParse("︷ ︸","{}");
TestParse( "⏞ ⏟","{}");
TestParse( "﹇﹈","[]");
TestParse( "⎴ ⎵ ","[]");
TestParse( "⏜⏝","()");
TestParse( "\"Jack\"", 4, "\"Jack\"" );
TestParse("(\"Jack\" \"Wester\")", 2, "(\"Jack\" \"Wester\")");
TestParse( "⏜\nif (= einstein genius)\n (print \"e=mc²\")\n (print \"e!=mc²\")\n⏝",
"(if (= einstein genius) (print \"e=mc²\") (print \"e!=mc²\"))");
TestParse("⏜\n ⏜\n defn pow [n] \n ⏜\n fn [x]\n (apply * (repeat n x))\n ⏝\n ⏝\n (def ² (pow 2))\n (def ³ (pow 3))\n⏝",
"((defn pow [n] (fn [x] (apply * (repeat n x)))) (def ² (pow 2)) (def ³ (pow 3)))");
//TestParse("(print 123) (print 456)",
// "(print 123) (print 456)");
//TestFn();
//TestRun("(+ 1 2 3)",INTEGER(6));
//TestRun("(fn* [] (+ 1 2 3))",VALUE(OFunction,1));
TestRun("((fn* [x y] (+ 2 3 x y)) 10 4)",INTEGER(19)); // VALUE(OFunction,1));
TestRun("((fn* [x y] (- 2 -3 x y)) 10 4)",INTEGER(-13)); // VALUE(OFunction,1));
TestRun("((fn* [x y] (* 2 3 x y)) 10 4)",INTEGER(240)); // VALUE(OFunction,1));
TestRun("(/ 20 2 2)",INTEGER(5));
TestRun("(+ 1 2)",INTEGER(3));
TestRun("(+ 1)",INTEGER(1));
TestRun("(+)",INTEGER(0));
TestRun("(def a 1)",INTEGER(1));
TestRun("(do (def b 123) b)",INTEGER(123));
#ifdef USE_VECTOR
TestMap();
#endif
}<commit_msg>Preparing for making CALL/SCALL instructions work for both user defined and built-in functions<commit_after>//
// Main.cpp
// Addie
//
// Created by Joachim Wester on 22/04/16.
// Copyright © 2016 Joachim Wester, Starcounter AB.
//
#include "VM.hpp"
#include "Reader.hpp"
#include "Compiler.hpp"
#include <iostream>
using namespace Addie;
using namespace Addie::Internals;
#ifdef USE_VECTOR
extern void TestMap();
#endif
#ifdef USE_INTARRAY
#include "Optimized_IntArray.hpp"
// Used by unit tests
IntArray<int>* CreateSimpleArray() {
IntArray<int>* arr = IntArray<int>::__beginWrite();
arr->__write(123);
arr->__write(789);
arr->__endWrite();
assert( arr->Count() == 2 );
assert( arr->GetAt(0).Integer == 123 );
assert( arr->GetAt(1).Integer == 789 );
return arr;
}
void TestIntArrays() {
IntArray<int>* arr = CreateSimpleArray();
arr->RefCount += 2;
List* arr2 = arr->ReplaceAt(1,INTEGER(456));
assert( arr->GetAt(1).Integer == 789 );
assert( arr2->Count() == 2 );
assert( arr2->GetAt(0).Integer == 123 );
assert( arr2->GetAt(1).Integer == 456 );
}
#endif
void TestAppend() {
std::cout << "Test Append:";
VALUE str(QString,INTEGER(74));
str.CheckIntegrety();
VALUE str2 = str.Append(INTEGER(97));
VALUE str3 = str2.Append(INTEGER(99));
VALUE str4 = str3.Append(INTEGER(107));
std::cout << str4.Print();
std::cout << "\n";
assert( strcmp("\"Jack\"",str4.Print().c_str()) == 0 );
}
void TestPrepend() {
std::cout << "Test Prepend:";
VALUE str(QString,INTEGER(107));
str.CheckIntegrety();
VALUE str2 = str.Prepend(INTEGER(99));
VALUE str3 = str2.Prepend(INTEGER(97));
VALUE str4 = str3.Prepend(INTEGER(74));
std::cout << str4.Print();
std::cout << "\n";
assert( strcmp("\"Jack\"",str4.Print().c_str()) == 0 );
}
void TestArrays() {
#ifdef USE_INTARRAY
TestIntArrays();
#endif
TestAppend();
TestPrepend();
}
VALUE IllustrateParse( const char* str ) {
std::cout << "\n**** Parsing ****\n" << str << "\n";
std::cout << "===>\n";
auto teststr = StringReader(str,strlen(str));
VALUE v = Parser::Parse( &teststr );
std::cout << v.Print();
std::cout << "\n";
return v;
}
VALUE TestParse( const char* input, const char* expectedOutput ) {
VALUE v = IllustrateParse( input );
const char* output = v.Print().c_str();
assert( strcmp( expectedOutput, output ) == 0 );
return v;
}
VALUE TestParse( const char* input, int expectedCount, const char* expectedOutput ) {
VALUE x = IllustrateParse( input );
VALUE v;
v.Whole = x.Whole;
int actualCount = v.GetList()->Count();
const char* output = v.Print().c_str();
assert( actualCount == expectedCount );
assert( strcmp( expectedOutput, output ) == 0 );
return v;
}
VALUE TestRun( const char* input, VALUE expectedOutput ) {
Isolate isolate;
//Namespace* ns = MALLOC_HEAP(Namespace);
//new (ns) Namespace();
VALUE v = Parser::Parse( input );
MetaCompilation* mc = Compiler::Compile( &isolate, v );
std::cout << Compiler::Disassemble(&isolate, mc->compilation, mc ).ToString();
Continuation c = Interpreter::Interpret( &isolate, mc->compilation );
v = c.GetReturnValue();
c.ExitRuntimeFrame(&isolate);
std::cout << input << " == " << v.Print() << "\n";
assert( v.Equals(expectedOutput) );
return v;
}
void TestFn() {
Isolate isolate;
VALUE v;
v = TestParse("⏜\nlet* [y 6 z 5]\n ⏜\n fn* [x]\n ⏜\n let* ﹇\n a 10\n b 20\n ﹈\n (print (+ a b x y) (+ a z))\n ⏝\n ⏝\n⏝",
"(let* [y 6 z 5] (fn* [x] (let* [a 10 b 20] (print (+ a b x y) (+ a z)))))");
// Namespace ns;
MetaCompilation* mc = Compiler::Compile( &isolate, v );
STRINGOLD str = Compiler::Disassemble( &isolate, mc->compilation, mc );
std::cout << str.ToString();
Continuation c = Interpreter::Interpret( &isolate, mc->compilation );
Interpreter::Interpret( &isolate,c);
c.ExitRuntimeFrame(&isolate);
v = TestParse( "{ :FirstName \"Jack\" }", "{:FirstName \"Jack\"}" );
mc = Compiler::Compile( &isolate, v );
std::cout << Compiler::Disassemble(&isolate, mc->compilation, mc ).ToString();
c = Interpreter::Interpret( &isolate, mc->compilation );
c.ExitRuntimeFrame(&isolate);
//assert(c.HasRunToCompletion());
std::cout << "\nEvaluated:" << c.GetReturnValue().Print();
std::cout << "\n\n";
}
int main(int argc, const char * argv[]) {
Isolate isolate;
CurrentIsolate = &isolate;
VALUE v;
assert( sizeof(VALUE) == sizeof(uintptr_t) ); // If we are on a 64 bit machine we want 64
// bit values
assert( sizeof(Instruction) == 4 ); // Our byte instructions are 32 bit
TestArrays();
TestParse("︷ ︸","{}");
TestParse( "⏞ ⏟","{}");
TestParse( "﹇﹈","[]");
TestParse( "⎴ ⎵ ","[]");
TestParse( "⏜⏝","()");
TestParse( "\"Jack\"", 4, "\"Jack\"" );
TestParse("(\"Jack\" \"Wester\")", 2, "(\"Jack\" \"Wester\")");
TestParse( "⏜\nif (= einstein genius)\n (print \"e=mc²\")\n (print \"e!=mc²\")\n⏝",
"(if (= einstein genius) (print \"e=mc²\") (print \"e!=mc²\"))");
TestParse("⏜\n ⏜\n defn pow [n] \n ⏜\n fn [x]\n (apply * (repeat n x))\n ⏝\n ⏝\n (def ² (pow 2))\n (def ³ (pow 3))\n⏝",
"((defn pow [n] (fn [x] (apply * (repeat n x)))) (def ² (pow 2)) (def ³ (pow 3)))");
//TestParse("(print 123) (print 456)",
// "(print 123) (print 456)");
//TestFn();
//TestRun("(+ 1 2 3)",INTEGER(6));
//TestRun("(fn* [] (+ 1 2 3))",VALUE(OFunction,1));
TestRun("((fn* [x y] (+ 2 3 x y)) 10 4)",INTEGER(19)); // VALUE(OFunction,1));
TestRun("((fn* [x y] (- 2 -3 x y)) 10 4)",INTEGER(-13)); // VALUE(OFunction,1));
TestRun("((fn* [x y] (* 2 3 x y)) 10 4)",INTEGER(240)); // VALUE(OFunction,1));
TestRun("(/ 20 2 2)",INTEGER(5));
TestRun("(+ 1 2)",INTEGER(3));
TestRun("(+ 1)",INTEGER(1));
TestRun("(+)",INTEGER(0));
TestRun("(def a 1)",INTEGER(1));
TestRun("(do (def b 123) b)",INTEGER(123));
//TestRun("(do (def pow2 (fn [x] (* x x))) (pow2 3))",INTEGER(9));
#ifdef USE_VECTOR
TestMap();
#endif
}<|endoftext|> |
<commit_before>#ifndef DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
#define DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
// forward, to be used in the traits
class CoarseBasisProduct;
/**
* \brief Traits for the Product evaluation.
*/
class ProductTraitsBase {
public:
typedef Problem::LocalDiffusionType LocalizableFunctionType;
typedef LocalizableFunctionType::EntityType EntityType;
typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;
typedef std::tuple<std::shared_ptr<LocalfunctionType>> LocalfunctionTupleType;
static constexpr auto dimDomain = CommonTraits::dimDomain;
static constexpr auto dimRange = CommonTraits::dimRange;
typedef CommonTraits::DomainFieldType DomainFieldType;
static_assert(std::is_base_of<Dune::Stuff::IsLocalizableFunction, LocalizableFunctionType>::value,
"LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction.");
};
struct CoarseBasisProductTraits : public ProductTraitsBase {
typedef CoarseBasisProduct derived_type;
};
class CoarseBasisProduct : public GDT::LocalEvaluation::Codim0Interface<CoarseBasisProductTraits, 1> {
typedef MsFEMTraits::LocalEntityType EntityType;
public:
typedef CoarseBasisProductTraits Traits;
typedef typename Traits::DomainFieldType DomainFieldType;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
CoarseBasisProduct(const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base,
const LocalizableFunctionType& inducingFunction, const std::size_t coarseBaseFunc)
: inducingFunction_(inducingFunction)
, coarse_base_set_(coarse_base)
, coarseBaseFunc_(coarseBaseFunc) {}
CoarseBasisProduct(const CoarseBasisProduct&) = default;
typename Traits::LocalfunctionTupleType localFunctions(const EntityType& entity) const {
return std::make_tuple(inducingFunction_.local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class E, size_t d, class R, size_t rT, size_t rCT>
size_t order(const typename Traits::LocalfunctionTupleType& localFuncs,
const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const {
const auto localFunction = std::get<0>(localFuncs);
return order(*localFunction, testBase);
}
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class E, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT>
size_t order(const Stuff::LocalfunctionInterface<E, DomainFieldType, d, R, rL, rCL>& localFunction,
const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const {
return localFunction.order() + testBase.order();
} // int order(...)
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <size_t d, class R, size_t rT, size_t rCT>
void evaluate(const typename Traits::LocalfunctionTupleType& localFuncs,
const Stuff::LocalfunctionSetInterface<EntityType, DomainFieldType, d, R, rT, rCT>& testBase,
const Dune::FieldVector<DomainFieldType, d>& localPoint, Dune::DynamicVector<R>& ret) const {
const auto& localFunction = std::get<0>(localFuncs);
evaluate(*localFunction, testBase, localPoint, ret);
}
template< class R, size_t r, size_t rC >
void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const
{
// evaluate local function
const auto& entity = testBase.entity();
const auto global_point = entity.geometry().global(localPoint);
const auto& coarse_entity = coarse_base_set_.entity();
const auto quadInCoarseLocal = coarse_entity.geometry().local(global_point);
const auto coarseBaseFuncJacs = coarse_base_set_.jacobian(quadInCoarseLocal);
const auto direction = coarseBaseFuncJacs[coarseBaseFunc_];
DMP::JacobianRangeType flux;
//! todo make member
DMP::getDiffusion().diffusiveFlux(global_point, direction, flux);
// evaluate test base
const std::size_t size = testBase.size();
const auto transformed_gradients = testBase.jacobian(localPoint);
// compute product
assert(ret.size() >= size);
assert(transformed_gradients.size() >= size);
//! \TODO WTF muss hier eigentlich hin
for (size_t ii = 0; ii < size; ++ii) {
// transformed_gradients[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2>
ret[ii] = -1 * (flux[0] * transformed_gradients[ii][0]);
// DSC_LOG_DEBUG << "DIFF " << global_point << " | " << flux << " | " << grad_phi_s[ii][0]<< std::endl;
}
}
private:
const LocalizableFunctionType& inducingFunction_;
const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base_set_;
const std::size_t coarseBaseFunc_;
}; // class CoarseBasisProduct
// forward, to be used in the traits
class DirichletProduct;
/**
* \brief Traits for the Product evaluation.
*/
struct DirichletProductTraits : public ProductTraitsBase {
typedef DirichletProduct derived_type;
};
class DirichletProduct : public GDT::LocalEvaluation::Codim0Interface<DirichletProductTraits, 1> {
public:
typedef DirichletProductTraits Traits;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
DirichletProduct(const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension,
const LocalizableFunctionType& inducingFunction)
: inducingFunction_(inducingFunction)
, dirichlet_extension_(dirichlet_extension) {}
template <class EntityType>
class LocalfunctionTuple {
typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;
public:
typedef std::tuple<std::shared_ptr<LocalfunctionType>> Type;
};
template <class EntityType>
typename LocalfunctionTuple<EntityType>::Type localFunctions(const EntityType& entity) const {
return std::make_tuple(inducingFunction_.local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class E, class D, size_t d, class R, size_t rT, size_t rCT>
size_t order(const typename LocalfunctionTuple<E>::Type& localFuncs,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const {
const auto localFunction = std::get<0>(localFuncs);
return order(*localFunction, testBase);
}
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class E, class D, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT>
size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& localFunction,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const {
return localFunction.order() + testBase.order();
} // int order(...)
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class E, class D, size_t d, class R, size_t rT, size_t rCT>
void evaluate(const typename LocalfunctionTuple<E>::Type& localFuncs,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const {
const auto& localFunction = std::get<0>(localFuncs);
evaluate(*localFunction, testBase, localPoint, ret);
}
template< class R, size_t r, size_t rC >
void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const {
// evaluate local function
const auto& entity = testBase.entity();
const auto dirichlet_lf = dirichlet_extension_.local_function(entity);
const auto direction = dirichlet_lf->jacobian(localPoint);
DMP::JacobianRangeType flux;
const auto global_point = entity.geometry().global(localPoint);
//!TODO make member
DMP::getDiffusion().diffusiveFlux(global_point, direction, flux);
// evaluate test base
const std::size_t size = testBase.size();
typedef typename Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>::JacobianRangeType JR;
const std::vector<JR> grad_phi_s = testBase.jacobian(localPoint);
// compute product
assert(ret.size() >= size);
assert(grad_phi_s.size() >= size);
//! \TODO WTF muss hier eigentlich hin
for (size_t ii = 0; ii < size; ++ii) {
// grad_phi_s[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2>
ret[ii] = -1 * (flux[0] * grad_phi_s[ii][0]);
}
}
private:
const LocalizableFunctionType& inducingFunction_;
const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension_;
}; // class Product
} // namespace Multiscale {
} // namespace Dune {
#endif // DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
<commit_msg>really fixes type mismatch regression in coarse product evals<commit_after>#ifndef DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
#define DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/gdt/functionals/l2.hh>
namespace Dune {
namespace Multiscale {
// forward, to be used in the traits
class CoarseBasisProduct;
/**
* \brief Traits for the Product evaluation.
*/
class ProductTraitsBase {
public:
typedef Problem::LocalDiffusionType LocalizableFunctionType;
typedef LocalizableFunctionType::EntityType EntityType;
typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;
typedef std::tuple<std::shared_ptr<LocalfunctionType>> LocalfunctionTupleType;
static constexpr auto dimDomain = CommonTraits::dimDomain;
static constexpr auto dimRange = CommonTraits::dimRange;
typedef CommonTraits::DomainFieldType DomainFieldType;
static_assert(std::is_base_of<Dune::Stuff::IsLocalizableFunction, LocalizableFunctionType>::value,
"LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction.");
};
struct CoarseBasisProductTraits : public ProductTraitsBase {
typedef CoarseBasisProduct derived_type;
};
class CoarseBasisProduct : public GDT::LocalEvaluation::Codim0Interface<CoarseBasisProductTraits, 1> {
typedef MsFEMTraits::LocalEntityType EntityType;
public:
typedef CoarseBasisProductTraits Traits;
typedef typename Traits::DomainFieldType DomainFieldType;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
CoarseBasisProduct(const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base,
const LocalizableFunctionType& inducingFunction, const std::size_t coarseBaseFunc)
: inducingFunction_(inducingFunction)
, coarse_base_set_(coarse_base)
, coarseBaseFunc_(coarseBaseFunc) {}
CoarseBasisProduct(const CoarseBasisProduct&) = default;
typename Traits::LocalfunctionTupleType localFunctions(const EntityType& entity) const {
return std::make_tuple(inducingFunction_.local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class E, size_t d, class R, size_t rT, size_t rCT>
size_t order(const typename Traits::LocalfunctionTupleType& localFuncs,
const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const {
const auto localFunction = std::get<0>(localFuncs);
return order(*localFunction, testBase);
}
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class E, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT>
size_t order(const Stuff::LocalfunctionInterface<E, DomainFieldType, d, R, rL, rCL>& localFunction,
const Stuff::LocalfunctionSetInterface<E, DomainFieldType, d, R, rT, rCT>& testBase) const {
return localFunction.order() + testBase.order();
} // int order(...)
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <size_t d, class R, size_t rT, size_t rCT>
void evaluate(const typename Traits::LocalfunctionTupleType& localFuncs,
const Stuff::LocalfunctionSetInterface<EntityType, DomainFieldType, d, R, rT, rCT>& testBase,
const Dune::FieldVector<DomainFieldType, d>& localPoint, Dune::DynamicVector<R>& ret) const {
const auto& localFunction = std::get<0>(localFuncs);
evaluate(*localFunction, testBase, localPoint, ret);
}
template< class R, size_t r, size_t rC >
void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const
{
// evaluate local function
const auto& entity = testBase.entity();
const auto global_point = entity.geometry().global(localPoint);
const auto& coarse_entity = coarse_base_set_.entity();
const auto quadInCoarseLocal = coarse_entity.geometry().local(global_point);
const auto coarseBaseFuncJacs = coarse_base_set_.jacobian(quadInCoarseLocal);
const auto direction = coarseBaseFuncJacs[coarseBaseFunc_];
DMP::JacobianRangeType flux;
//! todo make member
DMP::getDiffusion().diffusiveFlux(global_point, direction, flux);
// evaluate test base
const std::size_t size = testBase.size();
const auto transformed_gradients = testBase.jacobian(localPoint);
// compute product
assert(ret.size() >= size);
assert(transformed_gradients.size() >= size);
//! \TODO WTF muss hier eigentlich hin
for (size_t ii = 0; ii < size; ++ii) {
// transformed_gradients[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2>
ret[ii] = -1 * (flux[0] * transformed_gradients[ii][0]);
// DSC_LOG_DEBUG << "DIFF " << global_point << " | " << flux << " | " << grad_phi_s[ii][0]<< std::endl;
}
}
private:
const LocalizableFunctionType& inducingFunction_;
const Multiscale::CommonTraits::BaseFunctionSetType& coarse_base_set_;
const std::size_t coarseBaseFunc_;
}; // class CoarseBasisProduct
// forward, to be used in the traits
class DirichletProduct;
/**
* \brief Traits for the Product evaluation.
*/
struct DirichletProductTraits : public ProductTraitsBase {
typedef DirichletProduct derived_type;
};
class DirichletProduct : public GDT::LocalEvaluation::Codim0Interface<DirichletProductTraits, 1> {
public:
typedef DirichletProductTraits Traits;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
DirichletProduct(const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension,
const LocalizableFunctionType& inducingFunction)
: inducingFunction_(inducingFunction)
, dirichlet_extension_(dirichlet_extension) {}
template <class EntityType>
class LocalfunctionTuple {
typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;
public:
typedef std::tuple<std::shared_ptr<LocalfunctionType>> Type;
};
template <class EntityType>
typename LocalfunctionTuple<EntityType>::Type localFunctions(const EntityType& entity) const {
return std::make_tuple(inducingFunction_.local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class E, class D, size_t d, class R, size_t rT, size_t rCT>
size_t order(const typename LocalfunctionTuple<E>::Type& localFuncs,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const {
const auto localFunction = std::get<0>(localFuncs);
return order(*localFunction, testBase);
}
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class E, class D, size_t d, class R, size_t rL, size_t rCL, size_t rT, size_t rCT>
size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rL, rCL>& localFunction,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase) const {
return localFunction.order() + testBase.order();
} // int order(...)
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class E, class D, size_t d, class R, size_t rT, size_t rCT>
void evaluate(const typename LocalfunctionTuple<E>::Type& localFuncs,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& testBase,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const {
const auto& localFunction = std::get<0>(localFuncs);
evaluate(*localFunction, testBase, localPoint, ret);
}
template< class R, size_t r, size_t rC >
void evaluate(const typename Traits::LocalfunctionTupleType& /*localFunctions_in*/,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const {
// evaluate local function
const auto& entity = testBase.entity();
const auto dirichlet_lf = dirichlet_extension_.local_function(entity);
const auto direction = dirichlet_lf->jacobian(localPoint);
DMP::JacobianRangeType flux;
const auto global_point = entity.geometry().global(localPoint);
//!TODO make member
DMP::getDiffusion().diffusiveFlux(global_point, direction, flux);
// evaluate test base
const std::size_t size = testBase.size();
const auto grad_phi_s = testBase.jacobian(localPoint);
// compute product
assert(ret.size() >= size);
assert(grad_phi_s.size() >= size);
//! \TODO WTF muss hier eigentlich hin
for (size_t ii = 0; ii < size; ++ii) {
// grad_phi_s[ii] is FieldMatrix<double, 1, 2> --> grad_phi_s[ii][0] is FieldVector<double,2>
ret[ii] = -1 * (flux[0] * grad_phi_s[ii][0]);
}
}
private:
const LocalizableFunctionType& inducingFunction_;
const MsFEMTraits::LocalGridDiscreteFunctionType& dirichlet_extension_;
}; // class Product
} // namespace Multiscale {
} // namespace Dune {
#endif // DUNE_MULTISCALE_MSFEM_DIFFUSION_EVALUATION_HH
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <chrono>
#include "mpihead.hpp"
#include "epa.hpp"
using namespace std;
static void print_help()
{
cout << "EPA - Evolutionary Placement Algorithm" << endl << endl;
cout << "USAGE: epa [options]" << endl << endl;
cout << "OPTIONS:" << endl;
cout << " -h \tDisplay this page" << endl;
cout << " -t \tPath to Tree file" << endl;
cout << " -s \tPath to reference MSA file. May also include the query sequences." << endl;
cout << " -q \tPath to separate query MSA file. If none is provided, epa will assume" << endl;
cout << " \tquery reads are in the reference MSA file (-s)" << endl;
cout << " -w \tPath to working directory" << endl;
cout << " -r \tRanged heuristic: only consider portion of query sequence sites not flanked by gaps during insertion" << endl;
cout << " \t DEFAULT: OFF" << endl;
cout << " -g \tTwo-phase heuristic, determination of candidate edges using accumulative threshold" << endl;
cout << " \t" << endl;
cout << " -G \tTwo-phase heuristic, determination of candidate edges by specified percentage of total edges" << endl;
cout << " \t" << endl;
cout << " -O \toptimize reference tree and model parameters" << endl;
cout << " -l \tspecify minimum likelihood weight below which a placement is discarded" << endl;
cout << " \t DEFAULT: 0.01" << endl;
cout << " -L \tspecify accumulated likelihood weight after which further placements are discarded" << endl;
cout << " \t DEFAULT: OFF" << endl;
cout << " -m \tSpecify model of nucleotide substitution" << endl;
cout << " \tGTR \tGeneralized time reversible (DEFAULT)" << endl;
cout << " \tJC69\tJukes-Cantor Model" << endl;
cout << " \tK80 \tKimura 80 Model" << endl;
}
static void inv(string msg)
{
int mpi_rank = 0;
MPI_COMM_RANK(MPI_COMM_WORLD, &mpi_rank);
if (mpi_rank == 0)
{
if (msg.size())
cerr << msg << endl;
print_help();
cout.flush();
}
MPI_FINALIZE();
exit(EXIT_FAILURE);
}
static void ensure_dir_has_slash(string& dir)
{
if (dir.length() > 0 && dir.back() != '/')
dir += "/";
}
int main(int argc, char** argv)
{
MPI_INIT(&argc, &argv);
string invocation("");
string model_id("GTR");
Options options;
for (int i = 0; i < argc; ++i)
{
invocation += argv[i];
invocation += " ";
}
string query_file("");
string work_dir("");
string tree_file("");
string reference_file("");
string binary_file("");
int c;
while((c = getopt(argc, argv, "hOBb:t:s:q:l:L:w:g::G::r")) != EOF)
{
switch (c)
{
case 't':
tree_file += optarg;
break;
case 's':
reference_file += optarg;
break;
case 'q':
query_file += optarg;
break;
case 'w':
work_dir += optarg;
break;
case 'l':
options.support_threshold = stod(optarg);
if (options.support_threshold < 0.0)
inv("Support threshold cutoff too small! Range: [0,1)");
if (options.support_threshold >= 1.0)
inv("Support threshold cutoff too large! Range: [0,1)");
break;
case 'L':
options.support_threshold = stod(optarg);
if (options.support_threshold <= 0.0)
inv("Accumulated support threshold cutoff too small! Range: (0,1]");
if (options.support_threshold > 1.0)
inv("Accumulated support threshold cutoff too large! Range: (0,1]");
options.acc_threshold = true;
break;
case 'h':
inv("");
break;
case 'g':
if (options.prescoring)
inv("-g cannot be used simultaneously with -G!");
if (optarg)
options.prescoring_threshold = stod(optarg);
if (options.prescoring_threshold < 0.0)
inv("Prescoring threshold cutoff too small! Range: [0,1]");
if (options.prescoring_threshold > 1.0)
inv("Prescoring threshold cutoff too large! Range: [0,1]");
options.prescoring = true;
break;
case 'G':
if (options.prescoring)
inv("-g cannot be used simultaneously with -G!");
if (optarg)
options.prescoring_threshold = stod(optarg);
else
options.prescoring_threshold = 0.1;
if (options.prescoring_threshold < 0.0)
inv("Prescoring threshold cutoff too small! Range: [0,1]");
if (options.prescoring_threshold > 1.0)
inv("Prescoring threshold cutoff too large! Range: [0,1]");
options.prescoring = true;
options.prescoring_by_percentage = true;
break;
case 'O':
options.opt_branches = true;
options.opt_model = true;
break;
case 'r':
options.ranged = true;
break;
case 'B':
options.dump_binary_mode = true;
break;
case 'b':
options.load_binary_mode = true;
binary_file += optarg;
break;
case ':':
inv("Invalid option.");
break;
}
}
//================================================================
//============ EPA =========================================
//================================================================
ensure_dir_has_slash(work_dir);
MSA ref_msa;
if (reference_file.size())
ref_msa = build_MSA_from_file(reference_file);
Model model(model_id);
// build the Tree
Tree tree;
if (options.load_binary_mode)
{
cout << "Loading from binary" << endl;
tree = Tree(binary_file, options);
}
else
{
// build the full tree with all possible clv's
tree = Tree(tree_file, ref_msa, model, options);
}
// build the query stream
MSA_Stream queries;
if ((query_file.size() != 0) and not options.dump_binary_mode)
{
queries = MSA_Stream(query_file);
}
// attempt to split msa if it is intermingled with (supposed) query sequences
else
{
throw runtime_error{"Combined MSA files not currently supported, please split them and specify using -s and -q."};
// split_combined_msa(ref_msa, queries, tree);
}
// dump to binary if specified
if (options.dump_binary_mode)
{
cout << "Writing to binary" << endl;
string dump_file(work_dir + "epa_binary_file");
dump_to_binary(tree, dump_file);
MPI_FINALIZE();
return EXIT_SUCCESS;
}
// start the placement process and write to file
auto start = chrono::high_resolution_clock::now();
process(tree, queries, work_dir, options, invocation);
// MSA full_msa = build_MSA_from_file(query_file);
// place(tree, full_msa);
auto end = chrono::high_resolution_clock::now();
auto runtime = chrono::duration_cast<chrono::seconds>(end - start).count();
cout << "\nTime spent placing: " << runtime << "s" << endl;
MPI_FINALIZE();
return EXIT_SUCCESS;
}
<commit_msg>fixed incorrect error<commit_after>#include <iostream>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <chrono>
#include "mpihead.hpp"
#include "epa.hpp"
using namespace std;
static void print_help()
{
cout << "EPA - Evolutionary Placement Algorithm" << endl << endl;
cout << "USAGE: epa [options]" << endl << endl;
cout << "OPTIONS:" << endl;
cout << " -h \tDisplay this page" << endl;
cout << " -t \tPath to Tree file" << endl;
cout << " -s \tPath to reference MSA file. May also include the query sequences." << endl;
cout << " -q \tPath to separate query MSA file. If none is provided, epa will assume" << endl;
cout << " \tquery reads are in the reference MSA file (-s)" << endl;
cout << " -w \tPath to working directory" << endl;
cout << " -r \tRanged heuristic: only consider portion of query sequence sites not flanked by gaps during insertion" << endl;
cout << " \t DEFAULT: OFF" << endl;
cout << " -g \tTwo-phase heuristic, determination of candidate edges using accumulative threshold" << endl;
cout << " \t" << endl;
cout << " -G \tTwo-phase heuristic, determination of candidate edges by specified percentage of total edges" << endl;
cout << " \t" << endl;
cout << " -O \toptimize reference tree and model parameters" << endl;
cout << " -l \tspecify minimum likelihood weight below which a placement is discarded" << endl;
cout << " \t DEFAULT: 0.01" << endl;
cout << " -L \tspecify accumulated likelihood weight after which further placements are discarded" << endl;
cout << " \t DEFAULT: OFF" << endl;
cout << " -m \tSpecify model of nucleotide substitution" << endl;
cout << " \tGTR \tGeneralized time reversible (DEFAULT)" << endl;
cout << " \tJC69\tJukes-Cantor Model" << endl;
cout << " \tK80 \tKimura 80 Model" << endl;
}
static void inv(string msg)
{
int mpi_rank = 0;
MPI_COMM_RANK(MPI_COMM_WORLD, &mpi_rank);
if (mpi_rank == 0)
{
if (msg.size())
cerr << msg << endl;
print_help();
cout.flush();
}
MPI_FINALIZE();
exit(EXIT_FAILURE);
}
static void ensure_dir_has_slash(string& dir)
{
if (dir.length() > 0 && dir.back() != '/')
dir += "/";
}
int main(int argc, char** argv)
{
MPI_INIT(&argc, &argv);
string invocation("");
string model_id("GTR");
Options options;
for (int i = 0; i < argc; ++i)
{
invocation += argv[i];
invocation += " ";
}
string query_file("");
string work_dir("");
string tree_file("");
string reference_file("");
string binary_file("");
int c;
while((c = getopt(argc, argv, "hOBb:t:s:q:l:L:w:g::G::r")) != EOF)
{
switch (c)
{
case 't':
tree_file += optarg;
break;
case 's':
reference_file += optarg;
break;
case 'q':
query_file += optarg;
break;
case 'w':
work_dir += optarg;
break;
case 'l':
options.support_threshold = stod(optarg);
if (options.support_threshold < 0.0)
inv("Support threshold cutoff too small! Range: [0,1)");
if (options.support_threshold >= 1.0)
inv("Support threshold cutoff too large! Range: [0,1)");
break;
case 'L':
options.support_threshold = stod(optarg);
if (options.support_threshold <= 0.0)
inv("Accumulated support threshold cutoff too small! Range: (0,1]");
if (options.support_threshold > 1.0)
inv("Accumulated support threshold cutoff too large! Range: (0,1]");
options.acc_threshold = true;
break;
case 'h':
inv("");
break;
case 'g':
if (options.prescoring)
inv("-g cannot be used simultaneously with -G!");
if (optarg)
options.prescoring_threshold = stod(optarg);
if (options.prescoring_threshold < 0.0)
inv("Prescoring threshold cutoff too small! Range: [0,1]");
if (options.prescoring_threshold > 1.0)
inv("Prescoring threshold cutoff too large! Range: [0,1]");
options.prescoring = true;
break;
case 'G':
if (options.prescoring)
inv("-g cannot be used simultaneously with -G!");
if (optarg)
options.prescoring_threshold = stod(optarg);
else
options.prescoring_threshold = 0.1;
if (options.prescoring_threshold < 0.0)
inv("Prescoring threshold cutoff too small! Range: [0,1]");
if (options.prescoring_threshold > 1.0)
inv("Prescoring threshold cutoff too large! Range: [0,1]");
options.prescoring = true;
options.prescoring_by_percentage = true;
break;
case 'O':
options.opt_branches = true;
options.opt_model = true;
break;
case 'r':
options.ranged = true;
break;
case 'B':
options.dump_binary_mode = true;
break;
case 'b':
options.load_binary_mode = true;
binary_file += optarg;
break;
case ':':
inv("Invalid option.");
break;
}
}
//================================================================
//============ EPA =========================================
//================================================================
ensure_dir_has_slash(work_dir);
MSA ref_msa;
if (reference_file.size())
ref_msa = build_MSA_from_file(reference_file);
Model model(model_id);
// build the Tree
Tree tree;
if (options.load_binary_mode)
{
cout << "Loading from binary" << endl;
tree = Tree(binary_file, options);
}
else
{
// build the full tree with all possible clv's
tree = Tree(tree_file, ref_msa, model, options);
}
// build the query stream
MSA_Stream queries;
if (not options.dump_binary_mode)
{
if (query_file.size() != 0)
{
queries = MSA_Stream(query_file);
}
// attempt to split msa if it is intermingled with (supposed) query sequences
else
{
throw runtime_error{"Combined MSA files not currently supported, please split them and specify using -s and -q."};
// split_combined_msa(ref_msa, queries, tree);
}
}
// dump to binary if specified
if (options.dump_binary_mode)
{
cout << "Writing to binary" << endl;
string dump_file(work_dir + "epa_binary_file");
dump_to_binary(tree, dump_file);
MPI_FINALIZE();
return EXIT_SUCCESS;
}
// start the placement process and write to file
auto start = chrono::high_resolution_clock::now();
process(tree, queries, work_dir, options, invocation);
// MSA full_msa = build_MSA_from_file(query_file);
// place(tree, full_msa);
auto end = chrono::high_resolution_clock::now();
auto runtime = chrono::duration_cast<chrono::seconds>(end - start).count();
cout << "\nTime spent placing: " << runtime << "s" << endl;
MPI_FINALIZE();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "SelectSpritesOP.h"
#include "FontBlankSprite.h"
#include "SymbolMgr.h"
#include "SpriteFactory.h"
#include "EditCMPT.h"
#include "MultiSpritesImpl.h"
#include "StageCanvas.h"
#include "SpriteSelection.h"
#include "EditPanelImpl.h"
#include "DrawSelectedSpriteVisitor.h"
#include "sprite_msg.h"
#include "panel_msg.h"
#include "FetchAllVisitor.h"
#include "PointMultiQueryVisitor.h"
#include "InsertSpriteAOP.h"
#include <sprite2/S2_RVG.h>
#include <wx/clipbrd.h>
#include <sstream>
namespace ee
{
SelectSpritesOP::SelectSpritesOP(wxWindow* wnd, EditPanelImpl* stage,
MultiSpritesImpl* sprites_impl,
EditCMPT* callback)
: DrawSelectRectOP(wnd, stage)
, m_callback(callback)
, m_spritesImpl(sprites_impl)
, m_draggable(true)
, m_rect_select(false)
{
m_left_first_pos.MakeInvalid();
m_selection = sprites_impl->GetSpriteSelection();
m_selection->AddReference();
}
SelectSpritesOP::~SelectSpritesOP()
{
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_selection->RemoveReference();
}
bool SelectSpritesOP::OnKeyDown(int keyCode)
{
if (DrawSelectRectOP::OnKeyDown(keyCode)) return true;
if (m_stage->GetKeyState(WXK_CONTROL) && m_stage->GetKeyState(WXK_CONTROL_X))
{
PasteToSelection();
m_spritesImpl->ClearSelectedSprite();
return true;
}
else if (m_stage->GetKeyState(WXK_CONTROL) && keyCode == 'C')
{
PasteToSelection();
return true;
}
else if (m_stage->GetKeyState(WXK_CONTROL) && keyCode == 'V')
{
CopyFromSelection();
return true;
}
else if (keyCode == WXK_SHIFT)
{
if (!m_rect_select) {
m_rect_select = true;
m_stage->SetCursor(wxCURSOR_RIGHT_ARROW);
}
}
return false;
}
bool SelectSpritesOP::OnKeyUp(int keyCode)
{
if (DrawSelectRectOP::OnKeyUp(keyCode)) return true;
switch (keyCode)
{
case WXK_SHIFT:
if (m_rect_select) {
m_rect_select = false;
m_stage->SetCursor(wxCURSOR_ARROW);
}
break;
}
return false;
}
bool SelectSpritesOP::OnMouseLeftDown(int x, int y)
{
m_draggable = true;
sm::vec2 pos = m_stage->TransPosScrToProj(x, y);
Sprite* selected = NULL;
if (!m_rect_select) {
selected = SelectByPos(pos);
}
if (selected)
{
assert(selected->IsEditable());
if (m_stage->GetKeyState(WXK_CONTROL))
{
if (m_selection->IsExist(selected)) {
m_selection->Remove(selected);
} else {
m_selection->Add(selected);
}
SelectSpriteSetSJ::Instance()->Select(m_selection, m_spritesImpl);
}
else
{
if (!m_selection->IsExist(selected) && !m_stage->GetKeyState(WXK_SPACE))
{
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_selection->Add(selected);
SelectSpriteSJ::Instance()->Select(selected, true);
}
}
m_left_first_pos.MakeInvalid();
if (m_callback)
m_callback->UpdateControlValue();
}
else
{
DrawSelectRectOP::OnMouseLeftDown(x, y);
if (m_stage->GetKeyState(WXK_SPACE)) {
m_left_first_pos.MakeInvalid();
} else {
m_left_first_pos = pos;
}
if (m_stage->GetKeyState(WXK_CONTROL)) {
m_draggable = false;
} else {
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
}
}
return false;
}
bool SelectSpritesOP::OnMouseLeftUp(int x, int y)
{
if (DrawSelectRectOP::OnMouseLeftUp(x, y)) return true;
m_draggable = true;
if (!m_left_first_pos.IsValid()) {
return false;
}
sm::vec2 end = m_stage->TransPosScrToProj(x, y);
sm::rect rect(m_left_first_pos, end);
std::vector<Sprite*> sprs;
m_spritesImpl->QuerySpritesByRect(rect, m_left_first_pos.x < end.x, sprs);
if (m_stage->GetKeyState(WXK_CONTROL))
{
for (size_t i = 0, n = sprs.size(); i < n; ++i)
{
Sprite* spr = sprs[i];
if (m_selection->IsExist(spr)) {
m_selection->Remove(sprs[i]);
} else {
m_selection->Add(sprs[i]);
}
}
}
else
{
for (size_t i = 0, n = sprs.size(); i < n; ++i) {
m_selection->Add(sprs[i]);
}
}
SelectSpriteSetSJ::Instance()->Select(m_selection, m_spritesImpl);
m_left_first_pos.MakeInvalid();
if (m_callback) {
m_callback->UpdateControlValue();
}
SetCanvasDirtySJ::Instance()->SetDirty();
return false;
}
bool SelectSpritesOP::OnMouseRightDown(int x, int y)
{
m_right_first_pos.Set(x, y);
SetRightPan(m_selection->IsEmpty());
if (DrawSelectRectOP::OnMouseRightDown(x, y)) return true;
return false;
}
bool SelectSpritesOP::OnMouseRightUp(int x, int y)
{
// select
if (m_right_first_pos == sm::vec2(x, y))
{
sm::vec2 pos = m_stage->TransPosScrToProj(x, y);
PointMultiQueryVisitor visitor(pos);
m_spritesImpl->TraverseSprites(visitor, DT_EDITABLE);
const std::vector<Sprite*>& sprs = visitor.GetResult();
SetRightPan(sprs.empty());
}
if (DrawSelectRectOP::OnMouseRightUp(x, y)) return true;
return false;
}
bool SelectSpritesOP::OnMouseDrag(int x, int y)
{
if (DrawSelectRectOP::OnMouseDrag(x, y)) return true;
return !m_draggable;
}
bool SelectSpritesOP::OnDraw() const
{
if (DrawSelectRectOP::OnDraw()) {
return true;
}
m_selection->Traverse(DrawSelectedSpriteVisitor(s2::Color(255, 0, 0)));
return false;
}
bool SelectSpritesOP::Clear()
{
if (DrawSelectRectOP::Clear()) return true;
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_left_first_pos.MakeInvalid();
return false;
}
Sprite* SelectSpritesOP::SelectByPos(const sm::vec2& pos) const
{
if (m_stage->GetKeyState(WXK_SPACE)) {
return NULL;
}
Sprite* selected = NULL;
std::vector<Sprite*> sprs;
m_spritesImpl->GetSpriteSelection()->Traverse(FetchAllVisitor<Sprite>(sprs));
for (int i = 0, n = sprs.size(); i < n; ++i)
{
Sprite* spr = sprs[i];
if (spr->IsEditable() && spr->GetBounding()->IsContain(pos)) {
selected = spr;
break;
}
}
if (!selected) {
Sprite* spr = m_spritesImpl->QuerySpriteByPos(pos);
if (spr) {
selected = spr;
}
}
return selected;
}
void SelectSpritesOP::PasteSprToClipboard(const Sprite* spr, Json::Value& value) const
{
value["filename"] = dynamic_cast<const ee::Symbol*>(spr->GetSymbol())->GetFilepath();
spr->Store(value);
}
void SelectSpritesOP::CopySprFromClipboard(Sprite* spr, const Json::Value& value) const
{
spr->Load(value);
}
void SelectSpritesOP::PasteToSelection() const
{
std::vector<Sprite*> sprs;
m_selection->Traverse(FetchAllVisitor<Sprite>(sprs));
Json::Value value;
for (int i = 0, n = sprs.size(); i < n; ++i)
{
Json::Value& sval = value["sprite"][i];
Sprite* s = sprs[i];
if (wxTheClipboard->Open()) {
PasteSprToClipboard(s, sval);
}
}
Json::StyledStreamWriter writer;
std::stringstream ss;
writer.write(ss, value);
wxTheClipboard->SetData(new wxTextDataObject(ss.str()));
wxTheClipboard->Close();
}
void SelectSpritesOP::CopyFromSelection()
{
if (!wxTheClipboard->Open()) {
return;
}
if (!wxTheClipboard->IsSupported( wxDF_TEXT )) {
wxTheClipboard->Close();
return;
}
wxTextDataObject data;
wxTheClipboard->GetData( data );
Json::Value value;
Json::Reader reader;
std::string test = data.GetText().ToStdString();
reader.parse(data.GetText().ToStdString(), value);
if (value.isNull()) {
wxTheClipboard->Close();
return;
}
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
Sprite* last_spr = NULL;
std::vector<Sprite*> sprs;
int i = 0;
Json::Value sval = value["sprite"][i++];
while (!sval.isNull()) {
std::string filepath = sval["filename"].asString();
// fixme
if (filepath != "group") {
Symbol* sym = SymbolMgr::Instance()->FetchSymbol(filepath);
// for snapshoot
sym->RefreshThumbnail(filepath);
Sprite* spr = SpriteFactory::Instance()->Create(sym);
sprs.push_back(spr);
sym->RemoveReference();
CopySprFromClipboard(spr, sval);
InsertSpriteSJ::Instance()->Insert(spr);
EditAddRecordSJ::Instance()->Add(new InsertSpriteAOP(spr));
cu::RefCountObjAssign(last_spr, spr);
}
sval = value["sprite"][i++];
}
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_selection->Add(sprs[i]);
}
bool add = m_stage->GetKeyState(WXK_CONTROL);
SelectSpriteSJ::Instance()->Select(last_spr, !add);
if (last_spr) {
last_spr->RemoveReference();
}
wxTheClipboard->Close();
}
}<commit_msg>[FIXED] paste invalid json str<commit_after>#include "SelectSpritesOP.h"
#include "FontBlankSprite.h"
#include "SymbolMgr.h"
#include "SpriteFactory.h"
#include "EditCMPT.h"
#include "MultiSpritesImpl.h"
#include "StageCanvas.h"
#include "SpriteSelection.h"
#include "EditPanelImpl.h"
#include "DrawSelectedSpriteVisitor.h"
#include "sprite_msg.h"
#include "panel_msg.h"
#include "FetchAllVisitor.h"
#include "PointMultiQueryVisitor.h"
#include "InsertSpriteAOP.h"
#include <sprite2/S2_RVG.h>
#include <wx/clipbrd.h>
#include <sstream>
namespace ee
{
SelectSpritesOP::SelectSpritesOP(wxWindow* wnd, EditPanelImpl* stage,
MultiSpritesImpl* sprites_impl,
EditCMPT* callback)
: DrawSelectRectOP(wnd, stage)
, m_callback(callback)
, m_spritesImpl(sprites_impl)
, m_draggable(true)
, m_rect_select(false)
{
m_left_first_pos.MakeInvalid();
m_selection = sprites_impl->GetSpriteSelection();
m_selection->AddReference();
}
SelectSpritesOP::~SelectSpritesOP()
{
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_selection->RemoveReference();
}
bool SelectSpritesOP::OnKeyDown(int keyCode)
{
if (DrawSelectRectOP::OnKeyDown(keyCode)) return true;
if (m_stage->GetKeyState(WXK_CONTROL) && m_stage->GetKeyState(WXK_CONTROL_X))
{
PasteToSelection();
m_spritesImpl->ClearSelectedSprite();
return true;
}
else if (m_stage->GetKeyState(WXK_CONTROL) && keyCode == 'C')
{
PasteToSelection();
return true;
}
else if (m_stage->GetKeyState(WXK_CONTROL) && keyCode == 'V')
{
CopyFromSelection();
return true;
}
else if (keyCode == WXK_SHIFT)
{
if (!m_rect_select) {
m_rect_select = true;
m_stage->SetCursor(wxCURSOR_RIGHT_ARROW);
}
}
return false;
}
bool SelectSpritesOP::OnKeyUp(int keyCode)
{
if (DrawSelectRectOP::OnKeyUp(keyCode)) return true;
switch (keyCode)
{
case WXK_SHIFT:
if (m_rect_select) {
m_rect_select = false;
m_stage->SetCursor(wxCURSOR_ARROW);
}
break;
}
return false;
}
bool SelectSpritesOP::OnMouseLeftDown(int x, int y)
{
m_draggable = true;
sm::vec2 pos = m_stage->TransPosScrToProj(x, y);
Sprite* selected = NULL;
if (!m_rect_select) {
selected = SelectByPos(pos);
}
if (selected)
{
assert(selected->IsEditable());
if (m_stage->GetKeyState(WXK_CONTROL))
{
if (m_selection->IsExist(selected)) {
m_selection->Remove(selected);
} else {
m_selection->Add(selected);
}
SelectSpriteSetSJ::Instance()->Select(m_selection, m_spritesImpl);
}
else
{
if (!m_selection->IsExist(selected) && !m_stage->GetKeyState(WXK_SPACE))
{
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_selection->Add(selected);
SelectSpriteSJ::Instance()->Select(selected, true);
}
}
m_left_first_pos.MakeInvalid();
if (m_callback)
m_callback->UpdateControlValue();
}
else
{
DrawSelectRectOP::OnMouseLeftDown(x, y);
if (m_stage->GetKeyState(WXK_SPACE)) {
m_left_first_pos.MakeInvalid();
} else {
m_left_first_pos = pos;
}
if (m_stage->GetKeyState(WXK_CONTROL)) {
m_draggable = false;
} else {
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
}
}
return false;
}
bool SelectSpritesOP::OnMouseLeftUp(int x, int y)
{
if (DrawSelectRectOP::OnMouseLeftUp(x, y)) return true;
m_draggable = true;
if (!m_left_first_pos.IsValid()) {
return false;
}
sm::vec2 end = m_stage->TransPosScrToProj(x, y);
sm::rect rect(m_left_first_pos, end);
std::vector<Sprite*> sprs;
m_spritesImpl->QuerySpritesByRect(rect, m_left_first_pos.x < end.x, sprs);
if (m_stage->GetKeyState(WXK_CONTROL))
{
for (size_t i = 0, n = sprs.size(); i < n; ++i)
{
Sprite* spr = sprs[i];
if (m_selection->IsExist(spr)) {
m_selection->Remove(sprs[i]);
} else {
m_selection->Add(sprs[i]);
}
}
}
else
{
for (size_t i = 0, n = sprs.size(); i < n; ++i) {
m_selection->Add(sprs[i]);
}
}
SelectSpriteSetSJ::Instance()->Select(m_selection, m_spritesImpl);
m_left_first_pos.MakeInvalid();
if (m_callback) {
m_callback->UpdateControlValue();
}
SetCanvasDirtySJ::Instance()->SetDirty();
return false;
}
bool SelectSpritesOP::OnMouseRightDown(int x, int y)
{
m_right_first_pos.Set(x, y);
SetRightPan(m_selection->IsEmpty());
if (DrawSelectRectOP::OnMouseRightDown(x, y)) return true;
return false;
}
bool SelectSpritesOP::OnMouseRightUp(int x, int y)
{
// select
if (m_right_first_pos == sm::vec2(x, y))
{
sm::vec2 pos = m_stage->TransPosScrToProj(x, y);
PointMultiQueryVisitor visitor(pos);
m_spritesImpl->TraverseSprites(visitor, DT_EDITABLE);
const std::vector<Sprite*>& sprs = visitor.GetResult();
SetRightPan(sprs.empty());
}
if (DrawSelectRectOP::OnMouseRightUp(x, y)) return true;
return false;
}
bool SelectSpritesOP::OnMouseDrag(int x, int y)
{
if (DrawSelectRectOP::OnMouseDrag(x, y)) return true;
return !m_draggable;
}
bool SelectSpritesOP::OnDraw() const
{
if (DrawSelectRectOP::OnDraw()) {
return true;
}
m_selection->Traverse(DrawSelectedSpriteVisitor(s2::Color(255, 0, 0)));
return false;
}
bool SelectSpritesOP::Clear()
{
if (DrawSelectRectOP::Clear()) return true;
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
m_left_first_pos.MakeInvalid();
return false;
}
Sprite* SelectSpritesOP::SelectByPos(const sm::vec2& pos) const
{
if (m_stage->GetKeyState(WXK_SPACE)) {
return NULL;
}
Sprite* selected = NULL;
std::vector<Sprite*> sprs;
m_spritesImpl->GetSpriteSelection()->Traverse(FetchAllVisitor<Sprite>(sprs));
for (int i = 0, n = sprs.size(); i < n; ++i)
{
Sprite* spr = sprs[i];
if (spr->IsEditable() && spr->GetBounding()->IsContain(pos)) {
selected = spr;
break;
}
}
if (!selected) {
Sprite* spr = m_spritesImpl->QuerySpriteByPos(pos);
if (spr) {
selected = spr;
}
}
return selected;
}
void SelectSpritesOP::PasteSprToClipboard(const Sprite* spr, Json::Value& value) const
{
value["filename"] = dynamic_cast<const ee::Symbol*>(spr->GetSymbol())->GetFilepath();
spr->Store(value);
}
void SelectSpritesOP::CopySprFromClipboard(Sprite* spr, const Json::Value& value) const
{
spr->Load(value);
}
void SelectSpritesOP::PasteToSelection() const
{
std::vector<Sprite*> sprs;
m_selection->Traverse(FetchAllVisitor<Sprite>(sprs));
Json::Value value;
for (int i = 0, n = sprs.size(); i < n; ++i)
{
Json::Value& sval = value["sprite"][i];
Sprite* s = sprs[i];
if (wxTheClipboard->Open()) {
PasteSprToClipboard(s, sval);
}
}
Json::StyledStreamWriter writer;
std::stringstream ss;
writer.write(ss, value);
wxTheClipboard->SetData(new wxTextDataObject(ss.str()));
wxTheClipboard->Close();
}
void SelectSpritesOP::CopyFromSelection()
{
if (!wxTheClipboard->Open()) {
return;
}
if (!wxTheClipboard->IsSupported( wxDF_TEXT )) {
wxTheClipboard->Close();
return;
}
wxTextDataObject data;
wxTheClipboard->GetData( data );
std::string str = data.GetText().ToStdString();
if (str.find("{") == std::string::npos) {
wxTheClipboard->Close();
return;
}
Json::Value value;
Json::Reader reader;
std::string test = data.GetText().ToStdString();
bool succ = reader.parse(str, value);
if (!succ || value["sprite"].isNull()) {
wxTheClipboard->Close();
return;
}
m_selection->Clear();
ClearSpriteSelectionSJ::Instance()->Clear();
Sprite* last_spr = NULL;
std::vector<Sprite*> sprs;
int i = 0;
Json::Value sval = value["sprite"][i++];
while (!sval.isNull()) {
std::string filepath = sval["filename"].asString();
// fixme
if (filepath != "group") {
Symbol* sym = SymbolMgr::Instance()->FetchSymbol(filepath);
// for snapshoot
sym->RefreshThumbnail(filepath);
Sprite* spr = SpriteFactory::Instance()->Create(sym);
sprs.push_back(spr);
sym->RemoveReference();
CopySprFromClipboard(spr, sval);
InsertSpriteSJ::Instance()->Insert(spr);
EditAddRecordSJ::Instance()->Add(new InsertSpriteAOP(spr));
cu::RefCountObjAssign(last_spr, spr);
}
sval = value["sprite"][i++];
}
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_selection->Add(sprs[i]);
}
bool add = m_stage->GetKeyState(WXK_CONTROL);
SelectSpriteSJ::Instance()->Select(last_spr, !add);
if (last_spr) {
last_spr->RemoveReference();
}
wxTheClipboard->Close();
}
}<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "InputValidator.h"
#include "MetaLexer.h"
#include <algorithm>
namespace cling {
bool InputValidator::inBlockComment() const {
return std::find(m_ParenStack.begin(), m_ParenStack.end(), tok::slash)
!= m_ParenStack.end();
}
static int findNestedBlockComments(const char* startPos, const char* endPos) {
// While probably not standard compliant, it should work fine for the indent
// Let the real parser error if the balancing is incorrect
// search forward for //, then backward for block comments
// */ last, comment has ended, doesn't matter how many /* before
// /* last, comment has begun, doesn't matter if priors ended or not
char commentTok = 0;
while (startPos < endPos) {
if (*startPos == '/') {
if (++commentTok == 2) {
while (endPos > startPos) {
switch (*endPos) {
case '*':
if (commentTok == '*')
return -1;
else
commentTok = '/';
break;
case '/':
if (commentTok == '/')
return 1;
else
commentTok = '*';
break;
default:
commentTok = 0;
break;
}
--endPos;
}
return 0;
}
} else if (commentTok)
commentTok = 0; // need a new start to double slash
++startPos;
}
return 0;
}
static void unwindTokens(std::deque<int>& queue, int tok) {
assert(!queue.empty() && "Token stack is empty!");
while (queue.back() != tok) {
queue.pop_back();
assert(!queue.empty() && "Token stack is empty!");
}
queue.pop_back();
}
InputValidator::ValidationResult
InputValidator::validate(llvm::StringRef line) {
ValidationResult Res = kComplete;
Token Tok;
const char* curPos = line.data();
bool multilineComment = inBlockComment();
int commentTok = multilineComment ? tok::asterik : tok::slash;
if (!multilineComment && m_ParenStack.empty()) {
// Only check for 'template' if we're not already indented
MetaLexer Lex(curPos, true);
Lex.Lex(Tok);
curPos = Lex.getLocation();
if (Tok.is(tok::ident)) {
if (Tok.getIdent()=="template")
m_ParenStack.push_back(tok::greater);
} else
curPos -= Tok.getLength(); // Rewind buffer for LexPunctuatorAndAdvance
}
do {
const char* prevStart = curPos;
MetaLexer::LexPunctuatorAndAdvance(curPos, Tok);
const int kind = (int)Tok.getKind();
if (kind == commentTok) {
if (kind == tok::slash) {
if (multilineComment) {
// exiting a comment, unwind the stack
multilineComment = false;
commentTok = tok::slash;
unwindTokens(m_ParenStack, tok::slash);
}
// If we have a closing comment without a start it will be transformed
// to */; and clang reports an error for both the */ and the ;
// If we return kIncomplete, then just one error is printed, but too
// late: after the user has another expression which will always fail.
// So just deal with two errors for now
// else if (prevKind == tok::asterik) {
// Res = kIncomplete;
// break;
// }
else // wait for an asterik
commentTok = tok::asterik;
}
else {
assert(commentTok == tok::asterik && "Comment token not / or *");
if (!multilineComment) {
// entering a new comment
multilineComment = true;
m_ParenStack.push_back(tok::slash);
}
else // wait for closing / (must be next token)
commentTok = tok::slash;
}
}
else {
// If we're in a multiline, and waiting for the closing slash
// we gonna have to wait for another asterik first
if (multilineComment) {
if (kind == tok::eof) {
switch (findNestedBlockComments(prevStart, curPos)) {
case -1: unwindTokens(m_ParenStack, tok::slash);
case 1:
case 0: break;
default: assert(0 && "Nested block comment count"); break;
}
// eof, were done anyway
break;
}
else if (commentTok == tok::slash) {
// Cancel the wait for a slash, but only if current token isn't
// also an asterik.
if (kind != tok::asterik)
commentTok = tok::asterik;
}
}
if (kind >= (int)tok::l_square && kind <= (int)tok::r_brace) {
// The closing paren kind is open paren kind + 1 (i.e odd number)
if (kind % 2) {
int prev = m_ParenStack.empty() ? -1: m_ParenStack.back();
// closing the right one?
if (prev != kind - 1) {
if (multilineComment)
continue;
Res = kMismatch;
break;
}
m_ParenStack.pop_back();
// Right brace will pop a template if their is one
if (kind == tok::r_brace && m_ParenStack.size() == 1 ) {
if (m_ParenStack.back() == tok::greater)
m_ParenStack.pop_back();
}
}
else
m_ParenStack.push_back(kind);
}
else if (kind == tok::hash) {
MetaLexer Lex(curPos);
Lex.SkipWhitespace();
Lex.LexAnyString(Tok);
const llvm::StringRef PPtk = Tok.getIdent();
if (PPtk.startswith("endif")
&& (PPtk.size() > 5 ? PPtk[5]=='/' || isspace(PPtk[5]) : true)) {
if (m_ParenStack.empty() || m_ParenStack.back() != tok::hash) {
Res = kMismatch;
break;
}
m_ParenStack.pop_back();
}
else if (PPtk.startswith("if")) {
m_ParenStack.push_back(tok::hash);
}
}
else if (kind == tok::semicolon) {
// Template forward declatation
if (m_ParenStack.size() == 1 && m_ParenStack.back()==tok::greater)
m_ParenStack.pop_back();
}
else if (kind >= (int)tok::stringlit && kind <= (int)tok::charlit) {
MetaLexer::LexQuotedStringAndAdvance(curPos, Tok);
}
}
} while (Tok.isNot(tok::eof));
if (!m_ParenStack.empty() && Res != kMismatch)
Res = kIncomplete;
if (!m_Input.empty()) {
if (!m_ParenStack.empty() && (m_ParenStack.back() == tok::stringlit
|| m_ParenStack.back() == tok::charlit))
m_Input.append("\\n");
else
m_Input.append("\n");
}
else
m_Input = "";
m_Input.append(line);
return Res;
}
void InputValidator::reset(std::string* input) {
if (input) {
assert(input->empty() && "InputValidator::reset got non empty argument");
input->swap(m_Input);
} else
std::string().swap(m_Input);
std::deque<int>().swap(m_ParenStack);
}
} // end namespace cling
<commit_msg>Do not wait for a "*" if there is any other token after the "/" (ROOT-8529).<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "InputValidator.h"
#include "MetaLexer.h"
#include <algorithm>
namespace cling {
bool InputValidator::inBlockComment() const {
return std::find(m_ParenStack.begin(), m_ParenStack.end(), tok::slash)
!= m_ParenStack.end();
}
static int findNestedBlockComments(const char* startPos, const char* endPos) {
// While probably not standard compliant, it should work fine for the indent
// Let the real parser error if the balancing is incorrect
// search forward for //, then backward for block comments
// */ last, comment has ended, doesn't matter how many /* before
// /* last, comment has begun, doesn't matter if priors ended or not
char commentTok = 0;
while (startPos < endPos) {
if (*startPos == '/') {
if (++commentTok == 2) {
while (endPos > startPos) {
switch (*endPos) {
case '*':
if (commentTok == '*')
return -1;
else
commentTok = '/';
break;
case '/':
if (commentTok == '/')
return 1;
else
commentTok = '*';
break;
default:
commentTok = 0;
break;
}
--endPos;
}
return 0;
}
} else if (commentTok)
commentTok = 0; // need a new start to double slash
++startPos;
}
return 0;
}
static void unwindTokens(std::deque<int>& queue, int tok) {
assert(!queue.empty() && "Token stack is empty!");
while (queue.back() != tok) {
queue.pop_back();
assert(!queue.empty() && "Token stack is empty!");
}
queue.pop_back();
}
InputValidator::ValidationResult
InputValidator::validate(llvm::StringRef line) {
ValidationResult Res = kComplete;
Token Tok;
const char* curPos = line.data();
bool multilineComment = inBlockComment();
int commentTok = multilineComment ? tok::asterik : tok::slash;
if (!multilineComment && m_ParenStack.empty()) {
// Only check for 'template' if we're not already indented
MetaLexer Lex(curPos, true);
Lex.Lex(Tok);
curPos = Lex.getLocation();
if (Tok.is(tok::ident)) {
if (Tok.getIdent()=="template")
m_ParenStack.push_back(tok::greater);
} else
curPos -= Tok.getLength(); // Rewind buffer for LexPunctuatorAndAdvance
}
do {
const char* prevStart = curPos;
if (!MetaLexer::LexPunctuatorAndAdvance(curPos, Tok)) {
// there were tokens between the previous and this Tok.
commentTok = tok::slash;
}
const int kind = (int)Tok.getKind();
if (kind == commentTok) {
if (kind == tok::slash) {
if (multilineComment) {
// exiting a comment, unwind the stack
multilineComment = false;
commentTok = tok::slash;
unwindTokens(m_ParenStack, tok::slash);
}
// If we have a closing comment without a start it will be transformed
// to */; and clang reports an error for both the */ and the ;
// If we return kIncomplete, then just one error is printed, but too
// late: after the user has another expression which will always fail.
// So just deal with two errors for now
// else if (prevKind == tok::asterik) {
// Res = kIncomplete;
// break;
// }
else // wait for an asterik
commentTok = tok::asterik;
}
else {
assert(commentTok == tok::asterik && "Comment token not / or *");
if (!multilineComment) {
// entering a new comment
multilineComment = true;
m_ParenStack.push_back(tok::slash);
}
else // wait for closing / (must be next token)
commentTok = tok::slash;
}
}
else {
// If we're in a multiline, and waiting for the closing slash
// we gonna have to wait for another asterik first
if (multilineComment) {
if (kind == tok::eof) {
switch (findNestedBlockComments(prevStart, curPos)) {
case -1: unwindTokens(m_ParenStack, tok::slash);
case 1:
case 0: break;
default: assert(0 && "Nested block comment count"); break;
}
// eof, were done anyway
break;
}
else if (commentTok == tok::slash) {
// Cancel the wait for a slash, but only if current token isn't
// also an asterik.
if (kind != tok::asterik)
commentTok = tok::asterik;
}
}
if (kind >= (int)tok::l_square && kind <= (int)tok::r_brace) {
// The closing paren kind is open paren kind + 1 (i.e odd number)
if (kind % 2) {
int prev = m_ParenStack.empty() ? -1: m_ParenStack.back();
// closing the right one?
if (prev != kind - 1) {
if (multilineComment)
continue;
Res = kMismatch;
break;
}
m_ParenStack.pop_back();
// Right brace will pop a template if their is one
if (kind == tok::r_brace && m_ParenStack.size() == 1 ) {
if (m_ParenStack.back() == tok::greater)
m_ParenStack.pop_back();
}
}
else
m_ParenStack.push_back(kind);
}
else if (kind == tok::hash) {
MetaLexer Lex(curPos);
Lex.SkipWhitespace();
Lex.LexAnyString(Tok);
const llvm::StringRef PPtk = Tok.getIdent();
if (PPtk.startswith("endif")
&& (PPtk.size() > 5 ? PPtk[5]=='/' || isspace(PPtk[5]) : true)) {
if (m_ParenStack.empty() || m_ParenStack.back() != tok::hash) {
Res = kMismatch;
break;
}
m_ParenStack.pop_back();
}
else if (PPtk.startswith("if")) {
m_ParenStack.push_back(tok::hash);
}
}
else if (kind == tok::semicolon) {
// Template forward declatation
if (m_ParenStack.size() == 1 && m_ParenStack.back()==tok::greater)
m_ParenStack.pop_back();
}
else if (kind >= (int)tok::stringlit && kind <= (int)tok::charlit) {
MetaLexer::LexQuotedStringAndAdvance(curPos, Tok);
}
}
} while (Tok.isNot(tok::eof));
if (!m_ParenStack.empty() && Res != kMismatch)
Res = kIncomplete;
if (!m_Input.empty()) {
if (!m_ParenStack.empty() && (m_ParenStack.back() == tok::stringlit
|| m_ParenStack.back() == tok::charlit))
m_Input.append("\\n");
else
m_Input.append("\n");
}
else
m_Input = "";
m_Input.append(line);
return Res;
}
void InputValidator::reset(std::string* input) {
if (input) {
assert(input->empty() && "InputValidator::reset got non empty argument");
input->swap(m_Input);
} else
std::string().swap(m_Input);
std::deque<int>().swap(m_ParenStack);
}
} // end namespace cling
<|endoftext|> |
<commit_before>#ifndef SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_
#define SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_
#include <functional>
#include <core/detail/connection.hpp>
#include <core/ports.hpp>
namespace fc
{
namespace detail
{
//policy classes for determining argument order in connect calls in the proxy
struct active_sink_first
{
template<class sink_t, class source_t>
struct source
{
typedef source_t type;
};
template<class sink_t, class source_t>
struct sink
{
typedef sink_t type;
typedef void result_t;
};
template<class sink_t, class source_t>
auto operator()(sink_t&& sink, source_t&& source)
{
return ::fc::connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
struct active_source_first
{
template<class source_t, class sink_t>
struct source
{
typedef source_t type;
};
template<class source_t, class sink_t>
struct sink
{
typedef sink_t type;
typedef result_of_t<source_t> result_t;
};
template<class source_t, class sink_t>
auto operator()(source_t&& source, sink_t&& sink)
{
return ::fc::connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
/**
* \brief contains connections of active_connectables during creation.
*
* active_connection_proxy is used to store the intermediate objects created,
* when a connection is build up from an active connectable
* Until the active connectable is connected to a proper passive,
* the connection is not complete and no value can be pulled or send through.
* Nonetheless, the connection needs to be stored to allow further connections.
* the active_connection_proxy stores these temporary objects.
*
* \tparam active_ is the active connection,
* \tparam passive_t the passive side of the connection durint buildup
* \tparam
* {
* connect_policy a policy class which makes sure parameters to connect
* inside the proxy are in the correct order.
* }
* */
template<class active_t, class passive_t, class connect_policy>
struct active_connection_proxy
{
static_assert(is_active<std::decay_t<active_t>>{},
"active_t in proxy needs to be active connectable");
typedef typename
connect_policy::template sink<active_t, passive_t>::result_t result_t;
active_connection_proxy(active_t active_, passive_t passive) :
active(std::forward<active_t>(active_)),
stored_passive(std::forward<passive_t>(passive))
{}
/**
* \brief connects a passive connectable to the active_connection_proxy.
*
* connects the new_source to the current stored source
* then connects this connection to the sink which completes the connection
*
* \pre new_passive_t needs to be passive connectable.
* \post new_passive is now connected to active via the connection stored in the proxy.
* \returns port connection tag object.
*/
template<class new_passive_t, class enable = void>
auto connect(new_passive_t&& new_passive,
std::enable_if_t<(is_passive_source<std::decay_t<new_passive_t>>{} or
is_passive_sink<std::decay_t<new_passive_t>>{})>* = nullptr)
{
static_assert(is_passive<std::decay_t<new_passive_t>>{},
"new_passive_t in proxy needs to be passive connectable");
auto tmp = connect_policy()(std::forward<passive_t>(stored_passive),
std::forward<new_passive_t>(new_passive));
return std::forward<active_t>(active).connect(std::move(tmp));
}
/**
* \brief connects a connectable, which is not a passive connectable to the
* active_connection_proxy.
*
* connects the new_connectable to the current stored source
*
* \pre new_connectable_t needs to be connectable
* \post new_connectable_t is connected to the old passive.
* \returns a active_connection_proxy, which contains the new_connectable in its connection.
*/
template <class new_connectable_t,
class = std::enable_if_t<not(is_passive_source<std::decay_t<new_connectable_t>>{} or
is_passive_sink<std::decay_t<new_connectable_t>>{})>>
auto connect(new_connectable_t&& new_connectable)
{
auto connection = connect_policy()(std::forward<passive_t>(stored_passive),
std::forward<new_connectable_t>(new_connectable));
return active_connection_proxy<
active_t,
decltype(connection),
connect_policy>(active, std::move(connection));
}
active_t active;
passive_t stored_passive;
};
template<class active_t, class passive_t, class argument_order, class Enable = void>
struct active_passive_connect_impl;
/// Specialization of connect to call member connect of stream_proxy.
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t<is_instantiation_of<active_connection_proxy, std::decay_t<active_t>>{}>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
return std::forward<active_t>(active).connect(std::forward<passive_t>(passive));
}
};
/**
* Specialization of active_passive_connect_impl for the case of connecting a standard connectable
* which is not a is_passive_sink to a is_passive_source.
* \return a stream_proxy which contains the active && the passive.
*/
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t
< !is_instantiation_of< active_connection_proxy,std::decay_t<active_t>>{}
&& ( ( is_active_source<std::decay_t<active_t>>{}
&& !fc::is_passive_sink<std::decay_t<passive_t>>{}
)
|| ( fc::is_active_sink<std::decay_t<active_t>>{}
&& !fc::is_passive_source<std::decay_t<passive_t>>{}
)
)>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
return active_connection_proxy<active_t, passive_t, argument_order>
(std::forward<active_t>(active), std::forward<passive_t>(passive));
}
};
/**
* Specialization for the case of connecting a active_port to a passive_port.
* \pre active_t needs to be a active_connectable.
* \pre passive_t needs to be a passive_connectable.
* \post active is now connected to passive
* \return port_connection tag object with the type information of the connection.
*/
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t
< !is_instantiation_of< active_connection_proxy, std::decay_t<active_t>>{}
&& ( ( is_active_source<std::decay_t<active_t>>{}
&& fc::is_passive_sink<std::decay_t<passive_t>>{}
)
|| ( fc::is_active_sink<std::decay_t<active_t>>{}
&& fc::is_passive_source<std::decay_t<passive_t>>{}
)
)>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
std::forward<active_t>(active).connect(std::forward<passive_t>(passive));
using source_t = typename argument_order::template source<active_t, passive_t>::type;
using sink_t = typename argument_order::template sink<active_t, passive_t>::type;
return port_connection<source_t, sink_t, result_of_t<active_t>>();
}
};
template<class source_t, class sink_t>
struct connect_impl
< source_t,
sink_t,
std::enable_if_t<fc::is_active<std::decay_t<source_t>>{}>
>
{
auto operator()(source_t&& source, sink_t&& sink)
{
// source is active, thus it is the first parameter
return active_passive_connect_impl<source_t, sink_t, active_source_first>()
(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
template<class source_t, class sink_t>
struct connect_impl
< source_t,
sink_t,
std::enable_if_t<fc::is_active<std::decay_t<sink_t>>{}>
>
{
auto operator()(source_t&& source, sink_t&& sink)
{
// sink is active, thus it is the first parameter
return active_passive_connect_impl<sink_t, source_t, active_sink_first>()
(std::forward<sink_t>(sink), std::forward<source_t>(source));
}
};
} //namespace detail
template<class T, class U> struct is_active_sink<
detail::active_connection_proxy<T, U, detail::active_sink_first>>
: std::true_type {};
template<class T, class U> struct is_active_source<
detail::active_connection_proxy<T, U, detail::active_source_first>>
: std::true_type {};
} //namespace fc
#endif /* SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_ */
<commit_msg>core: disallow abusing active_connection_proxy.<commit_after>#ifndef SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_
#define SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_
#include <functional>
#include <core/detail/connection.hpp>
#include <core/ports.hpp>
namespace fc
{
namespace detail
{
//policy classes for determining argument order in connect calls in the proxy
struct active_sink_first
{
template<class sink_t, class source_t>
struct source
{
typedef source_t type;
};
template<class sink_t, class source_t>
struct sink
{
typedef sink_t type;
typedef void result_t;
};
template<class sink_t, class source_t>
auto operator()(sink_t&& sink, source_t&& source)
{
return ::fc::connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
struct active_source_first
{
template<class source_t, class sink_t>
struct source
{
typedef source_t type;
};
template<class source_t, class sink_t>
struct sink
{
typedef sink_t type;
typedef result_of_t<source_t> result_t;
};
template<class source_t, class sink_t>
auto operator()(source_t&& source, sink_t&& sink)
{
return ::fc::connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
template <class T>
struct always_false : std::false_type
{
};
/**
* \brief contains connections of active_connectables during creation.
*
* active_connection_proxy is used to store the intermediate objects created,
* when a connection is build up from an active connectable
* Until the active connectable is connected to a proper passive,
* the connection is not complete and no value can be pulled or send through.
* Nonetheless, the connection needs to be stored to allow further connections.
* the active_connection_proxy stores these temporary objects.
*
* \tparam active_ is the active connection,
* \tparam passive_t the passive side of the connection durint buildup
* \tparam
* {
* connect_policy a policy class which makes sure parameters to connect
* inside the proxy are in the correct order.
* }
* */
template<class active_t, class passive_t, class connect_policy>
struct active_connection_proxy
{
static_assert(is_active<std::decay_t<active_t>>{},
"active_t in proxy needs to be active connectable");
typedef typename
connect_policy::template sink<active_t, passive_t>::result_t result_t;
active_connection_proxy(active_t active_, passive_t passive) :
active(std::forward<active_t>(active_)),
stored_passive(std::forward<passive_t>(passive))
{}
/**
* \brief connects a passive connectable to the active_connection_proxy.
*
* connects the new_source to the current stored source
* then connects this connection to the sink which completes the connection
*
* \pre new_passive_t needs to be passive connectable.
* \post new_passive is now connected to active via the connection stored in the proxy.
* \returns port connection tag object.
*/
template<class new_passive_t, class enable = void>
auto connect(new_passive_t&& new_passive,
std::enable_if_t<(is_passive_source<std::decay_t<new_passive_t>>{} or
is_passive_sink<std::decay_t<new_passive_t>>{})>* = nullptr) &&
{
static_assert(is_passive<std::decay_t<new_passive_t>>{},
"new_passive_t in proxy needs to be passive connectable");
auto tmp = connect_policy()(std::forward<passive_t>(stored_passive),
std::forward<new_passive_t>(new_passive));
return std::forward<active_t>(active).connect(std::move(tmp));
}
/**
* \brief connects a connectable, which is not a passive connectable to the
* active_connection_proxy.
*
* connects the new_connectable to the current stored source
*
* \pre new_connectable_t needs to be connectable
* \post new_connectable_t is connected to the old passive.
* \returns a active_connection_proxy, which contains the new_connectable in its connection.
*/
template <class new_connectable_t,
class = std::enable_if_t<not(is_passive_source<std::decay_t<new_connectable_t>>{} or
is_passive_sink<std::decay_t<new_connectable_t>>{})>>
auto connect(new_connectable_t&& new_connectable) &&
{
auto connection = connect_policy()(std::forward<passive_t>(stored_passive),
std::forward<new_connectable_t>(new_connectable));
return active_connection_proxy<
active_t,
decltype(connection),
connect_policy>(active, std::move(connection));
}
/**
* \brief catch function to prevent active_connection_proxies from being treated as lvalues.
*/
template <class new_connectable_t>
void connect(new_connectable_t&&) &
{
static_assert(always_false<new_connectable_t>{}, "active_connection_proxies cannot be used multiple times.");
}
active_t active;
passive_t stored_passive;
};
template<class active_t, class passive_t, class argument_order, class Enable = void>
struct active_passive_connect_impl;
/// Specialization of connect to call member connect of stream_proxy.
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t<is_instantiation_of<active_connection_proxy, std::decay_t<active_t>>{}>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
return std::forward<active_t>(active).connect(std::forward<passive_t>(passive));
}
};
/**
* Specialization of active_passive_connect_impl for the case of connecting a standard connectable
* which is not a is_passive_sink to a is_passive_source.
* \return a stream_proxy which contains the active && the passive.
*/
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t
< !is_instantiation_of< active_connection_proxy,std::decay_t<active_t>>{}
&& ( ( is_active_source<std::decay_t<active_t>>{}
&& !fc::is_passive_sink<std::decay_t<passive_t>>{}
)
|| ( fc::is_active_sink<std::decay_t<active_t>>{}
&& !fc::is_passive_source<std::decay_t<passive_t>>{}
)
)>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
return active_connection_proxy<active_t, passive_t, argument_order>
(std::forward<active_t>(active), std::forward<passive_t>(passive));
}
};
/**
* Specialization for the case of connecting a active_port to a passive_port.
* \pre active_t needs to be a active_connectable.
* \pre passive_t needs to be a passive_connectable.
* \post active is now connected to passive
* \return port_connection tag object with the type information of the connection.
*/
template<class active_t, class passive_t, class argument_order>
struct active_passive_connect_impl
< active_t,
passive_t,
argument_order,
std::enable_if_t
< !is_instantiation_of< active_connection_proxy, std::decay_t<active_t>>{}
&& ( ( is_active_source<std::decay_t<active_t>>{}
&& fc::is_passive_sink<std::decay_t<passive_t>>{}
)
|| ( fc::is_active_sink<std::decay_t<active_t>>{}
&& fc::is_passive_source<std::decay_t<passive_t>>{}
)
)>
>
{
auto operator()(active_t&& active, passive_t&& passive)
{
std::forward<active_t>(active).connect(std::forward<passive_t>(passive));
using source_t = typename argument_order::template source<active_t, passive_t>::type;
using sink_t = typename argument_order::template sink<active_t, passive_t>::type;
return port_connection<source_t, sink_t, result_of_t<active_t>>();
}
};
template<class source_t, class sink_t>
struct connect_impl
< source_t,
sink_t,
std::enable_if_t<fc::is_active<std::decay_t<source_t>>{}>
>
{
auto operator()(source_t&& source, sink_t&& sink)
{
// source is active, thus it is the first parameter
return active_passive_connect_impl<source_t, sink_t, active_source_first>()
(std::forward<source_t>(source), std::forward<sink_t>(sink));
}
};
template<class source_t, class sink_t>
struct connect_impl
< source_t,
sink_t,
std::enable_if_t<fc::is_active<std::decay_t<sink_t>>{}>
>
{
auto operator()(source_t&& source, sink_t&& sink)
{
// sink is active, thus it is the first parameter
return active_passive_connect_impl<sink_t, source_t, active_sink_first>()
(std::forward<sink_t>(sink), std::forward<source_t>(source));
}
};
} //namespace detail
template<class T, class U> struct is_active_sink<
detail::active_connection_proxy<T, U, detail::active_sink_first>>
: std::true_type {};
template<class T, class U> struct is_active_source<
detail::active_connection_proxy<T, U, detail::active_source_first>>
: std::true_type {};
} //namespace fc
#endif /* SRC_PORTS_DETAIL_ACTIVE_SOURCE_PROXY_HPP_ */
<|endoftext|> |
<commit_before>/**
* @file
* Zenderer/Math/Matrix.hpp - A 4x4 matrix class wrapper for handling
* various graphical math operations.
*
* @author George Kudrayvtsev (halcyon)
* @version 1.0
* @copyright Apache License v2.0
* Licensed under the Apache License, Version 2.0 (the "License"). \n
* You may not use this file except in compliance with the License. \n
* You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0 \n
* Unless required by applicable law or agreed to in writing, software \n
* distributed under the License is distributed on an "AS IS" BASIS, \n
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
* See the License for the specific language governing permissions and \n
* limitations under the License.
*
* @addtogroup Math
* @{
**/
#ifndef ZENDERER__MATH__MATRIX_HPP
#define ZENDERER__MATH__MATRIX_HPP
#include "Vector.hpp"
namespace zen
{
namespace math
{
/**
* 4x4 matrix representation.
* This is in place to support various linear transformation
* operations required for moving vertices around in OpenGL
* terms. Currently, there is only support for creating projection
* matrices for the rendering window / shaders to use.
**/
class ZEN_API matrix4x4_t
{
public:
matrix4x4_t();
matrix4x4_t(const real_t values[4][4]);
matrix4x4_t(const real_t** ppvalues);
matrix4x4_t(const matrix4x4_t& Copy);
matrix4x4_t& operator=(const matrix4x4_t& Copy);
/**
* Provides the matrix's elements at that row.
* See the following examples:
*
* matrix[0][3] // 3rd element of row 0 (r0, c3)
* matrix[3][1] // 1st element of row 3 (r3, c1)
* matrix[2][1] // 1st element of row 2 (r2, c1)
*
* The index value is automatically clamped at [0, 3].
*
* @param index Row index to access
* @return The `real_t` array at that index.
**/
real_t* operator[](uint8_t index);
matrix4x4_t operator*(matrix4x4_t& Other) const;
inline const real_t* GetPointer() const
{ return reinterpret_cast<const real_t*>(m_values); }
/**
* Creates a 2D projection matrix.
*
* @param width Projection width
* @param height Projection height
* @param max_z Maximum projection depth
* @param min_z Minimum projection depth
*
* @return The requested projection matrix.
**/
static inline matrix4x4_t Projection2D(
const uint16_t width, const uint16_t height,
const uint16_t max_z, const int min_z)
{
matrix4x4_t result;
result[0][0] = 2.0f / width;
result[0][3] = -1.0f;
result[1][1] = -2.0f / height;
result[1][3] = 1.0f;
result[2][2] = -2.0f / (min_z - max_z);
result[3][3] = 1.0f;
return result;
}
static matrix4x4_t CreateIdentityMatrix();
static const matrix4x4_t& GetIdentityMatrix();
private:
real_t m_values[4][4];
};
} // namespace math
} // namespace zen
#endif // ZENDERER__MATH__MATRIX_HPP
/** @} **/
<commit_msg>Matrix translation<commit_after>/**
* @file
* Zenderer/Math/Matrix.hpp - A 4x4 matrix class wrapper for handling
* various graphical math operations.
*
* @author George Kudrayvtsev (halcyon)
* @version 1.0
* @copyright Apache License v2.0
* Licensed under the Apache License, Version 2.0 (the "License"). \n
* You may not use this file except in compliance with the License. \n
* You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0 \n
* Unless required by applicable law or agreed to in writing, software \n
* distributed under the License is distributed on an "AS IS" BASIS, \n
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
* See the License for the specific language governing permissions and \n
* limitations under the License.
*
* @addtogroup Math
* @{
**/
#ifndef ZENDERER__MATH__MATRIX_HPP
#define ZENDERER__MATH__MATRIX_HPP
#include "Vector.hpp"
namespace zen
{
namespace math
{
/**
* 4x4 matrix representation.
* This is in place to support various linear transformation
* operations required for moving vertices around in OpenGL
* terms. Currently, there is only support for creating projection
* matrices for the rendering window / shaders to use.
**/
class ZEN_API matrix4x4_t
{
public:
matrix4x4_t();
matrix4x4_t(const real_t values[4][4]);
matrix4x4_t(const real_t** ppvalues);
matrix4x4_t(const matrix4x4_t& Copy);
matrix4x4_t& operator=(const matrix4x4_t& Copy);
/**
* Provides the matrix's elements at that row.
* See the following examples:
*
* matrix[0][3] // 3rd element of row 0 (r0, c3)
* matrix[3][1] // 1st element of row 3 (r3, c1)
* matrix[2][1] // 1st element of row 2 (r2, c1)
*
* The index value is automatically clamped at [0, 3].
*
* @param index Row index to access
* @return The `real_t` array at that index.
**/
real_t* operator[](uint8_t index);
/// Multiple two matrices together.
matrix4x4_t operator*(matrix4x4_t& Other) const;
/// Translates the matrix by a vector.
inline void Translate(const math::vector_t& V)
{
m_values[0][3] = V.x;
m_values[1][3] = V.y;
m_values[2][3] = V.z;
}
/// Adjusts the translation matrix by a vector.
inline void TranslateAdj(const math::vector_t& DV)
{
m_values[0][3] += V.x;
m_values[1][3] += V.y;
m_values[2][3] += V.z;
}
inline const real_t* GetPointer() const
{ return reinterpret_cast<const real_t*>(m_values); }
/**
* Creates a 2D projection matrix.
*
* @param width Projection width
* @param height Projection height
* @param max_z Maximum projection depth
* @param min_z Minimum projection depth
*
* @return The requested projection matrix.
**/
static inline matrix4x4_t Projection2D(
const uint16_t width, const uint16_t height,
const uint16_t max_z, const int min_z)
{
matrix4x4_t result;
result[0][0] = 2.0f / width;
result[0][3] = -1.0f;
result[1][1] = -2.0f / height;
result[1][3] = 1.0f;
result[2][2] = -2.0f / (min_z - max_z);
result[3][3] = 1.0f;
return result;
}
static matrix4x4_t CreateIdentityMatrix();
static const matrix4x4_t& GetIdentityMatrix();
private:
real_t m_values[4][4];
};
} // namespace math
} // namespace zen
#endif // ZENDERER__MATH__MATRIX_HPP
/** @} **/
<|endoftext|> |
<commit_before>#include <GL/freeglut.h>
#include <iostream>
#include <thread>
#include "sim/Constants.h"
#include "sim/Maze.h"
#include "sim/MazeFileUtilities.h"
#include "sim/MazeGraphic.h"
#include "sim/Mouse.h"
#include "sim/MouseGraphic.h"
#include "sim/MouseInterface.h"
#include "sim/Parameters.h"
#include "sim/Tile.h"
#include "sim/Sleep.h"
#include "algo/Solver.h"
// Function declarations
void draw();
void solve();
void keyInput(unsigned char key, int x, int y);
// Global object variable declarations
Solver* g_solver;
sim::MazeGraphic* g_mazeGraphic;
sim::MouseGraphic* g_mouseGraphic;
// Global primitive variable declarations
static /*non-const*/ bool PAUSED = false; // Initially set to false
static /*non-const*/ int SLEEP_TIME = 150; // ms between simulation steps
static /*non-const*/ bool UNDO_REQUESTED = false; // Whether or not an undo was requested
static /*non-const*/ bool RESET_REQUESTED = false; // Whether or not a reset was requested
int main(int argc, char* argv[]){
// TODO: read input file, and check size, use this as value instead of parameter
// Ensure that the size parameters are valid
if (sim::MAZE_WIDTH < 1 || sim::MAZE_HEIGHT < 1){
std::cout << "Impossible maze size - check \"src/sim/Parameters.h\"" << std::endl;
return 0;
}
// Initialize local simulation objects
sim::Maze maze(sim::MAZE_WIDTH, sim::MAZE_HEIGHT, sim::getMazeFileDirPath(argv[0]), sim::MAZE_FILE);
sim::Mouse mouse(&maze);
sim::MouseInterface mouseInterface(&mouse, &SLEEP_TIME, &PAUSED, &UNDO_REQUESTED, &RESET_REQUESTED);
Solver solver(&mouseInterface);
// Initialize the local graphics objects
sim::MazeGraphic mazeGraphic(&maze);
sim::MouseGraphic mouseGraphic(&mouse);
// Assign global variables
g_solver = &solver;
g_mazeGraphic = &mazeGraphic;
g_mouseGraphic = &mouseGraphic;
// GLUT Initialization
glutInit(&argc, argv);
glutInitWindowSize(sim::WINDOW_WIDTH, sim::WINDOW_HEIGHT);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowPosition(0, 0);
glutCreateWindow(sim::MAZE_FILE.c_str());
glClearColor(0.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(draw);
glutKeyboardFunc(keyInput);
// Start the solving loop (the name "first" is not important)
std::thread first(solve);
// Start the graphics loop (which never terminates)
glutMainLoop();
}
// Draw method for the GLUT environment
void draw(){
glClear(GL_COLOR_BUFFER_BIT);
g_mazeGraphic->draw();
g_mouseGraphic->draw();
glFlush();
sim::sleep(sim::SLEEP_TIME_MIN); // Reduces CPU usage
glutPostRedisplay();
}
void solve(){
sim::sleep(250); // Wait for 0.25 seconds for GLUT to intialize
g_solver->solve();
}
void keyInput(unsigned char key, int x, int y){
if (key == 32){ // Space bar
PAUSED = !PAUSED;
}
else if (key == 'f' || key == 'F'){ // Faster
SLEEP_TIME /= 1.15;
if (SLEEP_TIME < sim::SLEEP_TIME_MIN){
SLEEP_TIME = sim::SLEEP_TIME_MIN;
}
}
else if (key == 's' || key == 'S'){ // Slower
SLEEP_TIME *= 1.2;
if (SLEEP_TIME > sim::SLEEP_TIME_MAX){
SLEEP_TIME = sim::SLEEP_TIME_MAX;
}
}
else if (key == 'u' || key == 'U'){
// Undo request - reset the position mouse but retains memory
UNDO_REQUESTED = true;
}
else if (key == 'r' || key == 'R'){
// Reset requested - reset the position mouse and don't retain memory
RESET_REQUESTED = true;
}
else if (key == 'q' || key == 'Q'){ // Quit
exit(0);
}
}
<commit_msg>Test Push<commit_after>#include <GL/freeglut.h>
#include <iostream>
#include <thread>
#include "sim/Constants.h"
#include "sim/Maze.h"
#include "sim/MazeFileUtilities.h"
#include "sim/MazeGraphic.h"
#include "sim/Mouse.h"
#include "sim/MouseGraphic.h"
#include "sim/MouseInterface.h"
#include "sim/Parameters.h"
#include "sim/Tile.h"
#include "sim/Sleep.h"
#include "algo/Solver.h"
// Test Comment
// Function declarations
void draw();
void solve();
void keyInput(unsigned char key, int x, int y);
// Global object variable declarations
Solver* g_solver;
sim::MazeGraphic* g_mazeGraphic;
sim::MouseGraphic* g_mouseGraphic;
// Global primitive variable declarations
static /*non-const*/ bool PAUSED = false; // Initially set to false
static /*non-const*/ int SLEEP_TIME = 150; // ms between simulation steps
static /*non-const*/ bool UNDO_REQUESTED = false; // Whether or not an undo was requested
static /*non-const*/ bool RESET_REQUESTED = false; // Whether or not a reset was requested
int main(int argc, char* argv[]){
// TODO: read input file, and check size, use this as value instead of parameter
// Ensure that the size parameters are valid
if (sim::MAZE_WIDTH < 1 || sim::MAZE_HEIGHT < 1){
std::cout << "Impossible maze size - check \"src/sim/Parameters.h\"" << std::endl;
return 0;
}
// Initialize local simulation objects
sim::Maze maze(sim::MAZE_WIDTH, sim::MAZE_HEIGHT, sim::getMazeFileDirPath(argv[0]), sim::MAZE_FILE);
sim::Mouse mouse(&maze);
sim::MouseInterface mouseInterface(&mouse, &SLEEP_TIME, &PAUSED, &UNDO_REQUESTED, &RESET_REQUESTED);
Solver solver(&mouseInterface);
// Initialize the local graphics objects
sim::MazeGraphic mazeGraphic(&maze);
sim::MouseGraphic mouseGraphic(&mouse);
// Assign global variables
g_solver = &solver;
g_mazeGraphic = &mazeGraphic;
g_mouseGraphic = &mouseGraphic;
// GLUT Initialization
glutInit(&argc, argv);
glutInitWindowSize(sim::WINDOW_WIDTH, sim::WINDOW_HEIGHT);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowPosition(0, 0);
glutCreateWindow(sim::MAZE_FILE.c_str());
glClearColor(0.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(draw);
glutKeyboardFunc(keyInput);
// Start the solving loop (the name "first" is not important)
std::thread first(solve);
// Start the graphics loop (which never terminates)
glutMainLoop();
}
// Draw method for the GLUT environment
void draw(){
glClear(GL_COLOR_BUFFER_BIT);
g_mazeGraphic->draw();
g_mouseGraphic->draw();
glFlush();
sim::sleep(sim::SLEEP_TIME_MIN); // Reduces CPU usage
glutPostRedisplay();
}
void solve(){
sim::sleep(250); // Wait for 0.25 seconds for GLUT to intialize
g_solver->solve();
}
void keyInput(unsigned char key, int x, int y){
if (key == 32){ // Space bar
PAUSED = !PAUSED;
}
else if (key == 'f' || key == 'F'){ // Faster
SLEEP_TIME /= 1.15;
if (SLEEP_TIME < sim::SLEEP_TIME_MIN){
SLEEP_TIME = sim::SLEEP_TIME_MIN;
}
}
else if (key == 's' || key == 'S'){ // Slower
SLEEP_TIME *= 1.2;
if (SLEEP_TIME > sim::SLEEP_TIME_MAX){
SLEEP_TIME = sim::SLEEP_TIME_MAX;
}
}
else if (key == 'u' || key == 'U'){
// Undo request - reset the position mouse but retains memory
UNDO_REQUESTED = true;
}
else if (key == 'r' || key == 'R'){
// Reset requested - reset the position mouse and don't retain memory
RESET_REQUESTED = true;
}
else if (key == 'q' || key == 'Q'){ // Quit
exit(0);
}
}
<|endoftext|> |
<commit_before>#include "NormalPack.h"
#include "MaxRectsBinaryPack2.h"
#include "ImageTrimData.h"
#include <ee/FileHelper.h>
#include <ee/Exception.h>
#include <ee/StringHelper.h>
#include <ee/ImagePack.h>
#include <ee/Image.h>
#include <ee/LibpngAdapter.h>
#include <json/json.h>
#include <string>
#include <assert.h>
namespace etexpacker
{
static const bool CLOCKWISE_ROT = true;
NormalPack::NormalPack(const std::vector<std::string>& files, const ImageTrimData* trim_info,
int extrude_min, int extrude_max, int start_id)
: m_filepaths(files)
, m_trim_info(trim_info)
, m_extrude_min(extrude_min)
, m_extrude_max(extrude_max)
, m_start_id(start_id)
{
}
void NormalPack::Pack(int static_size, int max_size, int min_size)
{
if (static_size <= 0) {
Pack(PACK_SQUARE_MULTI_AUTO, -1, max_size, min_size);
} else {
Pack(PACK_SQUARE_MULTI, static_size);
}
}
void NormalPack::OutputInfo(const std::string& dir, const std::string& dst_file, const std::string& format) const
{
assert(m_filepaths.size() == m_src_sizes.size() && m_filepaths.size() == m_dst_pos.size());
for (int i = 0, n = m_dst_img_idx.size(); i < n; ++i)
{
Json::Value value;
for (int j = 0, m = m_dst_img_idx[i].size(); j < m; ++j)
{
int idx = m_dst_img_idx[i][j];
Json::Value frame_val;
//std::string filepath = ee::FileHelper::FormatFilepath(m_filepaths[idx]);
std::string filepath = ee::FileHelper::GetRelativePath(dir, m_filepaths[idx]);
frame_val["filename"] = filepath;
const RectSize& src_sz = m_src_sizes[idx];
const Rect& pos = m_dst_pos[idx];
assert(src_sz.width == pos.width && src_sz.height == pos.height
|| src_sz.width == pos.height && src_sz.height == pos.width);
bool rot = (src_sz.width != pos.width || src_sz.height != pos.height);
frame_val["rotated"] = rot;
if (m_trim_info)
{
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[idx]);
if (!t) {
throw ee::Exception("NormalPack::OutputInfo didn't find trim_info info: %s\n", m_filepaths[idx]);
}
int e_left, e_right, e_bottom, e_up;
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
frame_val["frame"]["w"] = src_sz.width - e_left - e_right;
frame_val["frame"]["h"] = src_sz.height - e_bottom - e_up;
if (!rot) {
frame_val["frame"]["x"] = pos.x + e_left;
frame_val["frame"]["y"] = pos.y + e_bottom;
} else {
if (CLOCKWISE_ROT) {
frame_val["frame"]["x"] = pos.x + e_up;
frame_val["frame"]["y"] = pos.y + e_left;
} else {
frame_val["frame"]["x"] = pos.x + e_bottom;
frame_val["frame"]["y"] = pos.y + e_right;
}
}
frame_val["trimmed"] = false;
frame_val["spriteSourceSize"]["x"] = t->x;
frame_val["spriteSourceSize"]["y"] = t->y;
frame_val["spriteSourceSize"]["w"] = t->w;
frame_val["spriteSourceSize"]["h"] = t->h;
frame_val["sourceSize"]["w"] = t->ori_w;
frame_val["sourceSize"]["h"] = t->ori_h;
}
else
{
int e_left = m_extrude_min,
e_right = m_extrude_min,
e_bottom = m_extrude_min,
e_up = m_extrude_min;
int w = src_sz.width - e_left - e_right,
h = src_sz.height - e_bottom - e_up;
frame_val["frame"]["w"] = w;
frame_val["frame"]["h"] = h;
if (!rot) {
frame_val["frame"]["x"] = pos.x + e_left;
frame_val["frame"]["y"] = pos.y + e_bottom;
} else {
if (CLOCKWISE_ROT) {
frame_val["frame"]["x"] = pos.x + e_up;
frame_val["frame"]["y"] = pos.y + e_left;
} else {
frame_val["frame"]["x"] = pos.x + e_bottom;
frame_val["frame"]["y"] = pos.y + e_right;
}
}
frame_val["trimmed"] = false;
frame_val["spriteSourceSize"]["x"] = 0;
frame_val["spriteSourceSize"]["y"] = 0;
frame_val["spriteSourceSize"]["w"] = w;
frame_val["spriteSourceSize"]["h"] = h;
frame_val["sourceSize"]["w"] = w;
frame_val["sourceSize"]["h"] = h;
}
value["frames"][j] = frame_val;
}
Json::Value meta_val;
meta_val["size"]["w"] = m_dst_img_sz[i].width;
meta_val["size"]["h"] = m_dst_img_sz[i].height;
meta_val["scale"] = "1";
meta_val["app"] = "easydb";
meta_val["format"] = format;
value["meta"] = meta_val;
std::string out_filepath = dst_file;
out_filepath.insert(out_filepath.find_last_of("."), ee::StringHelper::ToString(m_start_id + i));
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(out_filepath.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, value);
fout.close();
}
}
void NormalPack::OutputImage(const std::string& filepath) const
{
assert(m_filepaths.size() == m_src_sizes.size() && m_filepaths.size() == m_dst_pos.size());
for (int i = 0, n = m_dst_img_idx.size(); i < n; ++i)
{
ee::ImagePack pack(m_dst_img_sz[i].width, m_dst_img_sz[i].height);
for (int j = 0, m = m_dst_img_idx[i].size(); j < m; ++j)
{
int idx = m_dst_img_idx[i][j];
const Rect& pos = m_dst_pos[idx];
const RectSize& src_sz = m_src_sizes[idx];
bool rot;
assert(src_sz.width == pos.width && src_sz.height == pos.height
|| src_sz.width == pos.height && src_sz.height == pos.width);
if (src_sz.width == pos.width && src_sz.height == pos.height) {
rot = false;
} else {
rot = true;
}
ee::Image* img = ee::ImageMgr::Instance()->GetItem(m_filepaths[idx]);
int e_left, e_right, e_bottom, e_up;
if (m_trim_info) {
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[idx]);
if (!t) {
throw ee::Exception("NormalPack::OutputInfo didn't find trim_info info: %s\n", m_filepaths[idx]);
}
assert(t->w == img->GetOriginWidth() && t->h == img->GetOriginHeight());
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
} else {
e_left = e_right = e_bottom = e_up = m_extrude_min;
}
if (rot) {
if (CLOCKWISE_ROT) {
pack.AddImage(img, pos.x + e_up, pos.y + e_left, pos.width - e_bottom - e_up, pos.height - e_left - e_right,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
} else {
pack.AddImage(img, pos.x + e_bottom, pos.y + e_right, pos.width - e_bottom - e_up, pos.height - e_left - e_right,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
}
} else {
pack.AddImage(img, pos.x + e_left, pos.y + e_bottom, pos.width - e_left - e_right, pos.height - e_bottom - e_up,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
}
img->Release();
}
std::string out_filepath = filepath;
out_filepath.insert(out_filepath.find_last_of("."), ee::StringHelper::ToString(m_start_id + i));
pack.OutputToFile(out_filepath);
}
}
void NormalPack::Pack(PACK_STRATEGY strategy, int static_size, int max_size, int min_size)
{
for (int i = 0, n = m_filepaths.size(); i < n; ++i) {
const std::string& path = m_filepaths[i];
RectSize sz;
ee::LibpngAdapter::ReadHeader(path.c_str(), sz.width, sz.height);
if (m_trim_info) {
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[i]);
if (!t) {
throw ee::Exception("NormalPack::OutputInfo didn't find trim_info info: %s\n", m_filepaths[i]);
}
int e_left, e_right, e_bottom, e_up;
assert(t->w == sz.width && t->h == sz.height);
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
sz.width += e_left + e_right;
sz.height += e_bottom + e_up;
} else {
sz.width += m_extrude_min * 2;
sz.height += m_extrude_min * 2;
}
m_src_sizes.push_back(sz);
}
MaxRectsBinaryPack2 packer;
packer.Pack(strategy, static_size, max_size, min_size, m_src_sizes, m_dst_pos);
packer.GetSize(m_dst_img_sz);
m_dst_img_idx.resize(m_dst_img_sz.size());
for (int i = 0, n = m_filepaths.size(); i < n; ++i) {
const Rect& pos = m_dst_pos[i];
m_dst_img_idx[pos.tex_id].push_back(i);
}
}
void NormalPack::GetExtrude(const int bound[], int w, int h, int& left, int& right, int& bottom, int& up) const
{
left = GetExtrude(bound[0], bound[1], h);
up = GetExtrude(bound[2], bound[3], w);
right = GetExtrude(bound[4], bound[5], h);
bottom = GetExtrude(bound[6], bound[7], w);
}
int NormalPack::GetExtrude(int max, int tot, int edge) const
{
const float MAX_LIMIT = 25;
const float TOT_LIMIT = 0.5f;
if (max > MAX_LIMIT || (float)tot/edge > TOT_LIMIT) {
return m_extrude_max;
} else {
return m_extrude_min;
}
}
}<commit_msg>[ADDED] exception for pack no space<commit_after>#include "NormalPack.h"
#include "MaxRectsBinaryPack2.h"
#include "ImageTrimData.h"
#include <ee/FileHelper.h>
#include <ee/Exception.h>
#include <ee/StringHelper.h>
#include <ee/ImagePack.h>
#include <ee/Image.h>
#include <ee/LibpngAdapter.h>
#include <json/json.h>
#include <string>
#include <assert.h>
namespace etexpacker
{
static const bool CLOCKWISE_ROT = true;
NormalPack::NormalPack(const std::vector<std::string>& files, const ImageTrimData* trim_info,
int extrude_min, int extrude_max, int start_id)
: m_filepaths(files)
, m_trim_info(trim_info)
, m_extrude_min(extrude_min)
, m_extrude_max(extrude_max)
, m_start_id(start_id)
{
}
void NormalPack::Pack(int static_size, int max_size, int min_size)
{
if (static_size <= 0) {
Pack(PACK_SQUARE_MULTI_AUTO, -1, max_size, min_size);
} else {
Pack(PACK_SQUARE_MULTI, static_size);
}
}
void NormalPack::OutputInfo(const std::string& dir, const std::string& dst_file, const std::string& format) const
{
assert(m_filepaths.size() == m_src_sizes.size() && m_filepaths.size() == m_dst_pos.size());
for (int i = 0, n = m_dst_img_idx.size(); i < n; ++i)
{
Json::Value value;
for (int j = 0, m = m_dst_img_idx[i].size(); j < m; ++j)
{
int idx = m_dst_img_idx[i][j];
Json::Value frame_val;
//std::string filepath = ee::FileHelper::FormatFilepath(m_filepaths[idx]);
std::string filepath = ee::FileHelper::GetRelativePath(dir, m_filepaths[idx]);
frame_val["filename"] = filepath;
const RectSize& src_sz = m_src_sizes[idx];
const Rect& pos = m_dst_pos[idx];
assert(src_sz.width == pos.width && src_sz.height == pos.height
|| src_sz.width == pos.height && src_sz.height == pos.width);
bool rot = (src_sz.width != pos.width || src_sz.height != pos.height);
frame_val["rotated"] = rot;
if (m_trim_info)
{
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[idx]);
if (!t) {
throw ee::Exception("NormalPack::OutputInfo didn't find trim_info info: %s\n", m_filepaths[idx]);
}
int e_left, e_right, e_bottom, e_up;
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
frame_val["frame"]["w"] = src_sz.width - e_left - e_right;
frame_val["frame"]["h"] = src_sz.height - e_bottom - e_up;
if (!rot) {
frame_val["frame"]["x"] = pos.x + e_left;
frame_val["frame"]["y"] = pos.y + e_bottom;
} else {
if (CLOCKWISE_ROT) {
frame_val["frame"]["x"] = pos.x + e_up;
frame_val["frame"]["y"] = pos.y + e_left;
} else {
frame_val["frame"]["x"] = pos.x + e_bottom;
frame_val["frame"]["y"] = pos.y + e_right;
}
}
frame_val["trimmed"] = false;
frame_val["spriteSourceSize"]["x"] = t->x;
frame_val["spriteSourceSize"]["y"] = t->y;
frame_val["spriteSourceSize"]["w"] = t->w;
frame_val["spriteSourceSize"]["h"] = t->h;
frame_val["sourceSize"]["w"] = t->ori_w;
frame_val["sourceSize"]["h"] = t->ori_h;
}
else
{
int e_left = m_extrude_min,
e_right = m_extrude_min,
e_bottom = m_extrude_min,
e_up = m_extrude_min;
int w = src_sz.width - e_left - e_right,
h = src_sz.height - e_bottom - e_up;
frame_val["frame"]["w"] = w;
frame_val["frame"]["h"] = h;
if (!rot) {
frame_val["frame"]["x"] = pos.x + e_left;
frame_val["frame"]["y"] = pos.y + e_bottom;
} else {
if (CLOCKWISE_ROT) {
frame_val["frame"]["x"] = pos.x + e_up;
frame_val["frame"]["y"] = pos.y + e_left;
} else {
frame_val["frame"]["x"] = pos.x + e_bottom;
frame_val["frame"]["y"] = pos.y + e_right;
}
}
frame_val["trimmed"] = false;
frame_val["spriteSourceSize"]["x"] = 0;
frame_val["spriteSourceSize"]["y"] = 0;
frame_val["spriteSourceSize"]["w"] = w;
frame_val["spriteSourceSize"]["h"] = h;
frame_val["sourceSize"]["w"] = w;
frame_val["sourceSize"]["h"] = h;
}
value["frames"][j] = frame_val;
}
Json::Value meta_val;
meta_val["size"]["w"] = m_dst_img_sz[i].width;
meta_val["size"]["h"] = m_dst_img_sz[i].height;
meta_val["scale"] = "1";
meta_val["app"] = "easydb";
meta_val["format"] = format;
value["meta"] = meta_val;
std::string out_filepath = dst_file;
out_filepath.insert(out_filepath.find_last_of("."), ee::StringHelper::ToString(m_start_id + i));
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(out_filepath.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, value);
fout.close();
}
}
void NormalPack::OutputImage(const std::string& filepath) const
{
assert(m_filepaths.size() == m_src_sizes.size() && m_filepaths.size() == m_dst_pos.size());
for (int i = 0, n = m_dst_img_idx.size(); i < n; ++i)
{
ee::ImagePack pack(m_dst_img_sz[i].width, m_dst_img_sz[i].height);
for (int j = 0, m = m_dst_img_idx[i].size(); j < m; ++j)
{
int idx = m_dst_img_idx[i][j];
const Rect& pos = m_dst_pos[idx];
const RectSize& src_sz = m_src_sizes[idx];
bool rot;
assert(src_sz.width == pos.width && src_sz.height == pos.height
|| src_sz.width == pos.height && src_sz.height == pos.width);
if (src_sz.width == pos.width && src_sz.height == pos.height) {
rot = false;
} else {
rot = true;
}
ee::Image* img = ee::ImageMgr::Instance()->GetItem(m_filepaths[idx]);
int e_left, e_right, e_bottom, e_up;
if (m_trim_info) {
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[idx]);
if (!t) {
throw ee::Exception("NormalPack::OutputInfo didn't find trim_info info: %s\n", m_filepaths[idx]);
}
assert(t->w == img->GetOriginWidth() && t->h == img->GetOriginHeight());
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
} else {
e_left = e_right = e_bottom = e_up = m_extrude_min;
}
if (rot) {
if (CLOCKWISE_ROT) {
pack.AddImage(img, pos.x + e_up, pos.y + e_left, pos.width - e_bottom - e_up, pos.height - e_left - e_right,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
} else {
pack.AddImage(img, pos.x + e_bottom, pos.y + e_right, pos.width - e_bottom - e_up, pos.height - e_left - e_right,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
}
} else {
pack.AddImage(img, pos.x + e_left, pos.y + e_bottom, pos.width - e_left - e_right, pos.height - e_bottom - e_up,
rot, CLOCKWISE_ROT, img->GetChannels() == 4, e_left, e_bottom, e_right, e_up);
}
img->Release();
}
std::string out_filepath = filepath;
out_filepath.insert(out_filepath.find_last_of("."), ee::StringHelper::ToString(m_start_id + i));
pack.OutputToFile(out_filepath);
}
}
void NormalPack::Pack(PACK_STRATEGY strategy, int static_size, int max_size, int min_size)
{
for (int i = 0, n = m_filepaths.size(); i < n; ++i) {
const std::string& path = m_filepaths[i];
RectSize sz;
ee::LibpngAdapter::ReadHeader(path.c_str(), sz.width, sz.height);
if (sz.width > max_size || sz.height > max_size) {
throw ee::Exception("NormalPack::Pack no sapce file: %s, src_sz: %d %d, dst_sz: %d\n",
m_filepaths[i].c_str(), sz.width, sz.height, max_size);
}
if (m_trim_info) {
const ImageTrimData::Trim* t = m_trim_info->Query(m_filepaths[i]);
if (!t) {
throw ee::Exception("NormalPack::Pack didn't find trim_info info: %s\n", m_filepaths[i]);
}
int e_left, e_right, e_bottom, e_up;
assert(t->w == sz.width && t->h == sz.height);
GetExtrude(t->bound, t->w, t->h, e_left, e_right, e_bottom, e_up);
sz.width += e_left + e_right;
sz.height += e_bottom + e_up;
} else {
sz.width += m_extrude_min * 2;
sz.height += m_extrude_min * 2;
}
m_src_sizes.push_back(sz);
}
MaxRectsBinaryPack2 packer;
packer.Pack(strategy, static_size, max_size, min_size, m_src_sizes, m_dst_pos);
packer.GetSize(m_dst_img_sz);
m_dst_img_idx.resize(m_dst_img_sz.size());
for (int i = 0, n = m_filepaths.size(); i < n; ++i) {
const Rect& pos = m_dst_pos[i];
m_dst_img_idx[pos.tex_id].push_back(i);
}
}
void NormalPack::GetExtrude(const int bound[], int w, int h, int& left, int& right, int& bottom, int& up) const
{
left = GetExtrude(bound[0], bound[1], h);
up = GetExtrude(bound[2], bound[3], w);
right = GetExtrude(bound[4], bound[5], h);
bottom = GetExtrude(bound[6], bound[7], w);
}
int NormalPack::GetExtrude(int max, int tot, int edge) const
{
const float MAX_LIMIT = 25;
const float TOT_LIMIT = 0.5f;
if (max > MAX_LIMIT || (float)tot/edge > TOT_LIMIT) {
return m_extrude_max;
} else {
return m_extrude_min;
}
}
}<|endoftext|> |
<commit_before>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "constants.hpp"
#include "event_manipulator.hpp"
#include "gcd_utility.hpp"
#include "human_interface_device.hpp"
#include "iokit_utility.hpp"
#include "iopm_client.hpp"
#include "logger.hpp"
#include "manipulator.hpp"
#include "spdlog_utility.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <fstream>
#include <json/json.hpp>
#include <thread>
#include <time.h>
class device_grabber final {
public:
device_grabber(const device_grabber&) = delete;
device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator),
grab_timer_(nullptr),
mode_(mode::observing),
grabbed_(false),
is_grabbable_callback_log_reducer_(logger::get_logger()),
suspended_(false) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
iopm_client_ = std::make_unique<iopm_client>(logger::get_logger(),
std::bind(&device_grabber::iopm_client_callback, this, std::placeholders::_1));
}
~device_grabber(void) {
// Release manager_ in main thread to avoid callback invocations after object has been destroyed.
gcd_utility::dispatch_sync_in_main_queue(^{
iopm_client_ = nullptr;
ungrab_devices();
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
});
}
void grab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::grabbing;
}
event_manipulator_.reset();
event_manipulator_.grab_mouse_events();
cancel_grab_timer();
// ----------------------------------------
// setup grab_timer_
grab_timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_.get());
dispatch_source_set_timer(grab_timer_, dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), 0.1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(grab_timer_, ^{
std::lock_guard<std::mutex> grab_guard(grab_mutex_);
if (grabbed_) {
return;
}
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_grabbable() != human_interface_device::grabbable_state::grabbable) {
return;
}
}
}
// ----------------------------------------
// grab devices
grabbed_ = true;
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
(it.second)->unobserve();
(it.second)->grab();
}
}
logger::get_logger().info("Connected devices are grabbed");
cancel_grab_timer();
});
dispatch_resume(grab_timer_);
}
void ungrab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::observing;
}
if (!grabbed_) {
return;
}
grabbed_ = false;
cancel_grab_timer();
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
(it.second)->ungrab();
(it.second)->observe();
}
}
event_manipulator_.ungrab_mouse_events();
event_manipulator_.reset();
logger::get_logger().info("Connected devices are ungrabbed");
}
void suspend(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (!suspended_) {
logger::get_logger().info("device_grabber::suspend");
suspended_ = true;
if (mode_ == mode::grabbing) {
ungrab_devices(false);
}
}
}
void resume(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (suspended_) {
logger::get_logger().info("device_grabber::resume");
suspended_ = false;
if (mode_ == mode::grabbing) {
grab_devices(false);
}
}
}
void set_caps_lock_led_state(krbn::led_state state) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
(it.second)->set_caps_lock_led_state(state);
}
}
private:
enum class mode {
observing,
grabbing,
};
void iopm_client_callback(uint32_t message_type) {
switch (message_type) {
case kIOMessageSystemWillSleep:
suspend();
break;
case kIOMessageSystemWillPowerOn:
resume();
break;
default:
break;
}
}
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_matching_device(logger::get_logger(), device);
auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device);
dev->set_is_grabbable_callback(std::bind(&device_grabber::is_grabbable_callback, this, std::placeholders::_1));
dev->set_grabbed_callback(std::bind(&device_grabber::grabbed_callback, this, std::placeholders::_1));
dev->set_value_callback(std::bind(&device_grabber::value_callback,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4,
std::placeholders::_5,
std::placeholders::_6));
// ----------------------------------------
if (grabbed_) {
dev->grab();
} else {
dev->observe();
}
{
std::lock_guard<std::mutex> guard(hids_mutex_);
hids_[device] = std::move(dev);
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(logger::get_logger(), device);
{
std::lock_guard<std::mutex> guard(hids_mutex_);
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
hids_.erase(it);
}
}
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
event_manipulator_.stop_key_repeat();
}
void value_callback(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
if (!grabbed_) {
return;
}
auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id());
if (auto key_code = krbn::types::get_key_code(usage_page, usage)) {
bool pressed = integer_value;
event_manipulator_.handle_keyboard_event(device_registry_entry_id, *key_code, pressed);
} else if (auto pointing_button = krbn::types::get_pointing_button(usage_page, usage)) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::button,
*pointing_button,
integer_value);
} else {
switch (usage_page) {
case kHIDPage_GenericDesktop:
if (usage == kHIDUsage_GD_X) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::x,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Y) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::y,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Wheel) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::vertical_wheel,
boost::none,
integer_value);
}
break;
case kHIDPage_Consumer:
if (usage == kHIDUsage_Csmr_ACPan) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::horizontal_wheel,
boost::none,
integer_value);
}
break;
default:
break;
}
}
// reset modifier_flags state if all keys are released.
if (get_all_devices_pressed_keys_count() == 0) {
event_manipulator_.reset_modifier_flag_state();
event_manipulator_.reset_pointing_button_state();
}
}
human_interface_device::grabbable_state is_grabbable_callback(human_interface_device& device) {
if (!event_manipulator_.is_ready()) {
is_grabbable_callback_log_reducer_.warn("event_manipulator_ is not ready. Please wait for a while.");
return human_interface_device::grabbable_state::ungrabbable_temporarily;
}
return human_interface_device::grabbable_state::grabbable;
}
void grabbed_callback(human_interface_device& device) {
// set keyboard led
event_manipulator_.refresh_caps_lock_led();
}
size_t get_all_devices_pressed_keys_count(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
size_t total = 0;
for (const auto& it : hids_) {
total += (it.second)->get_pressed_keys_count();
}
return total;
}
bool is_keyboard_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_keyboard()) {
return true;
}
}
return false;
}
bool is_pointing_device_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_pointing_device()) {
return true;
}
}
return false;
}
void output_devices_json(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
nlohmann::json json;
json = nlohmann::json::array();
for (const auto& it : hids_) {
nlohmann::json j({});
if (auto vendor_id = (it.second)->get_vendor_id()) {
j["vendor_id"] = *vendor_id;
}
if (auto product_id = (it.second)->get_product_id()) {
j["product_id"] = *product_id;
}
if (auto manufacturer = (it.second)->get_manufacturer()) {
j["manipulator"] = *manufacturer;
}
if (auto product = (it.second)->get_product()) {
j["product"] = *product;
}
if (!j.empty()) {
json.push_back(j);
}
}
std::ofstream stream(constants::get_devices_json_file_path());
if (stream) {
stream << std::setw(4) << json << std::endl;
chmod(constants::get_devices_json_file_path(), 0644);
}
}
void cancel_grab_timer(void) {
if (grab_timer_) {
dispatch_source_cancel(grab_timer_);
dispatch_release(grab_timer_);
grab_timer_ = nullptr;
}
}
manipulator::event_manipulator& event_manipulator_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<iopm_client> iopm_client_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
std::mutex hids_mutex_;
gcd_utility::scoped_queue queue_;
dispatch_source_t _Nullable grab_timer_;
std::mutex grab_mutex_;
std::atomic<mode> mode_;
std::atomic<bool> grabbed_;
spdlog_utility::log_reducer is_grabbable_callback_log_reducer_;
std::mutex suspend_mutex_;
bool suspended_;
};
<commit_msg>remove grab_timer from device_grabber<commit_after>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "constants.hpp"
#include "event_manipulator.hpp"
#include "gcd_utility.hpp"
#include "human_interface_device.hpp"
#include "iokit_utility.hpp"
#include "iopm_client.hpp"
#include "logger.hpp"
#include "manipulator.hpp"
#include "spdlog_utility.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <fstream>
#include <json/json.hpp>
#include <thread>
#include <time.h>
class device_grabber final {
public:
device_grabber(const device_grabber&) = delete;
device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator),
mode_(mode::observing),
is_grabbable_callback_log_reducer_(logger::get_logger()),
suspended_(false) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
iopm_client_ = std::make_unique<iopm_client>(logger::get_logger(),
std::bind(&device_grabber::iopm_client_callback, this, std::placeholders::_1));
}
~device_grabber(void) {
// Release manager_ in main thread to avoid callback invocations after object has been destroyed.
gcd_utility::dispatch_sync_in_main_queue(^{
iopm_client_ = nullptr;
ungrab_devices();
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
});
}
void grab_devices(bool change_mode = true) {
gcd_utility::dispatch_sync_in_main_queue(^{
if (change_mode) {
mode_ = mode::grabbing;
}
event_manipulator_.reset();
event_manipulator_.grab_mouse_events();
for (const auto& it : hids_) {
(it.second)->grab();
}
});
}
void ungrab_devices(bool change_mode = true) {
gcd_utility::dispatch_sync_in_main_queue(^{
if (change_mode) {
mode_ = mode::observing;
}
for (auto&& it : hids_) {
(it.second)->ungrab();
(it.second)->observe();
}
event_manipulator_.ungrab_mouse_events();
event_manipulator_.reset();
logger::get_logger().info("Connected devices are ungrabbed");
});
}
void suspend(void) {
gcd_utility::dispatch_sync_in_main_queue(^{
if (!suspended_) {
logger::get_logger().info("device_grabber::suspend");
suspended_ = true;
if (mode_ == mode::grabbing) {
ungrab_devices(false);
}
}
});
}
void resume(void) {
gcd_utility::dispatch_sync_in_main_queue(^{
if (suspended_) {
logger::get_logger().info("device_grabber::resume");
suspended_ = false;
if (mode_ == mode::grabbing) {
grab_devices(false);
}
}
});
}
void set_caps_lock_led_state(krbn::led_state state) {
gcd_utility::dispatch_sync_in_main_queue(^{
for (const auto& it : hids_) {
(it.second)->set_caps_lock_led_state(state);
}
});
}
private:
enum class mode {
observing,
grabbing,
};
void iopm_client_callback(uint32_t message_type) {
switch (message_type) {
case kIOMessageSystemWillSleep:
suspend();
break;
case kIOMessageSystemWillPowerOn:
resume();
break;
default:
break;
}
}
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_matching_device(logger::get_logger(), device);
auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device);
dev->set_is_grabbable_callback(std::bind(&device_grabber::is_grabbable_callback, this, std::placeholders::_1));
dev->set_grabbed_callback(std::bind(&device_grabber::grabbed_callback, this, std::placeholders::_1));
dev->set_value_callback(std::bind(&device_grabber::value_callback,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4,
std::placeholders::_5,
std::placeholders::_6));
// ----------------------------------------
if (mode_ == mode::grabbing) {
dev->grab();
} else {
dev->observe();
}
hids_[device] = std::move(dev);
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(logger::get_logger(), device);
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
hids_.erase(it);
}
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
event_manipulator_.stop_key_repeat();
}
void value_callback(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
if (!device.is_grabbed()) {
return;
}
auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id());
if (auto key_code = krbn::types::get_key_code(usage_page, usage)) {
bool pressed = integer_value;
event_manipulator_.handle_keyboard_event(device_registry_entry_id, *key_code, pressed);
} else if (auto pointing_button = krbn::types::get_pointing_button(usage_page, usage)) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::button,
*pointing_button,
integer_value);
} else {
switch (usage_page) {
case kHIDPage_GenericDesktop:
if (usage == kHIDUsage_GD_X) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::x,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Y) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::y,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Wheel) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::vertical_wheel,
boost::none,
integer_value);
}
break;
case kHIDPage_Consumer:
if (usage == kHIDUsage_Csmr_ACPan) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::horizontal_wheel,
boost::none,
integer_value);
}
break;
default:
break;
}
}
// reset modifier_flags state if all keys are released.
if (get_all_devices_pressed_keys_count() == 0) {
event_manipulator_.reset_modifier_flag_state();
event_manipulator_.reset_pointing_button_state();
}
}
human_interface_device::grabbable_state is_grabbable_callback(human_interface_device& device) {
if (!event_manipulator_.is_ready()) {
is_grabbable_callback_log_reducer_.warn("event_manipulator_ is not ready. Please wait for a while.");
return human_interface_device::grabbable_state::ungrabbable_temporarily;
}
return human_interface_device::grabbable_state::grabbable;
}
void grabbed_callback(human_interface_device& device) {
// set keyboard led
event_manipulator_.refresh_caps_lock_led();
}
size_t get_all_devices_pressed_keys_count(void) {
size_t total = 0;
for (const auto& it : hids_) {
total += (it.second)->get_pressed_keys_count();
}
return total;
}
bool is_keyboard_connected(void) {
for (const auto& it : hids_) {
if ((it.second)->is_keyboard()) {
return true;
}
}
return false;
}
bool is_pointing_device_connected(void) {
for (const auto& it : hids_) {
if ((it.second)->is_pointing_device()) {
return true;
}
}
return false;
}
void output_devices_json(void) {
nlohmann::json json;
json = nlohmann::json::array();
for (const auto& it : hids_) {
nlohmann::json j({});
if (auto vendor_id = (it.second)->get_vendor_id()) {
j["vendor_id"] = *vendor_id;
}
if (auto product_id = (it.second)->get_product_id()) {
j["product_id"] = *product_id;
}
if (auto manufacturer = (it.second)->get_manufacturer()) {
j["manipulator"] = *manufacturer;
}
if (auto product = (it.second)->get_product()) {
j["product"] = *product;
}
if (!j.empty()) {
json.push_back(j);
}
}
std::ofstream stream(constants::get_devices_json_file_path());
if (stream) {
stream << std::setw(4) << json << std::endl;
chmod(constants::get_devices_json_file_path(), 0644);
}
}
manipulator::event_manipulator& event_manipulator_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<iopm_client> iopm_client_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
mode mode_;
spdlog_utility::log_reducer is_grabbable_callback_log_reducer_;
bool suspended_;
};
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/opencv.hpp>
#include "Utils.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
// open the webcam
VideoCapture cam(0);
if (!cam.isOpened()) {
cerr << "Camera failed to open" << endl;
return -1;
}
// get dims of video capture
int camHeight = static_cast<int>(cam.get(CV_CAP_PROP_FRAME_HEIGHT));
int camWidth = static_cast<int>(cam.get(CV_CAP_PROP_FRAME_WIDTH));
cout << camHeight << "x" << camWidth << endl;
// create window that shows the unchanged webcam output
namedWindow("UnchangedOutput", CV_WINDOW_AUTOSIZE);
//create window that shows skin detection
namedWindow("SkinDetection", WINDOW_AUTOSIZE);
// create window that show pixel diffs per frame
//namedWindow("FrameDiff", WINDOW_AUTOSIZE);
// create window that show motion energy history
//namedWindow("MotionHistory", WINDOW_AUTOSIZE);
#if 0
// initialize motion history vector
vector<Mat> motionHist;
Mat fMH1, fMH2, fMH3;
fMH1 = Mat::zeros(camHeight, camWidth, CV_8UC1);
fMH2 = fMH1.clone();
fMH3 = fMH1.clone();
motionHist.push_back(fMH1);
motionHist.push_back(fMH2);
motionHist.push_back(fMH3);
#endif
// read a single frame now to have a frame to compare
Mat prevFrame;
if (!cam.read(prevFrame)) {
cerr << "Cannot read a frame from video stream" << endl;
return -1;
}
// initialize background subtraction algorithm
BackgroundSubtractorMOG2 bgsub;
bgsub.set("nmixtures", 3);
bgsub.set("detectShadows", false);
// loop frame by frame
while (1) {
Mat curFrame;
if (!cam.read(curFrame)) {
cerr << "Cannot read a frame from video stream" << endl;
break;
}
// create a zero array of same size as video capture
Mat dstFrame = Mat::zeros(curFrame.rows, curFrame.cols, CV_8UC1);
// display this frame without any changes
//imshow("UnchangedOutput", curFrame);
// display video with skin tones colored white
//mySkinDetect(curFrame, dstFrame);
imshow("UnchangedOutput", curFrame);
//Mat hull = drawHull(dstFrame);
bgsub.operator() (curFrame, dstFrame);
erode(dstFrame, dstFrame, Mat());
dilate(dstFrame, dstFrame, Mat());
imshow("SkinDetection", dstFrame);
// highlights pixels in this frame that are different from last frame
//myFrameDifferencing(prevFrame, curFrame, dstFrame);
//imshow("FrameDiff", dstFrame);
/*
// delete the oldest frame and add the newest frame
motionHist.erase(motionHist.begin());
motionHist.push_back(dstFrame);
Mat fMH = Mat::zeros(camHeight, camWidth, CV_8UC1);
myMotionEnergy(motionHist, fMH);
imshow("MotionHistory", fMH);
*/
// break loop if user hits key
if (waitKey(30) == 27) {
cout << "esc key is pressed by user" << endl;
break;
}
prevFrame = curFrame;
}
//waitKey(-1);
cam.release();
destroyWindow("UnchangedOutput");
destroyWindow("SkinDetection");
//destroyWindow("FrameDiff");
//destroyWindow("MotionHistory");
return 0;
}<commit_msg>commit<commit_after>#include "stdafx.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <opencv2/opencv.hpp>
#include "Utils.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
// open the webcam
VideoCapture cam(0);
if (!cam.isOpened()) {
cerr << "Camera failed to open" << endl;
return -1;
}
// get dims of video capture
int camHeight = static_cast<int>(cam.get(CV_CAP_PROP_FRAME_HEIGHT));
int camWidth = static_cast<int>(cam.get(CV_CAP_PROP_FRAME_WIDTH));
cout << camHeight << "x" << camWidth << endl;
// create window that shows the unchanged webcam output
namedWindow("UnchangedOutput", CV_WINDOW_AUTOSIZE);
//create window that shows skin detection
namedWindow("SkinDetection", WINDOW_AUTOSIZE);
// create window that show pixel diffs per frame
//namedWindow("FrameDiff", WINDOW_AUTOSIZE);
// create window that show motion energy history
//namedWindow("MotionHistory", WINDOW_AUTOSIZE);
#if 0
// initialize motion history vector
vector<Mat> motionHist;
Mat fMH1, fMH2, fMH3;
fMH1 = Mat::zeros(camHeight, camWidth, CV_8UC1);
fMH2 = fMH1.clone();
fMH3 = fMH1.clone();
motionHist.push_back(fMH1);
motionHist.push_back(fMH2);
motionHist.push_back(fMH3);
#endif
// read a single frame now to have a frame to compare
Mat prevFrame;
if (!cam.read(prevFrame)) {
cerr << "Cannot read a frame from video stream" << endl;
return -1;
}
// initialize background subtraction algorithm
BackgroundSubtractorMOG2 bgsub;
bgsub.set("nmixtures", 3);
bgsub.set("detectShadows", false);
// loop frame by frame
while (1) {
Mat curFrame;
if (!cam.read(curFrame)) {
cerr << "Cannot read a frame from video stream" << endl;
break;
}
// create a zero array of same size as video capture
Mat dstFrame = Mat::zeros(curFrame.rows, curFrame.cols, CV_8UC1);
Mat newFrame = Mat::zeros(curFrame.rows, curFrame.cols, CV_8UC1);
// display this frame without any changes
//imshow("UnchangedOutput", curFrame);
// display video with skin tones colored white
//mySkinDetect(curFrame, dstFrame);
imshow("UnchangedOutput", curFrame);
//Mat hull = drawHull(dstFrame);
// highlights pixels in this frame that are different from last frame
myFrameDifferencing(prevFrame, curFrame, dstFrame);
imshow("FrameDiff", dstFrame);
bgsub.operator() (dstFrame, newFrame);
imshow("Background Subtractor", newFrame);
erode(newFrame, newFrame, Mat());
dilate(newFrame, newFrame, Mat());
imshow("Erode dilate", newFrame);
/*
// delete the oldest frame and add the newest frame
motionHist.erase(motionHist.begin());
motionHist.push_back(dstFrame);
Mat fMH = Mat::zeros(camHeight, camWidth, CV_8UC1);
myMotionEnergy(motionHist, fMH);
imshow("MotionHistory", fMH);
*/
// break loop if user hits key
if (waitKey(30) == 27) {
cout << "esc key is pressed by user" << endl;
break;
}
prevFrame = curFrame;
}
//waitKey(-1);
cam.release();
destroyWindow("UnchangedOutput");
destroyWindow("SkinDetection");
//destroyWindow("FrameDiff");
//destroyWindow("MotionHistory");
return 0;
}<|endoftext|> |
<commit_before>#include "application.h"
#include "memory.h"
Application::Application()
{
memset(&m_callbacks, 0, sizeof(m_callbacks));
}
Application::~Application()
{
}
void Application::ManagerFunc()
{
std::vector<NotificationMessage*> messages;
{
CSLocker locker(&m_csMessages);
messages = m_messages;
m_messages.clear();
}
for(std::vector<NotificationMessage*>::iterator it = messages.begin();
it != messages.end(); it++)
{
(*it)->HandleMessage(m_callbacks);
delete *it;
}
}
void Application::ManagerStop()
{
{
CSLocker locker(&m_csModules);
for(std::vector<TwainetModule*>::iterator it = m_modules.begin(); it != m_modules.end();)
{
(*it)->Exit();
delete *it;
it = m_modules.erase(it);
}
}
{
CSLocker locker(&m_csMessages);
for(std::vector<NotificationMessage*>::iterator it = m_messages.begin(); it != m_messages.end();)
{
delete *it;
it = m_messages.erase(it);
}
}
}
void Application::Init(const Twainet::TwainetCallback& callback)
{
memcpy(&m_callbacks, &callback, sizeof(m_callbacks));
}
TwainetModule* Application::CreateModule(const Twainet::ModuleName& moduleName, bool isPPPListener)
{
CSLocker locker(&m_csModules);
TwainetModule* module = new TwainetModule(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix), isPPPListener);
m_modules.push_back(module);
return module;
}
void Application::DeleteModule(TwainetModule* module)
{
CSLocker locker(&m_csModules);
for(std::vector<TwainetModule*>::iterator it = m_modules.begin(); it != m_modules.end(); it++)
{
if(*it == module)
{
(*it)->Exit();
delete *it;
m_modules.erase(it);
return;
}
}
}
void Application::AddNotifycationMessage(NotificationMessage* message)
{
CSLocker locker(&m_csMessages);
m_messages.push_back(message);
}
<commit_msg>remove ppp library<commit_after>#include "application.h"
#include "memory.h"
Application::Application()
{
memset(&m_callbacks, 0, sizeof(m_callbacks));
}
Application::~Application()
{
}
void Application::ManagerFunc()
{
std::vector<NotificationMessage*> messages;
{
CSLocker locker(&m_csMessages);
messages = m_messages;
m_messages.clear();
}
for(std::vector<NotificationMessage*>::iterator it = messages.begin();
it != messages.end(); it++)
{
(*it)->HandleMessage(m_callbacks);
delete *it;
}
}
void Application::ManagerStop()
{
{
CSLocker locker(&m_csModules);
for(std::vector<TwainetModule*>::iterator it = m_modules.begin(); it != m_modules.end();)
{
(*it)->Exit();
delete *it;
it = m_modules.erase(it);
}
}
{
CSLocker locker(&m_csMessages);
for(std::vector<NotificationMessage*>::iterator it = m_messages.begin(); it != m_messages.end();)
{
delete *it;
it = m_messages.erase(it);
}
}
}
void Application::Init(const Twainet::TwainetCallback& callback)
{
memcpy(&m_callbacks, &callback, sizeof(m_callbacks));
}
TwainetModule* Application::CreateModule(const Twainet::ModuleName& moduleName)
{
CSLocker locker(&m_csModules);
TwainetModule* module = new TwainetModule(IPCObjectName(moduleName.m_name, moduleName.m_host, moduleName.m_suffix));
m_modules.push_back(module);
return module;
}
void Application::DeleteModule(TwainetModule* module)
{
CSLocker locker(&m_csModules);
for(std::vector<TwainetModule*>::iterator it = m_modules.begin(); it != m_modules.end(); it++)
{
if(*it == module)
{
(*it)->Exit();
delete *it;
m_modules.erase(it);
return;
}
}
}
void Application::AddNotifycationMessage(NotificationMessage* message)
{
CSLocker locker(&m_csMessages);
m_messages.push_back(message);
}
<|endoftext|> |
<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#pragma once
#ifndef PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
#define PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
#include <mutex> // std::mutex, std::scoped_lock, std::lock_guard.
#include <deque> // std::deque.
#include <utility> // std::move, std::swap.
// In System library MUST NOT use any another library because it is a core library.
namespace analyzer::common::types
{
/**
* @class LockedDeque LockedDeque.hpp "include/analyzer/LockedDeque.hpp"
* @brief This class defined concurrency wrapper over STL deque class to work in parallel threads.
* @tparam [in] Type - Typename of stored data in STL deque.
*
* @note This deque container if type-protected.
*
* @todo Set the global limit for adding new values to the deque.
*/
template <typename Type>
class LockedDeque
{
private:
/**
* @var std::mutex mutex;
* @brief A mutex value for thread-safe program working.
*/
std::mutex mutex = { };
/**
* @var std::deque<Type> deque;
* @brief STL deque for stored data;
*/
std::deque<Type> deque = { };
public:
/**
* @fn LockedDeque::LockedDeque(void) noexcept(true/false);
* @brief Default constructor.
*/
LockedDeque(void) noexcept(std::is_nothrow_default_constructible_v<std::deque<Type>>) = default;
/**
* @fn LockedDeque::~LockedDeque(void) noexcept;
* @brief Default destructor.
*/
~LockedDeque(void) noexcept = default;
/**
* @fn LockedDeque::LockedDeque (const LockedDeque<Type> &) noexcept(true/false);
* @brief Copy assignment constructor with LockedDeque<Type>.
* @tparam [in] other - The const reference of copied LockedDeque<Type>.
*/
LockedDeque (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>)
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = other.deque;
}
/**
* @fn explicit LockedDeque::LockedDeque (const std::deque<Type> &) noexcept(true/false);
* @brief Copy assignment constructor with STL std::deque<Type>.
* @tparam [in] other - The const reference of copied STL std::deque<Type>.
*/
explicit LockedDeque (const std::deque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>)
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = other;
}
/**
* @fn LockedDeque::LockedDeque (const LockedDeque<Type> &) noexcept;
* @brief Move assignment constructor with LockedDeque<Type>.
* @tparam [in] other - The rvalue reference of moved LockedDeque<Type>.
*/
LockedDeque (LockedDeque<Type>&& other) noexcept
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = std::move(other.deque);
}
/**
* @fn explicit LockedDeque::LockedDeque (const std::deque<Type> &) noexcept;
* @brief Move assignment constructor with STL std::deque<Type>.
* @tparam [in] other - The rvalue reference of moved STL std::deque<Type>.
*/
explicit LockedDeque (std::deque<Type>&& other) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = std::move(other);
}
/**
* @fn LockedDeque<Type> & LockedDeque::operator= (const LockedDeque<Type> &) noexcept(true/false);
* @brief Copy assignment operator.
* @tparam [in] other - The const reference of copied LockedDeque<Type> class.
* @return Reference of the current LockedDeque<Type> class.
*/
LockedDeque<Type>& operator= (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_assignable_v<std::deque<Type>>)
{
if (this != &other)
{
try { std::scoped_lock lock{mutex, other.mutex}; }
catch (const std::system_error& /*err*/) {
return *this;
}
deque = other.deque;
}
return *this;
}
/**
* @fn LockedDeque<Type> & LockedDeque::operator= (LockedDeque<Type> &&) noexcept;
* @brief Move assignment operator.
* @tparam [in] other - The rvalue reference of moved LockedDeque<Type> class.
* @return Reference of the current LockedDeque<Type> class.
*/
LockedDeque<Type>& operator= (LockedDeque<Type>&& other) noexcept
{
if (this != &other)
{
try { std::scoped_lock lock{mutex, other.mutex}; }
catch (const std::system_error& /*err*/) {
return *this;
}
deque = std::move(other.deque);
}
return *this;
}
/**
* @fn std::size_t LockedDeque::Size(void) noexcept;
* @brief Method that returns the size of deque.
* @return Size of deque.
*/
std::size_t Size(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return 0;
}
return deque.size();
}
/**
* @fn bool LockedDeque::IsEmpty(void) noexcept;
* @brief Method that returns the internal state of deque.
* @return State of deque.
*/
bool IsEmpty(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
return deque.empty();
}
/**
* @fn bool LockedDeque::Push (const Type &) noexcept;
* @brief Method that push new value to front of deque.
* @tparam [in] value - New value for insert.
* @return True - if push is successful, otherwise - false.
*/
bool Push (const Type& value) noexcept
{
try {
std::lock_guard<std::mutex> lock { mutex };
deque.emplace_front(value);
}
catch (const std::exception& /*err*/) {
return false;
}
return true;
}
/**
* @fn bool LockedDeque::PopBack (Type &) noexcept;
* @brief Method that pop value from back of deque.
* @tparam [out] result - Returned value.
* @return True - if pop is successful, otherwise - false.
*/
bool PopBack (Type& result) noexcept
{
try {
std::lock_guard<std::mutex> lock { mutex };
if (deque.empty() == true) {
return false;
}
result = deque.back();
deque.pop_back();
}
catch (const std::exception& /*err*/) {
return false;
}
return true;
}
/**
* @fn bool LockedDeque::PopFront (Type &) noexcept;
* @brief Method that pop value from front of deque.
* @tparam [out] result - Returned value.
* @return True - if pop is successful, otherwise - false.
*/
bool PopFront (Type& result) noexcept
{
try {
std::lock_guard<std::mutex> lock { mutex };
if (deque.empty() == true) {
return false;
}
result = deque.begin();
deque.pop_front();
}
catch (const std::exception& /*err*/) {
return false;
}
return true;
}
/**
* @fn bool LockedDeque::Move (std::deque<Type> &) noexcept;
* @brief Method that moves all internal values to outside STL std::deque<Type>.
* @tparam [out] result - Returned value.
* @return True - if move is successful, otherwise - false.
*/
bool Move (std::deque<Type>& result) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
if (deque.empty() == true) {
return false;
}
result = std::move(deque);
return true;
}
/**
* @fn bool LockedDeque::Swap (LockedDeque<Type> &) noexcept;
* @brief Method that swaps internal value with outside LockedDeque<Type> object.
* @tparam [in,out] other - Swapped value reference.
* @return True - if swap is successful, otherwise - false.
*/
bool Swap (LockedDeque<Type>& other) noexcept
{
if (this != &other)
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
std::swap(deque, other.deque);
}
return true;
}
/**
* @fn bool LockedDeque::Swap (std::deque<Type> &) noexcept;
* @brief Method that swaps internal value with outside STL std::deque<Type>.
* @tparam [in,out] other - Swapped value reference.
* @return True - if swap is successful, otherwise - false.
*/
bool Swap (std::deque<Type>& other) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
std::swap(deque, other);
return true;
}
/**
* @fn bool LockedDeque::Clear(void) noexcept;
* @brief Method that clears the deque.
* @return True - if clear is successful, otherwise - false.
*/
bool Clear(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
deque.clear();
return true;
}
};
} // namespace types.
#endif // PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
<commit_msg>[LIB] Improvement LockedDeque library.<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#pragma once
#ifndef PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
#define PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
#include <mutex> // std::mutex, std::scoped_lock, std::lock_guard.
#include <deque> // std::deque.
#include <utility> // std::move, std::swap.
// In System library MUST NOT use any another library because it is a core library.
namespace analyzer::common::types
{
/**
* @class LockedDeque LockedDeque.hpp "include/analyzer/LockedDeque.hpp"
* @brief This class defined concurrency wrapper over STL deque class to work in parallel threads.
* @tparam [in] Type - Typename of stored data in STL deque.
*
* @note This deque container if type-protected and provides a convenient RAII-style mechanism.
*
* @todo Set the global limit for adding new values to the deque.
*/
template <typename Type>
class LockedDeque
{
private:
/**
* @var std::mutex mutex;
* @brief A mutex value for thread-safe program working.
*/
std::mutex mutex = { };
/**
* @var std::deque<Type> deque;
* @brief STL deque for stored data;
*/
std::deque<Type> deque = { };
public:
/**
* @fn LockedDeque::LockedDeque(void) noexcept(true/false);
* @brief Default constructor.
*
* @throw std::bad_alloc - In case when do not system memory to allocate the storage.
*/
LockedDeque(void) noexcept(std::is_nothrow_default_constructible_v<std::deque<Type>>) = default;
/**
* @fn LockedDeque::~LockedDeque(void) noexcept;
* @brief Default destructor.
*/
~LockedDeque(void) noexcept = default;
/**
* @fn LockedDeque::LockedDeque (const LockedDeque<Type> &) noexcept(true/false);
* @brief Copy assignment constructor with LockedDeque<Type>.
* @tparam [in] other - The const reference of copied LockedDeque<Type>.
*
* @throw std::bad_alloc - In case when do not system memory to allocate the storage.
*/
LockedDeque (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>)
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = other.deque;
}
/**
* @fn explicit LockedDeque::LockedDeque (const std::deque<Type> &) noexcept(true/false);
* @brief Copy assignment constructor with STL std::deque<Type>.
* @tparam [in] other - The const reference of copied STL std::deque<Type>.
*
* @throw std::bad_alloc - In case when do not system memory to allocate the storage.
*/
explicit LockedDeque (const std::deque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>)
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = other;
}
/**
* @fn LockedDeque::LockedDeque (const LockedDeque<Type> &) noexcept;
* @brief Move assignment constructor with LockedDeque<Type>.
* @tparam [in] other - The rvalue reference of moved LockedDeque<Type>.
*/
LockedDeque (LockedDeque<Type>&& other) noexcept
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = std::move(other.deque);
}
/**
* @fn explicit LockedDeque::LockedDeque (const std::deque<Type> &) noexcept;
* @brief Move assignment constructor with STL std::deque<Type>.
* @tparam [in] other - The rvalue reference of moved STL std::deque<Type>.
*/
explicit LockedDeque (std::deque<Type>&& other) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return;
}
deque = std::move(other);
}
/**
* @fn LockedDeque<Type> & LockedDeque::operator= (const LockedDeque<Type> &) noexcept(true/false);
* @brief Copy assignment operator.
* @tparam [in] other - The const reference of copied LockedDeque<Type> class.
* @return Reference of the current LockedDeque<Type> class.
*
* @throw std::bad_alloc - In case when do not system memory to allocate the storage.
*/
LockedDeque<Type>& operator= (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_assignable_v<std::deque<Type>>)
{
if (this != &other)
{
try { std::scoped_lock lock{mutex, other.mutex}; }
catch (const std::system_error& /*err*/) {
return *this;
}
deque = other.deque;
}
return *this;
}
/**
* @fn LockedDeque<Type> & LockedDeque::operator= (LockedDeque<Type> &&) noexcept;
* @brief Move assignment operator.
* @tparam [in] other - The rvalue reference of moved LockedDeque<Type> class.
* @return Reference of the current LockedDeque<Type> class.
*/
LockedDeque<Type>& operator= (LockedDeque<Type>&& other) noexcept
{
if (this != &other)
{
try { std::scoped_lock lock{mutex, other.mutex}; }
catch (const std::system_error& /*err*/) {
return *this;
}
deque = std::move(other.deque);
}
return *this;
}
/**
* @fn std::size_t LockedDeque::Size(void) noexcept;
* @brief Method that returns the size of deque.
* @return Size of deque.
*/
std::size_t Size(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return 0;
}
return deque.size();
}
/**
* @fn bool LockedDeque::IsEmpty(void) noexcept;
* @brief Method that returns the internal state of deque.
* @return True - if the container size is 0, otherwise - false.
*/
bool IsEmpty(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
return deque.empty();
}
/**
* @fn bool LockedDeque::Push (const Type &) noexcept;
* @brief Method that push new value to front of deque.
* @tparam [in] value - New value for insert.
* @return True - if push is successful, otherwise - false.
*/
bool Push (const Type& value) noexcept
{
try {
std::lock_guard<std::mutex> lock { mutex };
deque.push_front(value);
}
catch (const std::exception& /*err*/) {
return false;
}
return true;
}
/**
* @fn bool LockedDeque::PopBack (Type &) noexcept;
* @brief Method that pop value from back of deque.
* @tparam [out] result - Returned value.
* @return True - if pop back element is successful, otherwise - false.
*
* @note Use this method for pop the oldest value in the deque.
*/
bool PopBack (Type& result) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::exception& /*err*/) {
return false;
}
if (deque.empty() == true) {
return false;
}
result = deque.back();
deque.pop_back();
return true;
}
/**
* @fn bool LockedDeque::PopFront (Type &) noexcept;
* @brief Method that pop value from front of deque.
* @tparam [out] result - Returned value.
* @return True - if pop the front element is successful, otherwise - false.
*/
bool PopFront (Type& result) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
if (deque.empty() == true) {
return false;
}
result = deque.front();
deque.pop_front();
return true;
}
/**
* @fn bool LockedDeque::Move (std::deque<Type> &) noexcept;
* @brief Method that moves all internal values to outside STL std::deque<Type>.
* @tparam [out] result - Returned value.
* @return True - if at least 1 element has been moved, otherwise - false.
*/
bool Move (std::deque<Type>& result) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
if (deque.empty() == true) {
return false;
}
result = std::move(deque);
return true;
}
/**
* @fn bool LockedDeque::Swap (LockedDeque<Type> &) noexcept;
* @brief Method that swaps internal value with outside LockedDeque<Type> object.
* @tparam [in,out] other - Swapped value reference.
* @return True - if swap is successful, otherwise - false.
*/
bool Swap (LockedDeque<Type>& other) noexcept
{
if (this != &other)
{
try { std::scoped_lock lock { mutex, other.mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
std::swap(deque, other.deque);
}
return true;
}
/**
* @fn bool LockedDeque::Swap (std::deque<Type> &) noexcept;
* @brief Method that swaps internal value with outside STL std::deque<Type>.
* @tparam [in,out] other - Swapped value reference.
* @return True - if swap is successful, otherwise - false.
*/
bool Swap (std::deque<Type>& other) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
std::swap(deque, other);
return true;
}
/**
* @fn bool LockedDeque::Clear(void) noexcept;
* @brief Method that clears the deque.
* @return True - if clear is successful, otherwise - false.
*/
bool Clear(void) noexcept
{
try { std::lock_guard<std::mutex> lock { mutex }; }
catch (const std::system_error& /*err*/) {
return false;
}
deque.clear();
return true;
}
};
} // namespace types.
#endif // PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP
<|endoftext|> |
<commit_before>#include <SFML/Graphics.hpp>
#include "Main.h"
#include "TextureLoader.h"
int main(){
sf::RenderWindow window(sf::VideoMode(MAIN_WINDOW_WIDTH,
MAIN_WINDOW_HEIGHT), MAIN_NAME);
// Syncs framerate with monitor; should be ~60f/s.
// This helps avoid frame tearing.
window.setVerticalSyncEnabled(true);
sf::CircleShape shape(MAIN_WINDOW_WIDTH/2);
shape.setFillColor(sf::Color::Green);
bool green=true;
TextureLoader*tl = TextureLoader::getInstance();
tl->load();
// MAIN LOOP.
while(window.isOpen()){
//================================
// Handle events
sf::Event event;
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::LostFocus)
green = false;
if (event.type == sf::Event::GainedFocus)
green = true;
}
//================================
// Set things up to be drawn
shape.setFillColor(green ? sf::Color::Green : sf::Color::Blue);
sf::Sprite sprite;
sprite.setTexture(TextureLoader::getInstance()->
getByName(std::string("")));
//================================
// Draw everything
window.clear();
window.draw(shape);
window.draw(sprite);
window.display();
}
return 0;
}
<commit_msg>[restating] Worked more on TextureLoader. There's still a weird issue with `new' apparently blocking indefinitely.<commit_after>#include <SFML/Graphics.hpp>
#include "Main.h"
#include "TextureLoader.h"
int main(){
sf::RenderWindow window(sf::VideoMode(MAIN_WINDOW_WIDTH,
MAIN_WINDOW_HEIGHT), MAIN_NAME);
// Syncs framerate with monitor; should be ~60f/s.
// This helps avoid frame tearing.
window.setVerticalSyncEnabled(true);
sf::CircleShape shape(MAIN_WINDOW_WIDTH/2);
shape.setFillColor(sf::Color::Green);
bool green=true;
TextureLoader*tl = TextureLoader::getInstance();
tl->load();
// MAIN LOOP.
while(window.isOpen()){
//================================
// Handle events
sf::Event event;
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::LostFocus)
green = false;
if (event.type == sf::Event::GainedFocus)
green = true;
}
//================================
// Set things up to be drawn
shape.setFillColor(green ? sf::Color::Green : sf::Color::Blue);
sf::Sprite sprite;
sprite.setTexture(TextureLoader::getInstance()->getByName(std::string("")));
//================================
// Draw everything
window.clear();
window.draw(shape);
window.draw(sprite);
window.display();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "general.hpp"
#include "course.hpp"
#include "student.hpp"
using namespace std;
vector<Course> all_courses;
Student user;
void loadCourses(string filename) {
ifstream infile(filename.c_str());
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
}
for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
if (c->getProfessor()[1] == ' ')
if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
cout << *c << endl;
}
void readData() {
loadCourses("data/2012-13-s2.csv");
loadCourses("data/2012-13-interim.csv");
loadCourses("data/2012-13-s1.csv");
loadCourses("data/2011-12-s2.csv");
loadCourses("data/2011-12-interim.csv");
loadCourses("data/2011-12-s1.csv");
loadCourses("data/2010-11-s2.csv");
loadCourses("data/2010-11-interim.csv");
loadCourses("data/2010-11-s1.csv");
}
void welcome() {
string name, yearS = "", yearE = "", majors;
cout << "Welcome!" << endl;
cout << "What is your name? ";
getline(cin, name);
cout << "What year do you graduate? ";
getline(cin, yearE);
cout << "What are your majors (ex. CSCI, ASIAN) ";
getline(cin, majors);
user = Student(name, yearS, yearE, majors);
}
void requestCourses() {
string courses;
cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
getline(cin, courses);
user.addCourses(courses);
}
int main(int argc, const char *argv[]) {
readData();
// Method 1: Dynamic.
// welcome();
// requestCourses();
// Method 2: Hard-coded file path.
user = Student("data/user.txt");
// Method 3: File path as an argument.
// Student user(argv[1]);
user.updateStanding();
user.display();
// Major m("MATH");
// ID id("Math 120");
// ID xd = id;
// bool i = ID("CSCI251") == ID("CSCI 251");
// cout << i << endl;
// cout << "Question: Has the user taken CSCI 251? ";
// cout << user.hasTakenCourse("csci251") << endl;
return 0;
}
<commit_msg>Add a commented-out cout for incourse<commit_after>#include "general.hpp"
#include "course.hpp"
#include "student.hpp"
using namespace std;
vector<Course> all_courses;
Student user;
void loadCourses(string filename) {
ifstream infile(filename.c_str());
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
// cout << incourse << endl;
}
for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
if (c->getProfessor()[1] == ' ')
if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
cout << *c << endl;
}
void readData() {
loadCourses("data/2012-13-s2.csv");
loadCourses("data/2012-13-interim.csv");
loadCourses("data/2012-13-s1.csv");
loadCourses("data/2011-12-s2.csv");
loadCourses("data/2011-12-interim.csv");
loadCourses("data/2011-12-s1.csv");
loadCourses("data/2010-11-s2.csv");
loadCourses("data/2010-11-interim.csv");
loadCourses("data/2010-11-s1.csv");
}
void welcome() {
string name, yearS = "", yearE = "", majors;
cout << "Welcome!" << endl;
cout << "What is your name? ";
getline(cin, name);
cout << "What year do you graduate? ";
getline(cin, yearE);
cout << "What are your majors (ex. CSCI, ASIAN) ";
getline(cin, majors);
user = Student(name, yearS, yearE, majors);
}
void requestCourses() {
string courses;
cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
getline(cin, courses);
user.addCourses(courses);
}
int main(int argc, const char *argv[]) {
readData();
// Method 1: Dynamic.
// welcome();
// requestCourses();
// Method 2: Hard-coded file path.
user = Student("data/user.txt");
// Method 3: File path as an argument.
// Student user(argv[1]);
user.updateStanding();
user.display();
// Major m("MATH");
// ID id("Math 120");
// ID xd = id;
// bool i = ID("CSCI251") == ID("CSCI 251");
// cout << i << endl;
// cout << "Question: Has the user taken CSCI 251? ";
// cout << user.hasTakenCourse("csci251") << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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 <QtGui/QApplication>
#include <QtGui/QPlastiqueStyle>
#include "Gui/MainWind.h"
int main(int argc, char *argv[])
{ /* // experimental GL backend for all widgets
#ifndef QT_NO_OPENGL
QApplication::setGraphicsSystem("opengl");
#endif*/
QApplication a(argc, argv);
MainWind w;
w.show();
return a.exec();
}
<commit_msg>Add docs to src/Main.cpp.<commit_after>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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.
*/
/****h* RagingMidi/Main.cpp
* PURPOSE
* Initializer for Raging MIDI. Creates the
* QApplication and MainWind objects.
******
*/
#include <QtGui/QApplication>
#include <QtGui/QPlastiqueStyle>
#include "Gui/MainWind.h"
int main(int argc, char *argv[])
{ /* // experimental GL backend for all widgets
#ifndef QT_NO_OPENGL
QApplication::setGraphicsSystem("opengl");
#endif*/
QApplication a(argc, argv);
MainWind w;
w.show();
return a.exec();
}
<|endoftext|> |
<commit_before>#include <lv.h>
using namespace std;
int main(int argc, char** argv)
{
// BLAS
var bt;
bt = 1.0f, 1.2f, 0.8f, -2.0f;
cout << bt << " sums to " << lv::sum(bt) << endl;
cout << bt << " asums to " << lv::asum(bt) << endl;
// Broadcasting scalars
var t1 = lv::irange(16.0f).view({4, 4});
t1(1,2) = 2.3f;
t1 += 1;
cout << "t1: " << t1 << endl;
t1 *= 1.5;
cout << "t1: " << t1 << endl;
t1 += t1;
cout << "t1: " << t1 << endl;
t1 -= t1 - 1;
cout << "t1: " << t1 << endl;
// Sub-views
var r12 = lv::irange(0.1, 12.1);
cout << "r12: " << r12 << endl;
var sv = r12.view({4}, 4);
cout << "sv: " << sv << endl;
cout << "sv(0): " << sv(0) << endl;
sv += 1;
cout << "r12: " << r12 << endl;
var rv;
rv = -1.0, -2.0, -3.0, -4.0;
cout << "rv: " << rv << endl;
sv.offset(8);
sv = rv;
cout << "r12: " << r12 << endl;
// Broadcasting tensors
var r6 = lv::irange(6.0).view({3,2});
var r2;
r2 = 1.0, 2.0;
cout << "r2: " << r2 << endl;
cout << "r6: " << r6 << endl;
r6 += r2;
cout << "r6: " << r6 << endl;
r6 *= r2;
cout << "r6: " << r6 << endl;
cout << "r6*r6: " << r6 * r6 << endl;
// View of a view
var r3 = r6.view({2}, 0);
var r4 = sv.view({2}, 0);
cout << "r3: " << r3 << endl;
cout << "r4: " << r4 << endl;
// Functors
cout << "Size: " << sizeof(lv::Pow) << endl;
cout << "Pow: " << lv::pow(3.0, 2) << endl;
cout << "Pow: " << lv::pow(r6, 2) << endl;
cout << "Tan: " << lv::tan(r6) << endl;
// Transpose
cout << "oTranspose:\n" << lv::transpose(r6) << endl << r6 << endl;
cout << "iTranspose:\n" << r6.transpose() << endl << r6 << endl;
// Dot
var rd;
rd = 2.0, 2.0, 2.0;
var rd6 = lv::dot(r6, rd);
cout << "Dot: " << rd6 << endl;
// DFT
var td = lv::view({2, 10});
var fd;
for (int i=0; i<10; i++)
{
td(0, i) = sinf(i);
td(1, i) = cosf(i);
}
cout << "Time: " << td << endl;
lv::DFT dft(10);
fd = dft(td);
cout << "Freq: " << fd << endl;
var ab = lv::abs(fd);
cout << "Abs: " << ab << endl;
var im = lv::iamax(fd);
cout << "IAMax: " << im << endl;
// Done
return 0;
}
<commit_msg>Test the easier functor vector()<commit_after>#include <lv.h>
using namespace std;
// A test functor
class Unary : public lv::UnaryFunctor
{
public:
Unary() { mDim = 1; };
protected:
void vector(var iVar, var& oVar) const;
};
void Unary::vector(var iVar, var& oVar) const
{
for (int i=0; i<iVar.size(); i++)
oVar[i] = iVar[iVar.size()-1-i];
cout << "Unary: I: " << iVar.shape() << " " << iVar << endl;
cout << "Unary: O: " << oVar.shape() << " " << oVar << endl;
}
int main(int argc, char** argv)
{
// BLAS
var bt;
bt = 1.0f, 1.2f, 0.8f, -2.0f;
cout << bt << " sums to " << lv::sum(bt) << endl;
cout << bt << " asums to " << lv::asum(bt) << endl;
// Broadcasting scalars
var t1 = lv::irange(16.0f).view({4, 4});
t1(1,2) = 2.3f;
t1 += 1;
cout << "t1: " << t1 << endl;
t1 *= 1.5;
cout << "t1: " << t1 << endl;
t1 += t1;
cout << "t1: " << t1 << endl;
t1 -= t1 - 1;
cout << "t1: " << t1 << endl;
// Sub-views
var r12 = lv::irange(0.1, 12.1);
cout << "r12: " << r12 << endl;
var sv = r12.view({4}, 4);
cout << "sv: " << sv << endl;
cout << "sv(0): " << sv(0) << endl;
sv += 1;
cout << "r12: " << r12 << endl;
var rv;
rv = -1.0, -2.0, -3.0, -4.0;
cout << "rv: " << rv << endl;
sv.offset(8);
sv = rv;
cout << "r12: " << r12 << endl;
// Broadcasting tensors
var r6 = lv::irange(6.0).view({3,2});
var r2;
r2 = 1.0, 2.0;
cout << "r2: " << r2 << endl;
cout << "r6: " << r6 << endl;
r6 += r2;
cout << "r6: " << r6 << endl;
r6 *= r2;
cout << "r6: " << r6 << endl;
cout << "r6*r6: " << r6 * r6 << endl;
// View of a view
var r3 = r6.view({2}, 0);
var r4 = sv.view({2}, 0);
cout << "r3: " << r3 << endl;
cout << "r4: " << r4 << endl;
// Functors
cout << "Size: " << sizeof(lv::Pow) << endl;
cout << "Pow: " << lv::pow(3.0, 2) << endl;
cout << "Pow: " << lv::pow(r6, 2) << endl;
cout << "Tan: " << lv::tan(r6) << endl;
// Transpose
cout << "oTranspose:\n" << lv::transpose(r6) << endl << r6 << endl;
cout << "iTranspose:\n" << r6.transpose() << endl << r6 << endl;
// Dot
var rd;
rd = 2.0, 2.0, 2.0;
var rd6 = lv::dot(r6, rd);
cout << "Dot: " << rd6 << endl;
// DFT
var td = lv::view({2, 10});
var fd;
for (int i=0; i<10; i++)
{
td(0, i) = sinf(i);
td(1, i) = cosf(i);
}
cout << "Time: " << td << endl;
lv::DFT dft(10);
fd = dft(td);
cout << "Freq: " << fd << endl;
var ab = lv::abs(fd);
cout << "Abs: " << ab << endl;
var im = lv::iamax(fd);
cout << "IAMax: " << im << endl;
// Functor view broadcast
Unary u;
cout << u(r6) << endl;
// Done
return 0;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include "ChunkSet.h"
template <typename T>
auto ChunkSet<T>::getIter(const Int2 &point, const ChunkList &chunks)
{
const auto iter = std::find_if(this->chunks.begin(), this->chunks.end(),
[&point](const auto &pair)
{
return pair.first == point;
});
return iter;
}
template <typename T>
auto ChunkSet<T>::getIter(const Int2 &point, const ChunkList &chunks) const
{
const auto iter = std::find_if(this->chunks.begin(), this->chunks.end(),
[&point](const auto &pair)
{
return pair.first == point;
});
return iter;
}
template<typename T>
int ChunkSet<T>::getCount() const
{
return static_cast<int>(this->chunks.size());
}
template <typename T>
T *ChunkSet<T>::get(const Int2 &point)
{
const auto iter = this->getIter(point, this->chunks);
return (iter != this->chunks.end()) ? &iter->second : nullptr;
}
template <typename T>
const T *ChunkSet<T>::get(const Int2 &point) const
{
const auto iter = this->getIter(point, this->chunks);
return (iter != this->chunks.end()) ? &iter->second : nullptr;
}
template <typename T>
typename ChunkSet<T>::PairType *ChunkSet<T>::getAt(int index)
{
return (index < this->getCount()) ? &this->chunks.at(index) : nullptr;
}
template <typename T>
typename const ChunkSet<T>::PairType *ChunkSet<T>::getAt(int index) const
{
return (index < this->getCount()) ? &this->chunks.at(index) : nullptr;
}
template <typename T>
void ChunkSet<T>::set(const Int2 &point, const T &chunk)
{
const auto iter = this->getIter(point, this->chunks);
// Add if it doesn't exist, overwrite if it does.
const bool exists = iter != this->chunks.end();
if (exists)
{
*iter = std::make_pair(point, chunk);
}
else
{
this->chunks.push_back(std::make_pair(point, chunk));
}
}
template <typename T>
void ChunkSet<T>::set(const Int2 &point, T &&chunk)
{
const auto iter = this->getIter(point, this->chunks);
// Add if it doesn't exist, overwrite if it does.
const bool exists = iter != this->chunks.end();
if (exists)
{
*iter = std::make_pair(point, std::move(chunk));
}
else
{
this->chunks.push_back(std::make_pair(point, std::move(chunk)));
}
}
template<typename T>
void ChunkSet<T>::remove(const Int2 &point)
{
const auto iter = this->getIter(point, this->chunks);
// Remove if the chunk exists.
const bool exists = iter != this->chunks.end();
if (exists)
{
this->chunks.erase(iter);
}
}
// Template instantiations.
template class ChunkSet<InteriorChunk>;
template class ChunkSet<ExteriorChunk>;
<commit_msg>Forgot to remove typename keywords in ChunkSet.cpp.<commit_after>#include <algorithm>
#include "ChunkSet.h"
template <typename T>
auto ChunkSet<T>::getIter(const Int2 &point, const ChunkList &chunks)
{
const auto iter = std::find_if(this->chunks.begin(), this->chunks.end(),
[&point](const auto &pair)
{
return pair.first == point;
});
return iter;
}
template <typename T>
auto ChunkSet<T>::getIter(const Int2 &point, const ChunkList &chunks) const
{
const auto iter = std::find_if(this->chunks.begin(), this->chunks.end(),
[&point](const auto &pair)
{
return pair.first == point;
});
return iter;
}
template <typename T>
int ChunkSet<T>::getCount() const
{
return static_cast<int>(this->chunks.size());
}
template <typename T>
T *ChunkSet<T>::get(const Int2 &point)
{
const auto iter = this->getIter(point, this->chunks);
return (iter != this->chunks.end()) ? &iter->second : nullptr;
}
template <typename T>
const T *ChunkSet<T>::get(const Int2 &point) const
{
const auto iter = this->getIter(point, this->chunks);
return (iter != this->chunks.end()) ? &iter->second : nullptr;
}
template <typename T>
ChunkSet<T>::PairType *ChunkSet<T>::getAt(int index)
{
return (index < this->getCount()) ? &this->chunks.at(index) : nullptr;
}
template <typename T>
const ChunkSet<T>::PairType *ChunkSet<T>::getAt(int index) const
{
return (index < this->getCount()) ? &this->chunks.at(index) : nullptr;
}
template <typename T>
void ChunkSet<T>::set(const Int2 &point, const T &chunk)
{
const auto iter = this->getIter(point, this->chunks);
// Add if it doesn't exist, overwrite if it does.
const bool exists = iter != this->chunks.end();
if (exists)
{
*iter = std::make_pair(point, chunk);
}
else
{
this->chunks.push_back(std::make_pair(point, chunk));
}
}
template <typename T>
void ChunkSet<T>::set(const Int2 &point, T &&chunk)
{
const auto iter = this->getIter(point, this->chunks);
// Add if it doesn't exist, overwrite if it does.
const bool exists = iter != this->chunks.end();
if (exists)
{
*iter = std::make_pair(point, std::move(chunk));
}
else
{
this->chunks.push_back(std::make_pair(point, std::move(chunk)));
}
}
template <typename T>
void ChunkSet<T>::remove(const Int2 &point)
{
const auto iter = this->getIter(point, this->chunks);
// Remove if the chunk exists.
const bool exists = iter != this->chunks.end();
if (exists)
{
this->chunks.erase(iter);
}
}
// Template instantiations.
template class ChunkSet<InteriorChunk>;
template class ChunkSet<ExteriorChunk>;
<|endoftext|> |
<commit_before><commit_msg>Outlined cpp file for Companionship robot [#61]<commit_after>#include "ros/ros.h"
#include <unistd.h>
#include <sstream>
#include "std_msgs/Empty.h"
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Point.h>
#include <tf/tf.h>
#include <queue>
#include "EventTriggerUtility.h"
#include "PerformTaskConstants.h"
#include "elderly_care_simulation/EventTrigger.h"
#include "elderly_care_simulation/PerformTask.h"
#include "elderly_care_simulation/FindPath.h"
#include "Robot.h"
#include "Friend.h"
#include "Poi.h"
#include "StaticPoi.h"
#include "StaticPoiConstants.h"
/**
* This node represents an assistant robot for the purpose of
* providing companionship to the Resident. THe robot moves to
* the the POI, in this case the resident, to perform
* a predetermined action. This action represents the robot
* providing companionship such as connecting the resident
* to other beings via VoIP sofware (Skype).
*
* Author: Akshay Kalyan
*/
Companionship::Companionship() {
MY_TASK = EVENT_TRIGGER_EVENT_TYPE_COMPANIONSHIP;
performingTask = false;
currentLocationState = AT_HOME;
}
Companionship::~Companionship() {
}
/**
* Prompt Companionship robot to travel to the resident
*/
void Companionship::goToResident(const std_msgs::Empty) {
ROS_INFO("Companionship: Going to %f, %f", residentPoi.getLocation().x, residentPoi.getLocation().y);
goToLocation(residentPoi.getLocation());
currentLocationState = GOING_TO_RESIDENT;
}
/**
* Prompt Companionship robot to return back to its home POI
*/
void Companionship::goToHome(const std_msgs::Empty) {
goToLocation(homePoi.getLocation());
currentLocationState = GOING_HOME;
}
/**
* Publish successful completion of task notice destined
* for the scheduler
*/
void Companionship::eventTriggerReply() {
// Create response message
elderly_care_simulation::EventTrigger msg;
msg.msg_type = EVENT_TRIGGER_MSG_TYPE_RESPONSE;
msg.event_type = MY_TASK;
msg.event_priority = EVENT_TRIGGER_PRIORITY_UNDEFINED;
msg.event_weight = getEventWeight(msg.event_type);
msg.result = EVENT_TRIGGER_RESULT_SUCCESS;
eventTriggerPub.publish(msg);
ROS_INFO("Companionship: Reply Message Sent");
}
/**
* Perform task when a request is received. Callback executed
* when a message is received from the Scheduler
*/
void Companionship::eventTriggerCallback(elderly_care_simulation::EventTrigger msg)
{
if (msg.msg_type == EVENT_TRIGGER_MSG_TYPE_REQUEST) {
if (msg.event_type == MY_TASK) {
ROS_INFO("Companionship: Event Recieved: [%s]", eventTypeToString(MY_TASK));
performingTask = true;
std_msgs::Empty emptyMessage;
goToResident(emptyMessage);
}
}
}
/**
* Carry out task on the resident
*/
void Companionship::performTask() {
// Generate the service call
elderly_care_simulation::PerformTask performTaskSrv;
performTaskSrv.request.taskType = MY_TASK;
// Make the call using the client
if (!performTaskClient.call(performTaskSrv)) {
throw std::runtime_error("Companionship: Service call to the initiate task with Resident failed");
}
switch (performTaskSrv.response.result) {
case PERFORM_TASK_RESULT_ACCEPTED:
{
// Resident has accepted the task but isn't finished yet
startSpinning(false);
break;
}
case PERFORM_TASK_RESULT_FINISHED:
{
// Resident accepted the task and has had enough
performingTask = false;
std_msgs::Empty emptyMessage;
goToHome(emptyMessage);
stopSpinning();
eventTriggerReply();
break;
}
case PERFORM_TASK_RESULT_BUSY:
{
// Resident is busy, do nothing
break;
}
}
}
Companionship companionshipRobot;
// Callback functions
void callStage0domCallback(const nav_msgs::Odometry msg) {
companionshipRobot.stage0domCallback(msg);
}
void callUpdateDesiredLocationCallback(const geometry_msgs::Point location){
companionshipRobot.goToLocation(location);
}
void callEventTriggerCallback(elderly_care_simulation::EventTrigger msg){
companionshipRobot.eventTriggerCallback(msg);
}
void callGoToResident(const std_msgs::Empty empty){
ROS_INFO("Companionship: Going to Resident");
companionshipRobot.goToResident(empty);
}
void callGoToHome(const std_msgs::Empty empty){
ROS_INFO("Companionship: Going home");
companionshipRobot.goToHome(empty);
}
void updateResidentPositionCallback(const nav_msgs::Odometry msg) {
double x = msg.pose.pose.position.x;
double y = msg.pose.pose.position.y;
companionshipRobot.residentPoi = StaticPoi(x+1, y, 0);
}
int main(int argc, char **argv) {
// ROS initialiser calls
ros::init(argc, argv, "Companionship");
ros::NodeHandle nodeHandle;
ros::Rate loop_rate(25);
companionshipRobot = Companionship();
// Initialise publishers
companionshipRobot.robotNodeStagePub = nodeHandle.advertise<geometry_msgs::Twist>("robot_3/cmd_vel",1000);
companionshipRobot.eventTriggerPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger", 1000, true);
// Initialise subscribers
companionshipRobot.residentStageSub = nodeHandle.subscribe<nav_msgs::Odometry>("robot_0/base_pose_ground_truth",1000,
updateResidentPositionCallback);
companionshipRobot.stageOdoSub = nodeHandle.subscribe<nav_msgs::Odometry>("robot_3/base_pose_ground_truth",1000,
callStage0domCallback);
companionshipRobot.eventTriggerSub = nodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger",1000,
callEventTriggerCallback);
companionshipRobot.locationInstructionsSub = nodeHandle.subscribe<geometry_msgs::Point>("robot_3/location", 1000,
callUpdateDesiredLocationCallback);
companionshipRobot.pathToRobotSub = nodeHandle.subscribe<std_msgs::Empty>("robot_3/toResident", 1000, callGoToResident);
companionshipRobot.pathToHomeSub = nodeHandle.subscribe<std_msgs::Empty>("robot_3/toHome", 1000, callGoToHome);
// Create a client to make service requests to the Resident
companionshipRobot.performTaskClient = nodeHandle.serviceClient<elderly_care_simulation::PerformTask>("perform_task");
// Create a link to the pathfinding service
companionshipRobot.pathFinderService = nodeHandle.serviceClient<elderly_care_simulation::FindPath>("find_path");
while (ros::ok())
{
// Required for dynamic pathfinding
companionshipRobot.updateCurrentVelocity();
if (companionshipRobot.atDesiredLocation()){
if (companionshipRobot.currentLocationState == companionshipRobot.GOING_TO_RESIDENT) {
companionshipRobot.currentLocationState = companionshipRobot.AT_RESIDENT;
} else if (companionshipRobot.currentLocationState == companionshipRobot.GOING_HOME) {
companionshipRobot.currentLocationState = companionshipRobot.AT_HOME;
}
}
if ((companionshipRobot.currentLocationState == companionshipRobot.AT_RESIDENT) && companionshipRobot.performingTask) {
companionshipRobot.performTask();
}
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: targetstatecontrol.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2005-02-25 09:21:50 $
*
* 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/types.h>
#include <osl/diagnose.h>
class TargetStateControl_Impl
{
sal_Int32& m_nTargetStateVariable;
public:
TargetStateControl_Impl( sal_Int32& nVariable, sal_Int32 nValue )
: m_nTargetStateVariable( nVariable )
{
OSL_ENSURE( m_nTargetStateVariable == -1, "The target state variable is not initialized properly!\n" );
m_nTargetStateVariable = nValue;
}
~TargetStateControl_Impl()
{
m_nTargetStateVariable = -1;
}
};
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.42); FILE MERGED 2005/09/05 17:18:09 rt 1.2.42.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: targetstatecontrol.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:40:20 $
*
* 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/types.h>
#include <osl/diagnose.h>
class TargetStateControl_Impl
{
sal_Int32& m_nTargetStateVariable;
public:
TargetStateControl_Impl( sal_Int32& nVariable, sal_Int32 nValue )
: m_nTargetStateVariable( nVariable )
{
OSL_ENSURE( m_nTargetStateVariable == -1, "The target state variable is not initialized properly!\n" );
m_nTargetStateVariable = nValue;
}
~TargetStateControl_Impl()
{
m_nTargetStateVariable = -1;
}
};
<|endoftext|> |
<commit_before>/*************************************************
* Copyright © 2015, afr-consulting GmbH *
* *
* See the file COPYING for copying permissions. *
*************************************************/
#ifndef CXXUTILS_NONCOPYABLE_HXX
#define CXXUTILS_NONCOPYABLE_HXX
/**
* \file noncopyable.hxx
*
* \brief Parent class for noncopyable classes.
*
* This file contains the noncopyable class. Other classes
* can inherit its noncopyability.
*/
// Internal
#include <cxx11_features.hxx>
namespace cxxutils
{
/**
* \brief Parent class for noncopyable classes.
*
* A class can inherit from this class to become noncopyable.
*
* \note You must use \a private inheritance for this to work.
* \note The child class might still be movable.
*/
#if defined(CXX11_FEATURE_DEFAULTDELETE)
struct noncopyable
{
noncopyable() = default; ///< Default constructor.
virtual ~noncopyable() = default; ///< Default destructor.
noncopyable(noncopyable const &) = delete; ///< The deleted copy constructor.
noncopyable & operator = (noncopyable const &) = delete; ///< The deleted copy assignment operator.
};
#else // !CXX11_FEATURE_DEFAULTDELETE
struct noncopyable
{
noncopyable() {} ///< Default constructor.
virtual ~noncopyable() {} ///< Default destructor.
private:
noncopyable(noncopyable const &); ///< The deleted copy constructor.
noncopyable & operator = (noncopyable const &); ///< The deleted copy assignment operator.
};
#endif // CXX11_FEATURE_DEFAULTDELETE
}
#endif // CXXUTILS_NONCOPYABLE_HXX
<commit_msg>little adjustment<commit_after>/*************************************************
* Copyright © 2015, afr-consulting GmbH *
* *
* See the file COPYING for copying permissions. *
*************************************************/
#ifndef CXXUTILS_NONCOPYABLE_HXX
#define CXXUTILS_NONCOPYABLE_HXX
/**
* \file noncopyable.hxx
*
* \brief Parent class for noncopyable classes.
*
* This file contains the noncopyable class. Other classes
* can inherit its noncopyability.
*/
// Internal
#include <cxx11_features.hxx>
namespace cxxutils
{
/**
* \brief Parent class for noncopyable classes.
*
* A class can inherit from this class to become noncopyable.
*
* \note You must use \a private inheritance for this to work.
* \note The child class might still be movable.
*/
struct noncopyable
{
#if defined(CXX11_FEATURE_DEFAULTDELETE)
noncopyable() = default; ///< Default constructor.
virtual ~noncopyable() = default; ///< Default destructor.
noncopyable(noncopyable const &) = delete; ///< The deleted copy constructor.
noncopyable & operator = (noncopyable const &) = delete; ///< The deleted copy assignment operator.
#else // !CXX11_FEATURE_DEFAULTDELETE
noncopyable() {} ///< Default constructor.
virtual ~noncopyable() {} ///< Default destructor.
private:
noncopyable(noncopyable const &); ///< The deleted copy constructor.
noncopyable & operator = (noncopyable const &); ///< The deleted copy assignment operator.
#endif // CXX11_FEATURE_DEFAULTDELETE
};
}
#endif // CXXUTILS_NONCOPYABLE_HXX
<|endoftext|> |
<commit_before>/*
Copyright (C) 2013,2014 Wei Dong <wdong@wdong.org>. All Rights Reserved.
*/
#ifndef KGRAPH_VALUE_TYPE
#define KGRAPH_VALUE_TYPE float
#endif
#include <sys/time.h>
#include <cctype>
#include <random>
#include <iomanip>
#include <type_traits>
#include <boost/timer/timer.hpp>
#include <boost/tr1/random.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "kgraph.h"
#include "kgraph-data.h"
using namespace std;
using namespace boost;
using namespace boost::timer;
using namespace kgraph;
namespace po = boost::program_options;
typedef KGRAPH_VALUE_TYPE value_type;
int main (int argc, char *argv[]) {
string data_path;
string output_path;
KGraph::IndexParams params;
unsigned D;
unsigned skip;
unsigned gap;
unsigned synthetic;
float noise;
bool lshkit = true;
po::options_description desc_visible("General options");
desc_visible.add_options()
("help,h", "produce help message.")
("version,v", "print version information.")
("data", po::value(&data_path), "input path")
("output", po::value(&output_path), "output path")
(",K", po::value(¶ms.K)->default_value(default_K), "number of nearest neighbor")
("controls,C", po::value(¶ms.controls)->default_value(default_controls), "number of control pounsigneds")
;
po::options_description desc_hidden("Expert options");
desc_hidden.add_options()
("iterations,I", po::value(¶ms.iterations)->default_value(default_iterations), "")
(",S", po::value(¶ms.S)->default_value(default_S), "")
(",R", po::value(¶ms.R)->default_value(default_R), "")
(",L", po::value(¶ms.L)->default_value(default_L), "")
("delta", po::value(¶ms.delta)->default_value(default_delta), "")
("recall", po::value(¶ms.recall)->default_value(default_recall), "")
("prune", po::value(¶ms.prune)->default_value(default_prune), "")
("reverse", po::value(¶ms.reverse)->default_value(default_reverse), "")
("noise", po::value(&noise)->default_value(0), "noise")
("seed", po::value(¶ms.seed)->default_value(default_seed), "")
("dim,D", po::value(&D), "dimension, see format")
("skip", po::value(&skip)->default_value(0), "see format")
("gap", po::value(&gap)->default_value(0), "see format")
("raw", "read raw binary file, need to specify D.")
("synthetic", po::value(&synthetic)->default_value(0), "generate synthetic data, for performance evaluation only, specify number of points")
("l2norm", "l2-normalize data, so as to mimic cosine similarity")
;
po::options_description desc("Allowed options");
desc.add(desc_visible).add(desc_hidden);
po::positional_options_description p;
p.add("data", 1);
p.add("output", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("raw") == 1) {
lshkit = false;
}
if (vm.count("version")) {
cout << "KGraph version " << KGraph::version() << endl;
return 0;
}
if (vm.count("help")
|| (synthetic && (vm.count("dim") == 0 || vm.count("data")))
|| (!synthetic && (vm.count("data") == 0 || (vm.count("dim") == 0 && !lshkit)))) {
cout << "Usage: index [OTHER OPTIONS]... INPUT [OUTPUT]" << endl;
cout << desc_visible << endl;
cout << desc_hidden << endl;
return 0;
}
if (params.S == 0) {
params.S = params.K;
}
if (lshkit && (synthetic == 0)) { // read dimension information from the data file
static const unsigned LSHKIT_HEADER = 3;
ifstream is(data_path.c_str(), ios::binary);
unsigned header[LSHKIT_HEADER]; /* entry size, row, col */
is.read((char *)header, sizeof header);
BOOST_VERIFY(is);
BOOST_VERIFY(header[0] == sizeof(value_type));
is.close();
D = header[2];
skip = LSHKIT_HEADER * sizeof(unsigned);
gap = 0;
}
Matrix<value_type> data;
if (synthetic) {
if (!std::is_floating_point<value_type>::value) {
throw std::runtime_error("synthetic data not implemented for non-floating-point values.");
}
data.resize(synthetic, D);
cerr << "Generating synthetic data..." << endl;
default_random_engine rng(params.seed);
uniform_real_distribution<double> distribution(-1.0, 1.0);
data.zero(); // important to do that
for (unsigned i = 0; i < synthetic; ++i) {
value_type *row = data[i];
for (unsigned j = 0; j < D; ++j) {
row[j] = distribution(rng);
}
}
}
else {
data.load(data_path, D, skip, gap);
}
if (noise != 0) {
if (!std::is_floating_point<value_type>::value) {
throw std::runtime_error("noise injection not implemented for non-floating-point value.");
}
tr1::ranlux64_base_01 rng;
double sum = 0, sum2 = 0;
for (unsigned i = 0; i < data.size(); ++i) {
for (unsigned j = 0; j < data.dim(); ++j) {
value_type v = data[i][j];
sum += v;
sum2 += v * v;
}
}
double total = double(data.size()) * data.dim();
double avg2 = sum2 / total, avg = sum / total;
double dev = sqrt(avg2 - avg * avg);
cerr << "Adding Gaussian noise w/ " << noise << "x sigma(" << dev << ")..." << endl;
boost::normal_distribution<double> gaussian(0, noise * dev);
for (unsigned i = 0; i < data.size(); ++i) {
for (unsigned j = 0; j < data.dim(); ++j) {
data[i][j] += gaussian(rng);
}
}
}
if (vm.count("l2norm")) {
cerr << "L2-normalizing data..." << endl;
data.normalize2();
}
MatrixOracle<value_type, metric::l2sqr> oracle(data);
KGraph::IndexInfo info;
KGraph *kgraph = KGraph::create(); //(oracle, params, &info);
{
auto_cpu_timer timer;
kgraph->build(oracle, params, &info);
cerr << info.stop_condition << endl;
}
if (output_path.size()) {
kgraph->save(output_path.c_str());
}
delete kgraph;
return 0;
}
<commit_msg>fixed old boost dependency, switch to C++11<commit_after>/*
Copyright (C) 2013,2014 Wei Dong <wdong@wdong.org>. All Rights Reserved.
*/
#ifndef KGRAPH_VALUE_TYPE
#define KGRAPH_VALUE_TYPE float
#endif
#include <sys/time.h>
#include <cctype>
#include <random>
#include <iomanip>
#include <type_traits>
#include <iostream>
#include <boost/timer/timer.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "kgraph.h"
#include "kgraph-data.h"
using namespace std;
using namespace boost;
using namespace boost::timer;
using namespace kgraph;
namespace po = boost::program_options;
typedef KGRAPH_VALUE_TYPE value_type;
int main (int argc, char *argv[]) {
string data_path;
string output_path;
KGraph::IndexParams params;
unsigned D;
unsigned skip;
unsigned gap;
unsigned synthetic;
float noise;
bool lshkit = true;
po::options_description desc_visible("General options");
desc_visible.add_options()
("help,h", "produce help message.")
("version,v", "print version information.")
("data", po::value(&data_path), "input path")
("output", po::value(&output_path), "output path")
(",K", po::value(¶ms.K)->default_value(default_K), "number of nearest neighbor")
("controls,C", po::value(¶ms.controls)->default_value(default_controls), "number of control pounsigneds")
;
po::options_description desc_hidden("Expert options");
desc_hidden.add_options()
("iterations,I", po::value(¶ms.iterations)->default_value(default_iterations), "")
(",S", po::value(¶ms.S)->default_value(default_S), "")
(",R", po::value(¶ms.R)->default_value(default_R), "")
(",L", po::value(¶ms.L)->default_value(default_L), "")
("delta", po::value(¶ms.delta)->default_value(default_delta), "")
("recall", po::value(¶ms.recall)->default_value(default_recall), "")
("prune", po::value(¶ms.prune)->default_value(default_prune), "")
("reverse", po::value(¶ms.reverse)->default_value(default_reverse), "")
("noise", po::value(&noise)->default_value(0), "noise")
("seed", po::value(¶ms.seed)->default_value(default_seed), "")
("dim,D", po::value(&D), "dimension, see format")
("skip", po::value(&skip)->default_value(0), "see format")
("gap", po::value(&gap)->default_value(0), "see format")
("raw", "read raw binary file, need to specify D.")
("synthetic", po::value(&synthetic)->default_value(0), "generate synthetic data, for performance evaluation only, specify number of points")
("l2norm", "l2-normalize data, so as to mimic cosine similarity")
;
po::options_description desc("Allowed options");
desc.add(desc_visible).add(desc_hidden);
po::positional_options_description p;
p.add("data", 1);
p.add("output", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("raw") == 1) {
lshkit = false;
}
if (vm.count("version")) {
cout << "KGraph version " << KGraph::version() << endl;
return 0;
}
if (vm.count("help")
|| (synthetic && (vm.count("dim") == 0 || vm.count("data")))
|| (!synthetic && (vm.count("data") == 0 || (vm.count("dim") == 0 && !lshkit)))) {
cout << "Usage: index [OTHER OPTIONS]... INPUT [OUTPUT]" << endl;
cout << desc_visible << endl;
cout << desc_hidden << endl;
return 0;
}
if (params.S == 0) {
params.S = params.K;
}
if (lshkit && (synthetic == 0)) { // read dimension information from the data file
static const unsigned LSHKIT_HEADER = 3;
ifstream is(data_path.c_str(), ios::binary);
unsigned header[LSHKIT_HEADER]; /* entry size, row, col */
is.read((char *)header, sizeof header);
BOOST_VERIFY(is);
BOOST_VERIFY(header[0] == sizeof(value_type));
is.close();
D = header[2];
skip = LSHKIT_HEADER * sizeof(unsigned);
gap = 0;
}
Matrix<value_type> data;
if (synthetic) {
if (!std::is_floating_point<value_type>::value) {
throw std::runtime_error("synthetic data not implemented for non-floating-point values.");
}
data.resize(synthetic, D);
cerr << "Generating synthetic data..." << endl;
default_random_engine rng(params.seed);
uniform_real_distribution<double> distribution(-1.0, 1.0);
data.zero(); // important to do that
for (unsigned i = 0; i < synthetic; ++i) {
value_type *row = data[i];
for (unsigned j = 0; j < D; ++j) {
row[j] = distribution(rng);
}
}
}
else {
data.load(data_path, D, skip, gap);
}
if (noise != 0) {
if (!std::is_floating_point<value_type>::value) {
throw std::runtime_error("noise injection not implemented for non-floating-point value.");
}
//tr1::ranlux64_base_01 rng;
std::default_random_engine rng;
double sum = 0, sum2 = 0;
for (unsigned i = 0; i < data.size(); ++i) {
for (unsigned j = 0; j < data.dim(); ++j) {
value_type v = data[i][j];
sum += v;
sum2 += v * v;
}
}
double total = double(data.size()) * data.dim();
double avg2 = sum2 / total, avg = sum / total;
double dev = sqrt(avg2 - avg * avg);
cerr << "Adding Gaussian noise w/ " << noise << "x sigma(" << dev << ")..." << endl;
std::normal_distribution<double> gaussian(0, noise * dev);
for (unsigned i = 0; i < data.size(); ++i) {
for (unsigned j = 0; j < data.dim(); ++j) {
data[i][j] += gaussian(rng);
}
}
}
if (vm.count("l2norm")) {
cerr << "L2-normalizing data..." << endl;
data.normalize2();
}
MatrixOracle<value_type, metric::l2sqr> oracle(data);
KGraph::IndexInfo info;
KGraph *kgraph = KGraph::create(); //(oracle, params, &info);
{
auto_cpu_timer timer;
kgraph->build(oracle, params, &info);
cerr << info.stop_condition << endl;
}
if (output_path.size()) {
kgraph->save(output_path.c_str());
}
delete kgraph;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com nor the names of its contributors
// may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <utility>
#include <vector>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>
#include <distributions/vector_math.hpp>
#include <distributions/random_fwd.hpp>
#include <eigen3/Eigen/Cholesky>
namespace distributions {
inline int sample_int(rng_t & rng, int low, int high) {
std::uniform_int_distribution<> sampler(low, high);
return sampler(rng);
}
inline float sample_unif01(rng_t & rng) {
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng);
}
inline bool sample_bernoulli(rng_t & rng, float p) {
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng) < p;
}
inline float sample_std_normal(rng_t & rng) {
std::normal_distribution<float> sampler(0.f, 1.f);
return sampler(rng);
}
inline float sample_normal(rng_t & rng, float mean, float variance) {
float stddev = sqrtf(variance);
std::normal_distribution<float> sampler(mean, stddev);
return sampler(rng);
}
inline float sample_chisq(rng_t & rng, float nu) {
// HACK <float> appears to be broken in libstdc++ 4.6
// typedef std::chi_squared_distribution<float> chi_squared_distribution_t;
typedef std::chi_squared_distribution<double> chi_squared_distribution_t;
chi_squared_distribution_t sampler(nu);
return sampler(rng);
}
inline int sample_poisson(rng_t & rng, float mean) {
std::poisson_distribution<int> sampler(mean);
return sampler(rng);
}
inline int sample_negative_binomial(rng_t & rng, float p, int r) {
std::negative_binomial_distribution<int> sampler(r, p);
return sampler(rng);
}
inline float sample_gamma(
rng_t & rng,
float alpha,
float beta = 1.f) {
// HACK <float> appears to be broken in libstdc++ 4.6
// typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;
gamma_distribution_t sampler(alpha, beta);
return sampler(rng);
}
inline float sample_beta(
rng_t & rng,
float alpha,
float beta) {
float x = sample_gamma(rng, alpha);
float y = sample_gamma(rng, beta);
if (x==0 && y==0)
return sample_bernoulli(rng, alpha / (alpha + beta)) ? 1.0 : 0.0;
return x / (x + y);
}
inline float sample_beta_safe(
rng_t & rng,
float alpha,
float beta,
float min_value) {
DIST_ASSERT(min_value >= 0, "bad bound: " << min_value);
DIST_ASSERT(alpha > 0, "bad alpha = " << alpha);
float p = sample_beta(rng, alpha, beta);
return (p + min_value) / (1.f + min_value);
}
void sample_dirichlet(
rng_t & rng,
size_t dim,
const float * alphas,
float * probs);
void sample_dirichlet_safe(
rng_t & rng,
size_t dim,
const float * alphas,
float * probs,
float min_value);
inline float fast_score_student_t(
float x,
float nu,
float mu,
float lambda) {
// \cite{murphy2007conjugate}, Eq. 304
float p = 0.f;
p += fast_lgamma_nu(nu);
p += 0.5f * fast_log(lambda / (M_PIf * nu));
p += (-0.5f * nu - 0.5f) * fast_log(1.f + (lambda * sqr(x - mu)) / nu);
return p;
}
inline float score_student_t(
float x,
float nu,
float mu,
float lambda) {
// \cite{murphy2007conjugate}, Eq. 304
float p = lgammaf(nu * 0.5f + 0.5f) - lgammaf(nu * 0.5f);
p += 0.5f * logf(lambda / (M_PIf * nu));
p += (-0.5f * nu - 0.5f) * logf(1.f + (lambda * sqr(x - mu)) / nu);
return p;
}
// XXX: not optimized for speed
template <typename Vector, typename Matrix>
inline float score_mv_student_t(
const Vector & v,
float nu,
const Vector & mu,
const Matrix & sigma) {
const unsigned d = v.size();
const float term1 = fast_lgamma(nu / 2. + static_cast<float>(d) / 2.)
- fast_lgamma(nu / 2.);
// XXX: use Cholesky decomposition to make this faster
const Matrix sigma_inv = sigma.inverse();
const float sigma_det = sigma.determinant();
const float log_pi = 1.1447298858494002;
const float term2 = -0.5 * fast_log(sigma_det)
- static_cast<float>(d) / 2. * (fast_log(nu) + log_pi);
const Vector diff = v - mu;
const float term3 = -0.5 * (nu + static_cast<float>(d)) *
fast_log(1. + 1. / nu * (diff.dot(sigma_inv * diff)));
return term1 + term2 + term3;
}
// Assumes sigma is positive definite
template <typename Vector, typename Matrix>
inline Vector sample_multivariate_normal(
const Vector & mu,
const Matrix & sigma,
rng_t & rng) {
DIST_ASSERT_EQ(sigma.rows(), sigma.cols());
DIST_ASSERT_EQ(mu.size(), sigma.rows());
Eigen::LLT<Matrix> llt(sigma);
DIST_ASSERT_EQ(llt.info(), Eigen::Success);
Vector z(mu.size());
std::normal_distribution<float> norm;
for (unsigned i = 0; i < mu.size(); i++) {
z(i) = norm(rng);
}
return mu + llt.matrixL() * z;
}
// Based on:
// http://www.mit.edu/~mattjj/released-code/hsmm/stats_util.py
template <typename Matrix>
inline Matrix sample_wishart(
float nu,
const Matrix & scale,
rng_t & rng) {
DIST_ASSERT_EQ(scale.rows(), scale.cols());
Eigen::LLT<Matrix> llt(scale);
DIST_ASSERT_EQ(llt.info(), Eigen::Success);
const unsigned size = scale.rows();
Matrix A = Matrix::Zero(size, size);
for (unsigned i = 0; i < size; i++) {
A(i, i) = sqrt(sample_chisq(rng, nu - static_cast<float>(i)));
}
std::normal_distribution<float> norm;
for (unsigned i = 1; i < size; i++) {
for (unsigned j = 0; j < i; j++) {
A(i, j) = norm(rng);
}
}
const Matrix X = llt.matrixL() * A;
return X * X.transpose();
}
// XXX: not optimized for speed
template <typename Matrix>
inline Matrix sample_inverse_wishart(
float nu,
const Matrix & psi,
rng_t & rng) {
const Matrix psi_inv = psi.inverse();
const Matrix sigma_inv = sample_wishart(nu, psi_inv, rng);
return sigma_inv.inverse();
}
template <typename Vector, typename Matrix>
inline std::pair<Vector, Matrix> sample_normal_inverse_wishart(
const Vector & mu0,
float lambda,
const Matrix & psi,
float nu,
rng_t & rng) {
Matrix cov = 1./lambda * sample_inverse_wishart(nu, psi, rng);
Vector mu = sample_multivariate_normal(mu0, cov, rng);
return std::make_pair(std::move(mu), std::move(cov));
}
template<class T>
inline T sample_from_urn(
rng_t & rng,
const std::vector<T> & urn) {
DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
size_t f = sample_int(rng, 0, urn.size() - 1);
DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
return urn[f];
}
template<class T>
inline std::pair<T, T> sample_pair_from_urn(
rng_t & rng,
const std::vector<T> & urn) {
DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
size_t f1 = sample_int(rng, 0, urn.size() - 1);
size_t f2 = sample_int(rng, 0, urn.size() - 2);
if (f2 >= f1) {
f2 += 1;
}
DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
return std::make_pair(urn[f1], urn[f2]);
}
// --------------------------------------------------------------------------
// Discrete Distribution
//
// Terminology:
//
// prob = probability
// likelihood = non-normalized probability
// score = non-normalized log probability
template<class Alloc>
float log_sum_exp(const std::vector<float, Alloc> & scores);
inline size_t sample_discrete(
rng_t & rng,
size_t dim,
const float * probs) {
DIST_ASSERT_LT(0, dim);
float t = sample_unif01(rng);
for (size_t i = 0; DIST_LIKELY(i < dim - 1); ++i) {
t -= probs[i];
if (DIST_UNLIKELY(t < 0)) {
return i;
}
}
return dim - 1;
}
template<class Alloc>
inline size_t sample_from_likelihoods(
rng_t & rng,
const std::vector<float, Alloc> & likelihoods,
float total_likelihood) {
const size_t size = likelihoods.size();
DIST_ASSERT_LT(0, size);
float t = total_likelihood * sample_unif01(rng);
for (size_t i = 0; DIST_LIKELY(i < size); ++i) {
t -= likelihoods[i];
if (DIST_UNLIKELY(t <= 0)) {
return i;
}
}
return size - 1;
}
template<class Alloc>
inline size_t sample_from_likelihoods(
rng_t & rng,
const std::vector<float, Alloc> & likelihoods) {
float total = vector_sum(likelihoods.size(), likelihoods.data());
return sample_from_likelihoods(rng, likelihoods, total);
}
template<class Alloc>
inline size_t sample_from_probs(
rng_t & rng,
const std::vector<float, Alloc> & probs) {
return sample_from_likelihoods(rng, probs, 1.f);
}
// returns total likelihood
template<class Alloc>
float scores_to_likelihoods(std::vector<float, Alloc> & scores);
template<class Alloc>
void scores_to_probs(std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
vector_scale(scores.size(), scores.data(), 1.f / total);
}
template<class Alloc>
inline size_t sample_from_scores_overwrite(
rng_t & rng,
std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
return sample_from_likelihoods(rng, scores, total);
}
template<class Alloc>
inline std::pair<size_t, float> sample_prob_from_scores_overwrite(
rng_t & rng,
std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
size_t sample = sample_from_likelihoods(rng, scores, total);
float prob = scores[sample] / total;
return std::make_pair(sample, prob);
}
// score_from_scores_overwrite(...) = log(prob_from_scores_overwrite(...)),
// this is less succeptible to overflow than prob_from_scores_overwrite
template<class Alloc>
float score_from_scores_overwrite(
rng_t & rng,
size_t sample,
std::vector<float, Alloc> & scores);
template<class Alloc>
inline size_t sample_from_scores(
rng_t & rng,
const std::vector<float, Alloc> & scores) {
std::vector<float, Alloc> scores_copy(scores);
return sample_from_scores_overwrite(rng, scores_copy);
}
} // namespace distributions
<commit_msg>Removed whitespace and added parens<commit_after>// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com nor the names of its contributors
// may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <utility>
#include <vector>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>
#include <distributions/vector_math.hpp>
#include <distributions/random_fwd.hpp>
#include <eigen3/Eigen/Cholesky>
namespace distributions {
inline int sample_int(rng_t & rng, int low, int high) {
std::uniform_int_distribution<> sampler(low, high);
return sampler(rng);
}
inline float sample_unif01(rng_t & rng) {
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng);
}
inline bool sample_bernoulli(rng_t & rng, float p) {
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng) < p;
}
inline float sample_std_normal(rng_t & rng) {
std::normal_distribution<float> sampler(0.f, 1.f);
return sampler(rng);
}
inline float sample_normal(rng_t & rng, float mean, float variance) {
float stddev = sqrtf(variance);
std::normal_distribution<float> sampler(mean, stddev);
return sampler(rng);
}
inline float sample_chisq(rng_t & rng, float nu) {
// HACK <float> appears to be broken in libstdc++ 4.6
// typedef std::chi_squared_distribution<float> chi_squared_distribution_t;
typedef std::chi_squared_distribution<double> chi_squared_distribution_t;
chi_squared_distribution_t sampler(nu);
return sampler(rng);
}
inline int sample_poisson(rng_t & rng, float mean) {
std::poisson_distribution<int> sampler(mean);
return sampler(rng);
}
inline int sample_negative_binomial(rng_t & rng, float p, int r) {
std::negative_binomial_distribution<int> sampler(r, p);
return sampler(rng);
}
inline float sample_gamma(
rng_t & rng,
float alpha,
float beta = 1.f) {
// HACK <float> appears to be broken in libstdc++ 4.6
// typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;
gamma_distribution_t sampler(alpha, beta);
return sampler(rng);
}
inline float sample_beta(
rng_t & rng,
float alpha,
float beta) {
float x = sample_gamma(rng, alpha);
float y = sample_gamma(rng, beta);
if ((x==0) && (y==0))
return sample_bernoulli(rng, alpha / (alpha + beta)) ? 1.0 : 0.0;
return x / (x + y);
}
inline float sample_beta_safe(
rng_t & rng,
float alpha,
float beta,
float min_value) {
DIST_ASSERT(min_value >= 0, "bad bound: " << min_value);
DIST_ASSERT(alpha > 0, "bad alpha = " << alpha);
float p = sample_beta(rng, alpha, beta);
return (p + min_value) / (1.f + min_value);
}
void sample_dirichlet(
rng_t & rng,
size_t dim,
const float * alphas,
float * probs);
void sample_dirichlet_safe(
rng_t & rng,
size_t dim,
const float * alphas,
float * probs,
float min_value);
inline float fast_score_student_t(
float x,
float nu,
float mu,
float lambda) {
// \cite{murphy2007conjugate}, Eq. 304
float p = 0.f;
p += fast_lgamma_nu(nu);
p += 0.5f * fast_log(lambda / (M_PIf * nu));
p += (-0.5f * nu - 0.5f) * fast_log(1.f + (lambda * sqr(x - mu)) / nu);
return p;
}
inline float score_student_t(
float x,
float nu,
float mu,
float lambda) {
// \cite{murphy2007conjugate}, Eq. 304
float p = lgammaf(nu * 0.5f + 0.5f) - lgammaf(nu * 0.5f);
p += 0.5f * logf(lambda / (M_PIf * nu));
p += (-0.5f * nu - 0.5f) * logf(1.f + (lambda * sqr(x - mu)) / nu);
return p;
}
// XXX: not optimized for speed
template <typename Vector, typename Matrix>
inline float score_mv_student_t(
const Vector & v,
float nu,
const Vector & mu,
const Matrix & sigma) {
const unsigned d = v.size();
const float term1 = fast_lgamma(nu / 2. + static_cast<float>(d) / 2.)
- fast_lgamma(nu / 2.);
// XXX: use Cholesky decomposition to make this faster
const Matrix sigma_inv = sigma.inverse();
const float sigma_det = sigma.determinant();
const float log_pi = 1.1447298858494002;
const float term2 = -0.5 * fast_log(sigma_det)
- static_cast<float>(d) / 2. * (fast_log(nu) + log_pi);
const Vector diff = v - mu;
const float term3 = -0.5 * (nu + static_cast<float>(d)) *
fast_log(1. + 1. / nu * (diff.dot(sigma_inv * diff)));
return term1 + term2 + term3;
}
// Assumes sigma is positive definite
template <typename Vector, typename Matrix>
inline Vector sample_multivariate_normal(
const Vector & mu,
const Matrix & sigma,
rng_t & rng) {
DIST_ASSERT_EQ(sigma.rows(), sigma.cols());
DIST_ASSERT_EQ(mu.size(), sigma.rows());
Eigen::LLT<Matrix> llt(sigma);
DIST_ASSERT_EQ(llt.info(), Eigen::Success);
Vector z(mu.size());
std::normal_distribution<float> norm;
for (unsigned i = 0; i < mu.size(); i++) {
z(i) = norm(rng);
}
return mu + llt.matrixL() * z;
}
// Based on:
// http://www.mit.edu/~mattjj/released-code/hsmm/stats_util.py
template <typename Matrix>
inline Matrix sample_wishart(
float nu,
const Matrix & scale,
rng_t & rng) {
DIST_ASSERT_EQ(scale.rows(), scale.cols());
Eigen::LLT<Matrix> llt(scale);
DIST_ASSERT_EQ(llt.info(), Eigen::Success);
const unsigned size = scale.rows();
Matrix A = Matrix::Zero(size, size);
for (unsigned i = 0; i < size; i++) {
A(i, i) = sqrt(sample_chisq(rng, nu - static_cast<float>(i)));
}
std::normal_distribution<float> norm;
for (unsigned i = 1; i < size; i++) {
for (unsigned j = 0; j < i; j++) {
A(i, j) = norm(rng);
}
}
const Matrix X = llt.matrixL() * A;
return X * X.transpose();
}
// XXX: not optimized for speed
template <typename Matrix>
inline Matrix sample_inverse_wishart(
float nu,
const Matrix & psi,
rng_t & rng) {
const Matrix psi_inv = psi.inverse();
const Matrix sigma_inv = sample_wishart(nu, psi_inv, rng);
return sigma_inv.inverse();
}
template <typename Vector, typename Matrix>
inline std::pair<Vector, Matrix> sample_normal_inverse_wishart(
const Vector & mu0,
float lambda,
const Matrix & psi,
float nu,
rng_t & rng) {
Matrix cov = 1./lambda * sample_inverse_wishart(nu, psi, rng);
Vector mu = sample_multivariate_normal(mu0, cov, rng);
return std::make_pair(std::move(mu), std::move(cov));
}
template<class T>
inline T sample_from_urn(
rng_t & rng,
const std::vector<T> & urn) {
DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
size_t f = sample_int(rng, 0, urn.size() - 1);
DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
return urn[f];
}
template<class T>
inline std::pair<T, T> sample_pair_from_urn(
rng_t & rng,
const std::vector<T> & urn) {
DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
size_t f1 = sample_int(rng, 0, urn.size() - 1);
size_t f2 = sample_int(rng, 0, urn.size() - 2);
if (f2 >= f1) {
f2 += 1;
}
DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
return std::make_pair(urn[f1], urn[f2]);
}
// --------------------------------------------------------------------------
// Discrete Distribution
//
// Terminology:
//
// prob = probability
// likelihood = non-normalized probability
// score = non-normalized log probability
template<class Alloc>
float log_sum_exp(const std::vector<float, Alloc> & scores);
inline size_t sample_discrete(
rng_t & rng,
size_t dim,
const float * probs) {
DIST_ASSERT_LT(0, dim);
float t = sample_unif01(rng);
for (size_t i = 0; DIST_LIKELY(i < dim - 1); ++i) {
t -= probs[i];
if (DIST_UNLIKELY(t < 0)) {
return i;
}
}
return dim - 1;
}
template<class Alloc>
inline size_t sample_from_likelihoods(
rng_t & rng,
const std::vector<float, Alloc> & likelihoods,
float total_likelihood) {
const size_t size = likelihoods.size();
DIST_ASSERT_LT(0, size);
float t = total_likelihood * sample_unif01(rng);
for (size_t i = 0; DIST_LIKELY(i < size); ++i) {
t -= likelihoods[i];
if (DIST_UNLIKELY(t <= 0)) {
return i;
}
}
return size - 1;
}
template<class Alloc>
inline size_t sample_from_likelihoods(
rng_t & rng,
const std::vector<float, Alloc> & likelihoods) {
float total = vector_sum(likelihoods.size(), likelihoods.data());
return sample_from_likelihoods(rng, likelihoods, total);
}
template<class Alloc>
inline size_t sample_from_probs(
rng_t & rng,
const std::vector<float, Alloc> & probs) {
return sample_from_likelihoods(rng, probs, 1.f);
}
// returns total likelihood
template<class Alloc>
float scores_to_likelihoods(std::vector<float, Alloc> & scores);
template<class Alloc>
void scores_to_probs(std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
vector_scale(scores.size(), scores.data(), 1.f / total);
}
template<class Alloc>
inline size_t sample_from_scores_overwrite(
rng_t & rng,
std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
return sample_from_likelihoods(rng, scores, total);
}
template<class Alloc>
inline std::pair<size_t, float> sample_prob_from_scores_overwrite(
rng_t & rng,
std::vector<float, Alloc> & scores) {
float total = scores_to_likelihoods(scores);
size_t sample = sample_from_likelihoods(rng, scores, total);
float prob = scores[sample] / total;
return std::make_pair(sample, prob);
}
// score_from_scores_overwrite(...) = log(prob_from_scores_overwrite(...)),
// this is less succeptible to overflow than prob_from_scores_overwrite
template<class Alloc>
float score_from_scores_overwrite(
rng_t & rng,
size_t sample,
std::vector<float, Alloc> & scores);
template<class Alloc>
inline size_t sample_from_scores(
rng_t & rng,
const std::vector<float, Alloc> & scores) {
std::vector<float, Alloc> scores_copy(scores);
return sample_from_scores_overwrite(rng, scores_copy);
}
} // namespace distributions
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include <stdafx.h>
#include "PlaybackService.h"
#include <cursespp/MessageQueue.h>
#include <cursespp/Message.h>
#include <core/audio/ITransport.h>
#include <core/library/LocalLibraryConstants.h>
using musik::core::TrackPtr;
using musik::core::LibraryPtr;
using musik::core::audio::ITransport;
using cursespp::IMessageTarget;
using cursespp::IMessage;
using namespace musik::core::library::constants;
using namespace musik::box;
#define NO_POSITION (size_t) -1
#define URI_AT_INDEX(x) this->playlist.Get(x)->URI()
#define PREVIOUS_GRACE_PERIOD 2.0f
#define MESSAGE_STREAM_EVENT 1000
#define MESSAGE_PLAYBACK_EVENT 1001
#define MESSAGE_PREPARE_NEXT_TRACK 1002
#define POST(instance, type, user1, user2) \
cursespp::MessageQueue::Instance().Post( \
cursespp::Message::Create(instance, type, user1, user2));
PlaybackService::PlaybackService(LibraryPtr library, ITransport& transport)
: library(library)
, transport(transport)
, playlist(library)
, repeatMode(RepeatNone) {
transport.StreamEvent.connect(this, &PlaybackService::OnStreamEvent);
transport.PlaybackEvent.connect(this, &PlaybackService::OnPlaybackEvent);
this->index = NO_POSITION;
this->nextIndex = NO_POSITION;
}
void PlaybackService::PrepareNextTrack() {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
if (this->Count() > 0) {
/* repeat track, just keep playing the same thing over and over */
if (this->repeatMode == RepeatTrack) {
this->nextIndex = this->index;
this->transport.PrepareNextTrack(URI_AT_INDEX(this->index));
}
else {
/* normal case, just move forward */
if (this->playlist.Count() > this->index + 1) {
if (this->nextIndex != this->index + 1) {
this->nextIndex = this->index + 1;
this->transport.PrepareNextTrack(URI_AT_INDEX(nextIndex));
}
}
/* repeat list case, wrap around to the beginning if necessary */
else if (this->repeatMode == RepeatList) {
if (this->nextIndex != 0) {
this->nextIndex = 0;
this->transport.PrepareNextTrack(URI_AT_INDEX(nextIndex));
}
}
}
}
}
void PlaybackService::SetRepeatMode(RepeatMode mode) {
if (this->repeatMode != mode) {
this->repeatMode = mode;
this->ModeChanged();
POST(this, MESSAGE_PREPARE_NEXT_TRACK, 0, 0);
}
}
void PlaybackService::ProcessMessage(IMessage &message) {
if (message.Type() == MESSAGE_STREAM_EVENT) {
int64 eventType = message.UserData1();
if (eventType == ITransport::StreamPlaying) {
if (this->nextIndex != NO_POSITION) {
this->index = this->nextIndex;
this->nextIndex = NO_POSITION;
}
if (this->index != NO_POSITION) {
TrackPtr track;
{
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
track = this->playlist.Get(this->index);
}
this->TrackChanged(this->index, track);
}
this->PrepareNextTrack();
}
}
else if (message.Type() == MESSAGE_PLAYBACK_EVENT) {
int64 eventType = message.UserData1();
if (eventType == ITransport::PlaybackStopped) {
this->TrackChanged(NO_POSITION, TrackPtr());
}
}
else if (message.Type() == MESSAGE_PREPARE_NEXT_TRACK) {
this->PrepareNextTrack();
}
}
bool PlaybackService::Next() {
if (transport.GetPlaybackState() == ITransport::PlaybackStopped) {
return false;
}
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
if (this->playlist.Count() > index + 1) {
this->Play(index + 1);
return true;
}
else if (this->repeatMode == RepeatList) {
this->Play(0); /* wrap around */
return true;
}
return false;
}
bool PlaybackService::Previous() {
if (transport.GetPlaybackState() == ITransport::PlaybackStopped) {
return false;
}
if (transport.Position() > PREVIOUS_GRACE_PERIOD) {
this->Play(index);
return true;
}
if (index > 0) {
this->Play(index - 1);
return true;
}
else if (this->repeatMode == RepeatList) {
this->Play(this->Count() - 1); /* wrap around */
return true;
}
return false;
}
void PlaybackService::Play(TrackList& tracks, size_t index) {
/* do the copy outside of the critical section, then swap. */
TrackList temp(this->library);
temp.CopyFrom(tracks);
{
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
this->playlist.Swap(temp);
}
if (index <= tracks.Count()) {
this->Play(index);
}
}
void PlaybackService::CopyTo(TrackList& target) {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
target.CopyFrom(this->playlist);
}
void PlaybackService::Play(size_t index) {
transport.Start(URI_AT_INDEX(index));
this->nextIndex = NO_POSITION;
this->index = index;
}
size_t PlaybackService::GetIndex() {
return this->index;
}
TrackPtr PlaybackService::GetTrackAtIndex(size_t index) {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
return this->playlist.Get(index);
}
void PlaybackService::OnStreamEvent(int eventType, std::string uri) {
POST(this, MESSAGE_STREAM_EVENT, eventType, 0);
}
void PlaybackService::OnPlaybackEvent(int eventType) {
POST(this, MESSAGE_PLAYBACK_EVENT, eventType, 0);
}
<commit_msg>Don't prepare the next track if the Transport is in the stopped state.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include <stdafx.h>
#include "PlaybackService.h"
#include <cursespp/MessageQueue.h>
#include <cursespp/Message.h>
#include <core/audio/ITransport.h>
#include <core/library/LocalLibraryConstants.h>
using musik::core::TrackPtr;
using musik::core::LibraryPtr;
using musik::core::audio::ITransport;
using cursespp::IMessageTarget;
using cursespp::IMessage;
using namespace musik::core::library::constants;
using namespace musik::box;
#define NO_POSITION (size_t) -1
#define URI_AT_INDEX(x) this->playlist.Get(x)->URI()
#define PREVIOUS_GRACE_PERIOD 2.0f
#define MESSAGE_STREAM_EVENT 1000
#define MESSAGE_PLAYBACK_EVENT 1001
#define MESSAGE_PREPARE_NEXT_TRACK 1002
#define POST(instance, type, user1, user2) \
cursespp::MessageQueue::Instance().Post( \
cursespp::Message::Create(instance, type, user1, user2));
PlaybackService::PlaybackService(LibraryPtr library, ITransport& transport)
: library(library)
, transport(transport)
, playlist(library)
, repeatMode(RepeatNone) {
transport.StreamEvent.connect(this, &PlaybackService::OnStreamEvent);
transport.PlaybackEvent.connect(this, &PlaybackService::OnPlaybackEvent);
this->index = NO_POSITION;
this->nextIndex = NO_POSITION;
}
void PlaybackService::PrepareNextTrack() {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
if (this->Count() > 0) {
/* repeat track, just keep playing the same thing over and over */
if (this->repeatMode == RepeatTrack) {
this->nextIndex = this->index;
this->transport.PrepareNextTrack(URI_AT_INDEX(this->index));
}
else {
/* normal case, just move forward */
if (this->playlist.Count() > this->index + 1) {
if (this->nextIndex != this->index + 1) {
this->nextIndex = this->index + 1;
this->transport.PrepareNextTrack(URI_AT_INDEX(nextIndex));
}
}
/* repeat list case, wrap around to the beginning if necessary */
else if (this->repeatMode == RepeatList) {
if (this->nextIndex != 0) {
this->nextIndex = 0;
this->transport.PrepareNextTrack(URI_AT_INDEX(nextIndex));
}
}
}
}
}
void PlaybackService::SetRepeatMode(RepeatMode mode) {
if (this->repeatMode != mode) {
this->repeatMode = mode;
this->ModeChanged();
POST(this, MESSAGE_PREPARE_NEXT_TRACK, 0, 0);
}
}
void PlaybackService::ProcessMessage(IMessage &message) {
if (message.Type() == MESSAGE_STREAM_EVENT) {
int64 eventType = message.UserData1();
if (eventType == ITransport::StreamPlaying) {
if (this->nextIndex != NO_POSITION) {
this->index = this->nextIndex;
this->nextIndex = NO_POSITION;
}
if (this->index != NO_POSITION) {
TrackPtr track;
{
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
track = this->playlist.Get(this->index);
}
this->TrackChanged(this->index, track);
}
this->PrepareNextTrack();
}
}
else if (message.Type() == MESSAGE_PLAYBACK_EVENT) {
int64 eventType = message.UserData1();
if (eventType == ITransport::PlaybackStopped) {
this->TrackChanged(NO_POSITION, TrackPtr());
}
}
else if (message.Type() == MESSAGE_PREPARE_NEXT_TRACK) {
if (transport.GetPlaybackState() != ITransport::PlaybackStopped) {
this->PrepareNextTrack();
}
}
}
bool PlaybackService::Next() {
if (transport.GetPlaybackState() == ITransport::PlaybackStopped) {
return false;
}
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
if (this->playlist.Count() > index + 1) {
this->Play(index + 1);
return true;
}
else if (this->repeatMode == RepeatList) {
this->Play(0); /* wrap around */
return true;
}
return false;
}
bool PlaybackService::Previous() {
if (transport.GetPlaybackState() == ITransport::PlaybackStopped) {
return false;
}
if (transport.Position() > PREVIOUS_GRACE_PERIOD) {
this->Play(index);
return true;
}
if (index > 0) {
this->Play(index - 1);
return true;
}
else if (this->repeatMode == RepeatList) {
this->Play(this->Count() - 1); /* wrap around */
return true;
}
return false;
}
void PlaybackService::Play(TrackList& tracks, size_t index) {
/* do the copy outside of the critical section, then swap. */
TrackList temp(this->library);
temp.CopyFrom(tracks);
{
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
this->playlist.Swap(temp);
}
if (index <= tracks.Count()) {
this->Play(index);
}
}
void PlaybackService::CopyTo(TrackList& target) {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
target.CopyFrom(this->playlist);
}
void PlaybackService::Play(size_t index) {
transport.Start(URI_AT_INDEX(index));
this->nextIndex = NO_POSITION;
this->index = index;
}
size_t PlaybackService::GetIndex() {
return this->index;
}
TrackPtr PlaybackService::GetTrackAtIndex(size_t index) {
boost::recursive_mutex::scoped_lock lock(this->playlistMutex);
return this->playlist.Get(index);
}
void PlaybackService::OnStreamEvent(int eventType, std::string uri) {
POST(this, MESSAGE_STREAM_EVENT, eventType, 0);
}
void PlaybackService::OnPlaybackEvent(int eventType) {
POST(this, MESSAGE_PLAYBACK_EVENT, eventType, 0);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "bochs.h"
#include "icon_bochs.h"
// This file defines stubs for the GUI interface, which is a
// place to start if you want to port bochs to a platform, for
// which there is no support for your native GUI, or if you want to compile
// bochs without any native GUI support (no output window or
// keyboard input will be possible).
// Look in 'x.cc', 'beos.cc', and 'win32.cc' for specific
// implementations of this interface. -Kevin
// ::SPECIFIC_INIT()
//
// Called from gui.cc, once upon program startup, to allow for the
// specific GUI code (X11, BeOS, ...) to be initialized.
//
// th: a 'this' pointer to the gui class. If a function external to the
// class needs access, store this pointer and use later.
// argc, argv: not used right now, but the intention is to pass native GUI
// specific options from the command line. (X11 options, BeOS options,...)
//
// tilewidth, tileheight: for optimization, graphics_tile_update() passes
// only updated regions of the screen to the gui code to be redrawn.
// These define the dimensions of a region (tile).
// headerbar_y: A headerbar (toolbar) is display on the top of the
// VGA window, showing floppy status, and other information. It
// always assumes the width of the current VGA mode width, but
// it's height is defined by this parameter.
void
bx_gui_c::specific_init(bx_gui_c *th, int argc, char **argv, unsigned tilewidth, unsigned tileheight,
unsigned headerbar_y)
{
th->setprefix("[NGUI]");
UNUSED(th);
UNUSED(argc);
UNUSED(argv);
UNUSED(tilewidth);
UNUSED(tileheight);
UNUSED(headerbar_y);
UNUSED(bochs_icon_bits); // global variable
if (bx_options.private_colormap) {
BX_INFO(("private_colormap option ignored.\n"));
}
}
// ::HANDLE_EVENTS()
//
// Called periodically (vga_update_interval in .bochsrc) so the
// the gui code can poll for keyboard, mouse, and other
// relevant events.
void
bx_gui_c::handle_events(void)
{
}
// ::FLUSH()
//
// Called periodically, requesting that the gui code flush all pending
// screen update requests.
void
bx_gui_c::flush(void)
{
}
// ::CLEAR_SCREEN()
//
// Called to request that the VGA region is cleared. Don't
// clear the area that defines the headerbar.
void
bx_gui_c::clear_screen(void)
{
}
// ::TEXT_UPDATE()
//
// Called in a VGA text mode, to update the screen with
// new content.
//
// old_text: array of character/attributes making up the contents
// of the screen from the last call. See below
// new_text: array of character/attributes making up the current
// contents, which should now be displayed. See below
//
// format of old_text & new_text: each is 4000 bytes long.
// This represents 80 characters wide by 25 high, with
// each character being 2 bytes. The first by is the
// character value, the second is the attribute byte.
// I currently don't handle the attribute byte.
//
// cursor_x: new x location of cursor
// cursor_y: new y location of cursor
void
bx_gui_c::text_update(Bit8u *old_text, Bit8u *new_text,
unsigned long cursor_x, unsigned long cursor_y,
unsigned nrows)
{
UNUSED(old_text);
UNUSED(new_text);
UNUSED(cursor_x);
UNUSED(cursor_y);
UNUSED(nrows);
}
// ::PALETTE_CHANGE()
//
// Allocate a color in the native GUI, for this color, and put
// it in the colormap location 'index'.
// returns: 0=no screen update needed (color map change has direct effect)
// 1=screen updated needed (redraw using current colormap)
Boolean
bx_gui_c::palette_change(unsigned index, unsigned red, unsigned green, unsigned blue)
{
UNUSED(index);
UNUSED(red);
UNUSED(green);
UNUSED(blue);
return(0);
}
// ::GRAPHICS_TILE_UPDATE()
//
// Called to request that a tile of graphics be drawn to the
// screen, since info in this region has changed.
//
// tile: array of 8bit values representing a block of pixels with
// dimension equal to the 'tilewidth' & 'tileheight' parameters to
// ::specific_init(). Each value specifies an index into the
// array of colors you allocated for ::palette_change()
// x0: x origin of tile
// y0: y origin of tile
//
// note: origin of tile and of window based on (0,0) being in the upper
// left of the window.
void
bx_gui_c::graphics_tile_update(Bit8u *tile, unsigned x0, unsigned y0)
{
UNUSED(tile);
UNUSED(x0);
UNUSED(y0);
}
// ::DIMENSION_UPDATE()
//
// Called when the VGA mode changes it's X,Y dimensions.
// Resize the window to this size, but you need to add on
// the height of the headerbar to the Y value.
//
// x: new VGA x size
// y: new VGA y size (add headerbar_y parameter from ::specific_init().
void
bx_gui_c::dimension_update(unsigned x, unsigned y)
{
UNUSED(x);
UNUSED(y);
}
// ::CREATE_BITMAP()
//
// Create a monochrome bitmap of size 'xdim' by 'ydim', which will
// be drawn in the headerbar. Return an integer ID to the bitmap,
// with which the bitmap can be referenced later.
//
// bmap: packed 8 pixels-per-byte bitmap. The pixel order is:
// bit0 is the left most pixel, bit7 is the right most pixel.
// xdim: x dimension of bitmap
// ydim: y dimension of bitmap
unsigned
bx_gui_c::create_bitmap(const unsigned char *bmap, unsigned xdim, unsigned ydim)
{
UNUSED(bmap);
UNUSED(xdim);
UNUSED(ydim);
return(0);
}
// ::HEADERBAR_BITMAP()
//
// Called to install a bitmap in the bochs headerbar (toolbar).
//
// bmap_id: will correspond to an ID returned from
// ::create_bitmap(). 'alignment' is either BX_GRAVITY_LEFT
// or BX_GRAVITY_RIGHT, meaning install the bitmap in the next
// available leftmost or rightmost space.
// alignment: is either BX_GRAVITY_LEFT or BX_GRAVITY_RIGHT,
// meaning install the bitmap in the next
// available leftmost or rightmost space.
// f: a 'C' function pointer to callback when the mouse is clicked in
// the boundaries of this bitmap.
unsigned
bx_gui_c::headerbar_bitmap(unsigned bmap_id, unsigned alignment, void (*f)(void))
{
UNUSED(bmap_id);
UNUSED(alignment);
UNUSED(f);
return(0);
}
// ::SHOW_HEADERBAR()
//
// Show (redraw) the current headerbar, which is composed of
// currently installed bitmaps.
void
bx_gui_c::show_headerbar(void)
{
}
// ::REPLACE_BITMAP()
//
// Replace the bitmap installed in the headerbar ID slot 'hbar_id',
// with the one specified by 'bmap_id'. 'bmap_id' will have
// been generated by ::create_bitmap(). The old and new bitmap
// must be of the same size. This allows the bitmap the user
// sees to change, when some action occurs. For example when
// the user presses on the floppy icon, it then displays
// the ejected status.
//
// hbar_id: headerbar slot ID
// bmap_id: bitmap ID
void
bx_gui_c::replace_bitmap(unsigned hbar_id, unsigned bmap_id)
{
UNUSED(hbar_id);
UNUSED(bmap_id);
}
// ::EXIT()
//
// Called before bochs terminates, to allow for a graceful
// exit from the native GUI mechanism.
void
bx_gui_c::exit(void)
{
BX_INFO(("bx_gui_c::exit() not implemented yet.\n"));
}
<commit_msg>- add missing LOG_THIS on main branch<commit_after>// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "bochs.h"
#include "icon_bochs.h"
#define LOG_THIS bx_gui.
// This file defines stubs for the GUI interface, which is a
// place to start if you want to port bochs to a platform, for
// which there is no support for your native GUI, or if you want to compile
// bochs without any native GUI support (no output window or
// keyboard input will be possible).
// Look in 'x.cc', 'beos.cc', and 'win32.cc' for specific
// implementations of this interface. -Kevin
// ::SPECIFIC_INIT()
//
// Called from gui.cc, once upon program startup, to allow for the
// specific GUI code (X11, BeOS, ...) to be initialized.
//
// th: a 'this' pointer to the gui class. If a function external to the
// class needs access, store this pointer and use later.
// argc, argv: not used right now, but the intention is to pass native GUI
// specific options from the command line. (X11 options, BeOS options,...)
//
// tilewidth, tileheight: for optimization, graphics_tile_update() passes
// only updated regions of the screen to the gui code to be redrawn.
// These define the dimensions of a region (tile).
// headerbar_y: A headerbar (toolbar) is display on the top of the
// VGA window, showing floppy status, and other information. It
// always assumes the width of the current VGA mode width, but
// it's height is defined by this parameter.
void
bx_gui_c::specific_init(bx_gui_c *th, int argc, char **argv, unsigned tilewidth, unsigned tileheight,
unsigned headerbar_y)
{
th->setprefix("[NGUI]");
UNUSED(th);
UNUSED(argc);
UNUSED(argv);
UNUSED(tilewidth);
UNUSED(tileheight);
UNUSED(headerbar_y);
UNUSED(bochs_icon_bits); // global variable
if (bx_options.private_colormap) {
BX_INFO(("private_colormap option ignored.\n"));
}
}
// ::HANDLE_EVENTS()
//
// Called periodically (vga_update_interval in .bochsrc) so the
// the gui code can poll for keyboard, mouse, and other
// relevant events.
void
bx_gui_c::handle_events(void)
{
}
// ::FLUSH()
//
// Called periodically, requesting that the gui code flush all pending
// screen update requests.
void
bx_gui_c::flush(void)
{
}
// ::CLEAR_SCREEN()
//
// Called to request that the VGA region is cleared. Don't
// clear the area that defines the headerbar.
void
bx_gui_c::clear_screen(void)
{
}
// ::TEXT_UPDATE()
//
// Called in a VGA text mode, to update the screen with
// new content.
//
// old_text: array of character/attributes making up the contents
// of the screen from the last call. See below
// new_text: array of character/attributes making up the current
// contents, which should now be displayed. See below
//
// format of old_text & new_text: each is 4000 bytes long.
// This represents 80 characters wide by 25 high, with
// each character being 2 bytes. The first by is the
// character value, the second is the attribute byte.
// I currently don't handle the attribute byte.
//
// cursor_x: new x location of cursor
// cursor_y: new y location of cursor
void
bx_gui_c::text_update(Bit8u *old_text, Bit8u *new_text,
unsigned long cursor_x, unsigned long cursor_y,
unsigned nrows)
{
UNUSED(old_text);
UNUSED(new_text);
UNUSED(cursor_x);
UNUSED(cursor_y);
UNUSED(nrows);
}
// ::PALETTE_CHANGE()
//
// Allocate a color in the native GUI, for this color, and put
// it in the colormap location 'index'.
// returns: 0=no screen update needed (color map change has direct effect)
// 1=screen updated needed (redraw using current colormap)
Boolean
bx_gui_c::palette_change(unsigned index, unsigned red, unsigned green, unsigned blue)
{
UNUSED(index);
UNUSED(red);
UNUSED(green);
UNUSED(blue);
return(0);
}
// ::GRAPHICS_TILE_UPDATE()
//
// Called to request that a tile of graphics be drawn to the
// screen, since info in this region has changed.
//
// tile: array of 8bit values representing a block of pixels with
// dimension equal to the 'tilewidth' & 'tileheight' parameters to
// ::specific_init(). Each value specifies an index into the
// array of colors you allocated for ::palette_change()
// x0: x origin of tile
// y0: y origin of tile
//
// note: origin of tile and of window based on (0,0) being in the upper
// left of the window.
void
bx_gui_c::graphics_tile_update(Bit8u *tile, unsigned x0, unsigned y0)
{
UNUSED(tile);
UNUSED(x0);
UNUSED(y0);
}
// ::DIMENSION_UPDATE()
//
// Called when the VGA mode changes it's X,Y dimensions.
// Resize the window to this size, but you need to add on
// the height of the headerbar to the Y value.
//
// x: new VGA x size
// y: new VGA y size (add headerbar_y parameter from ::specific_init().
void
bx_gui_c::dimension_update(unsigned x, unsigned y)
{
UNUSED(x);
UNUSED(y);
}
// ::CREATE_BITMAP()
//
// Create a monochrome bitmap of size 'xdim' by 'ydim', which will
// be drawn in the headerbar. Return an integer ID to the bitmap,
// with which the bitmap can be referenced later.
//
// bmap: packed 8 pixels-per-byte bitmap. The pixel order is:
// bit0 is the left most pixel, bit7 is the right most pixel.
// xdim: x dimension of bitmap
// ydim: y dimension of bitmap
unsigned
bx_gui_c::create_bitmap(const unsigned char *bmap, unsigned xdim, unsigned ydim)
{
UNUSED(bmap);
UNUSED(xdim);
UNUSED(ydim);
return(0);
}
// ::HEADERBAR_BITMAP()
//
// Called to install a bitmap in the bochs headerbar (toolbar).
//
// bmap_id: will correspond to an ID returned from
// ::create_bitmap(). 'alignment' is either BX_GRAVITY_LEFT
// or BX_GRAVITY_RIGHT, meaning install the bitmap in the next
// available leftmost or rightmost space.
// alignment: is either BX_GRAVITY_LEFT or BX_GRAVITY_RIGHT,
// meaning install the bitmap in the next
// available leftmost or rightmost space.
// f: a 'C' function pointer to callback when the mouse is clicked in
// the boundaries of this bitmap.
unsigned
bx_gui_c::headerbar_bitmap(unsigned bmap_id, unsigned alignment, void (*f)(void))
{
UNUSED(bmap_id);
UNUSED(alignment);
UNUSED(f);
return(0);
}
// ::SHOW_HEADERBAR()
//
// Show (redraw) the current headerbar, which is composed of
// currently installed bitmaps.
void
bx_gui_c::show_headerbar(void)
{
}
// ::REPLACE_BITMAP()
//
// Replace the bitmap installed in the headerbar ID slot 'hbar_id',
// with the one specified by 'bmap_id'. 'bmap_id' will have
// been generated by ::create_bitmap(). The old and new bitmap
// must be of the same size. This allows the bitmap the user
// sees to change, when some action occurs. For example when
// the user presses on the floppy icon, it then displays
// the ejected status.
//
// hbar_id: headerbar slot ID
// bmap_id: bitmap ID
void
bx_gui_c::replace_bitmap(unsigned hbar_id, unsigned bmap_id)
{
UNUSED(hbar_id);
UNUSED(bmap_id);
}
// ::EXIT()
//
// Called before bochs terminates, to allow for a graceful
// exit from the native GUI mechanism.
void
bx_gui_c::exit(void)
{
BX_INFO(("bx_gui_c::exit() not implemented yet.\n"));
}
<|endoftext|> |
<commit_before>// $Id$
//
// Class to make emcal particles in AOD/ESD events.
//
// Author: S.Aiola
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliVTrack.h"
#include "AliVCluster.h"
#include "AliEmcalParticle.h"
#include "AliEmcalParticleMaker.h"
ClassImp(AliEmcalParticleMaker)
//________________________________________________________________________
AliEmcalParticleMaker::AliEmcalParticleMaker() :
AliAnalysisTaskEmcal("AliEmcalParticleMaker",kFALSE),
fTracksOutName("EmcalTracks"),
fCaloOutName("EmcalClusters"),
fTracksOut(0),
fCaloClustersOut(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalParticleMaker::AliEmcalParticleMaker(const char *name) :
AliAnalysisTaskEmcal(name,kFALSE),
fTracksOutName("EmcalTracks"),
fCaloOutName("EmcalClusters"),
fTracksOut(0),
fCaloClustersOut(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalParticleMaker::~AliEmcalParticleMaker()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalParticleMaker::ExecOnce()
{
// Init the analysis.
AliAnalysisTaskEmcal::ExecOnce();
if (!fInitialized)
return;
if (!fTracksOutName.IsNull()) {
fTracksOut = new TClonesArray("AliEmcalParticle");
fTracksOut->SetName(fTracksOutName);
if (!(InputEvent()->FindListObject(fTracksOutName))) {
InputEvent()->AddObject(fTracksOut);
}
else {
fInitialized = kFALSE;
AliFatal(Form("%s: Container with same name %s already present. Aborting", GetName(), fTracksOutName.Data()));
return;
}
}
if (!fCaloOutName.IsNull()) {
fCaloClustersOut = new TClonesArray("AliEmcalParticle");
fCaloClustersOut->SetName(fCaloOutName);
// post output in event if not yet present
if (!(InputEvent()->FindListObject(fCaloOutName))) {
InputEvent()->AddObject(fCaloClustersOut);
}
else {
fInitialized = kFALSE;
AliFatal(Form("%s: Container with same name %s already present. Aborting", GetName(), fCaloOutName.Data()));
return;
}
}
}
//________________________________________________________________________
Bool_t AliEmcalParticleMaker::Run()
{
// Create the emcal particles
if (fTracks && fTracksOut) {
// clear container (normally a null operation as the event should clean it already)
fTracksOut->Delete();
// loop over tracks
const Int_t Ntracks = fTracks->GetEntries();
for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {
AliVTrack *track = static_cast<AliVTrack*>(fTracks->At(iTracks));
new ((*fTracksOut)[iTracks]) AliEmcalParticle(track, iTracks);
}
}
if (fCaloClusters && fCaloClustersOut) {
// clear container (normally a null operation as the event should clean it already)
fCaloClustersOut->Delete();
// loop over clusters
const Int_t Nclusters = fCaloClusters->GetEntries();
for (Int_t iClusters = 0, iN=0; iClusters < Nclusters; ++iClusters) {
AliVCluster *cluster = static_cast<AliVCluster*>(fCaloClusters->At(iClusters));
if (!cluster->IsEMCAL())
continue;
new ((*fCaloClustersOut)[iN++]) AliEmcalParticle(cluster, iClusters, fVertex[0], fVertex[1], fVertex[2]);
}
}
return kTRUE;
}
<commit_msg>Rely on IsEmcal in EmcalParticle to keep the ids in sync<commit_after>// $Id$
//
// Class to make emcal particles in AOD/ESD events.
//
// Author: S.Aiola
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliVTrack.h"
#include "AliVCluster.h"
#include "AliEmcalParticle.h"
#include "AliEmcalParticleMaker.h"
ClassImp(AliEmcalParticleMaker)
//________________________________________________________________________
AliEmcalParticleMaker::AliEmcalParticleMaker() :
AliAnalysisTaskEmcal("AliEmcalParticleMaker",kFALSE),
fTracksOutName("EmcalTracks"),
fCaloOutName("EmcalClusters"),
fTracksOut(0),
fCaloClustersOut(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalParticleMaker::AliEmcalParticleMaker(const char *name) :
AliAnalysisTaskEmcal(name,kFALSE),
fTracksOutName("EmcalTracks"),
fCaloOutName("EmcalClusters"),
fTracksOut(0),
fCaloClustersOut(0)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalParticleMaker::~AliEmcalParticleMaker()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalParticleMaker::ExecOnce()
{
// Init the analysis.
AliAnalysisTaskEmcal::ExecOnce();
if (!fInitialized)
return;
if (!fTracksOutName.IsNull()) {
fTracksOut = new TClonesArray("AliEmcalParticle");
fTracksOut->SetName(fTracksOutName);
if (!(InputEvent()->FindListObject(fTracksOutName))) {
InputEvent()->AddObject(fTracksOut);
}
else {
fInitialized = kFALSE;
AliFatal(Form("%s: Container with same name %s already present. Aborting", GetName(), fTracksOutName.Data()));
return;
}
}
if (!fCaloOutName.IsNull()) {
fCaloClustersOut = new TClonesArray("AliEmcalParticle");
fCaloClustersOut->SetName(fCaloOutName);
// post output in event if not yet present
if (!(InputEvent()->FindListObject(fCaloOutName))) {
InputEvent()->AddObject(fCaloClustersOut);
}
else {
fInitialized = kFALSE;
AliFatal(Form("%s: Container with same name %s already present. Aborting", GetName(), fCaloOutName.Data()));
return;
}
}
}
//________________________________________________________________________
Bool_t AliEmcalParticleMaker::Run()
{
// Create the emcal particles
if (fTracks && fTracksOut) {
// clear container (normally a null operation as the event should clean it already)
fTracksOut->Delete();
const Int_t Ntracks = fTracks->GetEntries();
for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {
AliVTrack *track = static_cast<AliVTrack*>(fTracks->At(iTracks));
new ((*fTracksOut)[iTracks]) AliEmcalParticle(track, iTracks);
}
}
if (fCaloClusters && fCaloClustersOut) {
// clear container (normally a null operation as the event should clean it already)
fCaloClustersOut->Delete();
const Int_t Nclusters = fCaloClusters->GetEntries();
for (Int_t iClusters = 0, iN=0; iClusters < Nclusters; ++iClusters) {
AliVCluster *cluster = static_cast<AliVCluster*>(fCaloClusters->At(iClusters));
/* commented because for simplicity prefer to keep indices aligned (CL)
if (!cluster->IsEMCAL())
continue;
*/
new ((*fCaloClustersOut)[iN++]) AliEmcalParticle(cluster, iClusters, fVertex[0], fVertex[1], fVertex[2]);
}
}
return kTRUE;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2005-2006 MySQL AB
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "mysql_priv.h"
#include "rpl_rli.h"
#include "base64.h"
/**
Execute a BINLOG statement
To execute the BINLOG command properly the server needs to know
which format the BINLOG command's event is in. Therefore, the first
BINLOG statement seen must be a base64 encoding of the
Format_description_log_event, as outputted by mysqlbinlog. This
Format_description_log_event is cached in
rli->description_event_for_exec.
*/
void mysql_client_binlog_statement(THD* thd)
{
DBUG_ENTER("mysql_client_binlog_statement");
DBUG_PRINT("info",("binlog base64: '%*s'",
(int) (thd->lex->comment.length < 2048 ?
thd->lex->comment.length : 2048),
thd->lex->comment.str));
if (check_global_access(thd, SUPER_ACL))
DBUG_VOID_RETURN;
size_t coded_len= thd->lex->comment.length + 1;
size_t decoded_len= base64_needed_decoded_length(coded_len);
DBUG_ASSERT(coded_len > 0);
/*
Allocation
*/
/*
If we do not have a Format_description_event, we create a dummy
one here. In this case, the first event we read must be a
Format_description_event.
*/
my_bool have_fd_event= TRUE;
if (!thd->rli_fake)
{
thd->rli_fake= new Relay_log_info;
#ifdef HAVE_purify
thd->rli_fake->is_fake= TRUE;
#endif
have_fd_event= FALSE;
}
if (thd->rli_fake && !thd->rli_fake->relay_log.description_event_for_exec)
{
thd->rli_fake->relay_log.description_event_for_exec=
new Format_description_log_event(4);
have_fd_event= FALSE;
}
const char *error= 0;
char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME));
Log_event *ev = 0;
/*
Out of memory check
*/
if (!(thd->rli_fake &&
thd->rli_fake->relay_log.description_event_for_exec &&
buf))
{
my_error(ER_OUTOFMEMORY, MYF(0), 1); /* needed 1 bytes */
goto end;
}
thd->rli_fake->sql_thd= thd;
thd->rli_fake->no_storage= TRUE;
for (char const *strptr= thd->lex->comment.str ;
strptr < thd->lex->comment.str + thd->lex->comment.length ; )
{
char const *endptr= 0;
int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr);
#ifndef HAVE_purify
/*
This debug printout should not be used for valgrind builds
since it will read from unassigned memory.
*/
DBUG_PRINT("info",
("bytes_decoded: %d strptr: 0x%lx endptr: 0x%lx ('%c':%d)",
bytes_decoded, (long) strptr, (long) endptr, *endptr,
*endptr));
#endif
if (bytes_decoded < 0)
{
my_error(ER_BASE64_DECODE_ERROR, MYF(0));
goto end;
}
else if (bytes_decoded == 0)
break; // If no bytes where read, the string contained only whitespace
DBUG_ASSERT(bytes_decoded > 0);
DBUG_ASSERT(endptr > strptr);
coded_len-= endptr - strptr;
strptr= endptr;
/*
Now we have one or more events stored in the buffer. The size of
the buffer is computed based on how much base64-encoded data
there were, so there should be ample space for the data (maybe
even too much, since a statement can consist of a considerable
number of events).
TODO: Switch to use a stream-based base64 encoder/decoder in
order to be able to read exactly what is necessary.
*/
DBUG_PRINT("info",("binlog base64 decoded_len: %lu bytes_decoded: %d",
(ulong) decoded_len, bytes_decoded));
/*
Now we start to read events of the buffer, until there are no
more.
*/
for (char *bufptr= buf ; bytes_decoded > 0 ; )
{
/*
Checking that the first event in the buffer is not truncated.
*/
ulong event_len= uint4korr(bufptr + EVENT_LEN_OFFSET);
DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d",
event_len, bytes_decoded));
if (bytes_decoded < EVENT_LEN_OFFSET || (uint) bytes_decoded < event_len)
{
my_error(ER_SYNTAX_ERROR, MYF(0));
goto end;
}
/*
If we have not seen any Format_description_event, then we must
see one; it is the only statement that can be read in base64
without a prior Format_description_event.
*/
if (!have_fd_event)
{
int type = bufptr[EVENT_TYPE_OFFSET];
if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3)
have_fd_event= TRUE;
else
{
my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT,
MYF(0), Log_event::get_type_str((Log_event_type)type));
goto end;
}
}
ev= Log_event::read_log_event(bufptr, event_len, &error,
thd->rli_fake->relay_log.
description_event_for_exec);
DBUG_PRINT("info",("binlog base64 err=%s", error));
if (!ev)
{
/*
This could actually be an out-of-memory, but it is more likely
causes by a bad statement
*/
my_error(ER_SYNTAX_ERROR, MYF(0));
goto end;
}
bytes_decoded -= event_len;
bufptr += event_len;
DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code()));
#ifndef HAVE_purify
/*
This debug printout should not be used for valgrind builds
since it will read from unassigned memory.
*/
DBUG_PRINT("info",("bufptr+EVENT_TYPE_OFFSET: 0x%lx",
(long) (bufptr+EVENT_TYPE_OFFSET)));
DBUG_PRINT("info", ("bytes_decoded: %d bufptr: 0x%lx buf[EVENT_LEN_OFFSET]: %lu",
bytes_decoded, (long) bufptr,
(ulong) uint4korr(bufptr+EVENT_LEN_OFFSET)));
#endif
ev->thd= thd;
/*
We go directly to the application phase, since we don't need
to check if the event shall be skipped or not.
Neither do we have to update the log positions, since that is
not used at all: the rli_fake instance is used only for error
reporting.
*/
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
if (apply_event_and_update_pos(ev, thd, thd->rli_fake, FALSE))
{
/*
TODO: Maybe a better error message since the BINLOG statement
now contains several events.
*/
my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement");
goto end;
}
#endif
/*
Format_description_log_event should not be deleted because it
will be used to read info about the relay log's format; it
will be deleted when the SQL thread does not need it,
i.e. when this thread terminates.
*/
if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT)
delete ev;
ev= 0;
}
}
DBUG_PRINT("info",("binlog base64 execution finished successfully"));
my_ok(thd);
end:
thd->rli_fake->clear_tables_to_lock();
my_free(buf, MYF(MY_ALLOW_ZERO_PTR));
DBUG_VOID_RETURN;
}
<commit_msg>auto merge<commit_after>/* Copyright (C) 2005-2006 MySQL AB
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "mysql_priv.h"
#include "rpl_rli.h"
#include "base64.h"
/**
Execute a BINLOG statement
To execute the BINLOG command properly the server needs to know
which format the BINLOG command's event is in. Therefore, the first
BINLOG statement seen must be a base64 encoding of the
Format_description_log_event, as outputted by mysqlbinlog. This
Format_description_log_event is cached in
rli->description_event_for_exec.
*/
void mysql_client_binlog_statement(THD* thd)
{
DBUG_ENTER("mysql_client_binlog_statement");
DBUG_PRINT("info",("binlog base64: '%*s'",
(int) (thd->lex->comment.length < 2048 ?
thd->lex->comment.length : 2048),
thd->lex->comment.str));
if (check_global_access(thd, SUPER_ACL))
DBUG_VOID_RETURN;
size_t coded_len= thd->lex->comment.length + 1;
size_t decoded_len= base64_needed_decoded_length(coded_len);
DBUG_ASSERT(coded_len > 0);
/*
Allocation
*/
/*
If we do not have a Format_description_event, we create a dummy
one here. In this case, the first event we read must be a
Format_description_event.
*/
my_bool have_fd_event= TRUE;
if (!thd->rli_fake)
{
thd->rli_fake= new Relay_log_info;
#ifdef HAVE_purify
thd->rli_fake->is_fake= TRUE;
#endif
have_fd_event= FALSE;
}
if (thd->rli_fake && !thd->rli_fake->relay_log.description_event_for_exec)
{
thd->rli_fake->relay_log.description_event_for_exec=
new Format_description_log_event(4);
have_fd_event= FALSE;
}
const char *error= 0;
char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME));
Log_event *ev = 0;
/*
Out of memory check
*/
if (!(thd->rli_fake &&
thd->rli_fake->relay_log.description_event_for_exec &&
buf))
{
my_error(ER_OUTOFMEMORY, MYF(0), 1); /* needed 1 bytes */
goto end;
}
thd->rli_fake->sql_thd= thd;
thd->rli_fake->no_storage= TRUE;
for (char const *strptr= thd->lex->comment.str ;
strptr < thd->lex->comment.str + thd->lex->comment.length ; )
{
char const *endptr= 0;
int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr);
#ifndef HAVE_purify
/*
This debug printout should not be used for valgrind builds
since it will read from unassigned memory.
*/
DBUG_PRINT("info",
("bytes_decoded: %d strptr: 0x%lx endptr: 0x%lx ('%c':%d)",
bytes_decoded, (long) strptr, (long) endptr, *endptr,
*endptr));
#endif
if (bytes_decoded < 0)
{
my_error(ER_BASE64_DECODE_ERROR, MYF(0));
goto end;
}
else if (bytes_decoded == 0)
break; // If no bytes where read, the string contained only whitespace
DBUG_ASSERT(bytes_decoded > 0);
DBUG_ASSERT(endptr > strptr);
coded_len-= endptr - strptr;
strptr= endptr;
/*
Now we have one or more events stored in the buffer. The size of
the buffer is computed based on how much base64-encoded data
there were, so there should be ample space for the data (maybe
even too much, since a statement can consist of a considerable
number of events).
TODO: Switch to use a stream-based base64 encoder/decoder in
order to be able to read exactly what is necessary.
*/
DBUG_PRINT("info",("binlog base64 decoded_len: %lu bytes_decoded: %d",
(ulong) decoded_len, bytes_decoded));
/*
Now we start to read events of the buffer, until there are no
more.
*/
for (char *bufptr= buf ; bytes_decoded > 0 ; )
{
/*
Checking that the first event in the buffer is not truncated.
*/
ulong event_len= uint4korr(bufptr + EVENT_LEN_OFFSET);
DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d",
event_len, bytes_decoded));
if (bytes_decoded < EVENT_LEN_OFFSET || (uint) bytes_decoded < event_len)
{
my_error(ER_SYNTAX_ERROR, MYF(0));
goto end;
}
/*
If we have not seen any Format_description_event, then we must
see one; it is the only statement that can be read in base64
without a prior Format_description_event.
*/
if (!have_fd_event)
{
int type = bufptr[EVENT_TYPE_OFFSET];
if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3)
have_fd_event= TRUE;
else
{
my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT,
MYF(0), Log_event::get_type_str((Log_event_type)type));
goto end;
}
}
ev= Log_event::read_log_event(bufptr, event_len, &error,
thd->rli_fake->relay_log.
description_event_for_exec);
DBUG_PRINT("info",("binlog base64 err=%s", error));
if (!ev)
{
/*
This could actually be an out-of-memory, but it is more likely
causes by a bad statement
*/
my_error(ER_SYNTAX_ERROR, MYF(0));
goto end;
}
bytes_decoded -= event_len;
bufptr += event_len;
DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code()));
#ifndef HAVE_purify
/*
This debug printout should not be used for valgrind builds
since it will read from unassigned memory.
*/
DBUG_PRINT("info",("bufptr+EVENT_TYPE_OFFSET: 0x%lx",
(long) (bufptr+EVENT_TYPE_OFFSET)));
DBUG_PRINT("info", ("bytes_decoded: %d bufptr: 0x%lx buf[EVENT_LEN_OFFSET]: %lu",
bytes_decoded, (long) bufptr,
(ulong) uint4korr(bufptr+EVENT_LEN_OFFSET)));
#endif
ev->thd= thd;
/*
We go directly to the application phase, since we don't need
to check if the event shall be skipped or not.
Neither do we have to update the log positions, since that is
not used at all: the rli_fake instance is used only for error
reporting.
*/
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
if (apply_event_and_update_pos(ev, thd, thd->rli_fake, FALSE))
{
delete ev;
/*
TODO: Maybe a better error message since the BINLOG statement
now contains several events.
*/
my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement");
goto end;
}
#endif
/*
Format_description_log_event should not be deleted because it
will be used to read info about the relay log's format; it
will be deleted when the SQL thread does not need it,
i.e. when this thread terminates.
*/
if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT)
delete ev;
ev= 0;
}
}
DBUG_PRINT("info",("binlog base64 execution finished successfully"));
my_ok(thd);
end:
thd->rli_fake->clear_tables_to_lock();
my_free(buf, MYF(MY_ALLOW_ZERO_PTR));
DBUG_VOID_RETURN;
}
<|endoftext|> |
<commit_before>#include "../../include/stupid/Service.hpp"
#include "../../include/stupid/Client.hpp"
#include "../../include/stupid/internal/CommunicationThread.hpp"
#include <base/Prompt.hpp>
namespace cutehmi {
namespace stupid {
Service::Service(const QString & name, Client * client, QObject * parent):
services::Service(name, parent),
m(new Members{std::unique_ptr<internal::CommunicationThread>(new internal::CommunicationThread(client)), client})
{
QObject::connect(m->client, & Client::error, this, & Service::handleError);
QObject::connect(m->client, & Client::connected, this, & Service::onClientConnected);
QObject::connect(m->client, & Client::disconnected, this, & Service::onClientDisconnected);
}
Service::~Service()
{
if (state() != STOPPED)
stop();
}
unsigned long Service::sleep() const
{
return m->thread->sleep();
}
void Service::setSleep(unsigned long sleep)
{
m->thread->setSleep(sleep);
}
Service::state_t Service::customStart()
{
setState(STARTING);
m->client->connect(); // onClientConnected() is connected to m->client->connected() signal.
return state();
}
Service::state_t Service::customStop()
{
if (m->thread->isRunning()) {
CUTEHMI_STUPID_QDEBUG("Stopping STUPiD client thread...");
m->thread->stop();
m->thread->quit();
m->thread->wait();
CUTEHMI_STUPID_QDEBUG("STUPiD client thread finished.");
}
setState(STOPPING);
m->client->disconnect();
return state();
}
void Service::onClientConnected()
{
CUTEHMI_STUPID_QDEBUG("Starting STUPiD client thread...");
m->thread->start();
setState(STARTED);
}
void Service::onClientDisconnected()
{
setState(STOPPED);
}
void Service::handleError(cutehmi::base::ErrorInfo errorInfo)
{
Q_UNUSED(errorInfo);
base::Prompt::Critical(errorInfo);
stop();
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<commit_msg>Remove unnecessary Q_UNUSED macro.<commit_after>#include "../../include/stupid/Service.hpp"
#include "../../include/stupid/Client.hpp"
#include "../../include/stupid/internal/CommunicationThread.hpp"
#include <base/Prompt.hpp>
namespace cutehmi {
namespace stupid {
Service::Service(const QString & name, Client * client, QObject * parent):
services::Service(name, parent),
m(new Members{std::unique_ptr<internal::CommunicationThread>(new internal::CommunicationThread(client)), client})
{
QObject::connect(m->client, & Client::error, this, & Service::handleError);
QObject::connect(m->client, & Client::connected, this, & Service::onClientConnected);
QObject::connect(m->client, & Client::disconnected, this, & Service::onClientDisconnected);
}
Service::~Service()
{
if (state() != STOPPED)
stop();
}
unsigned long Service::sleep() const
{
return m->thread->sleep();
}
void Service::setSleep(unsigned long sleep)
{
m->thread->setSleep(sleep);
}
Service::state_t Service::customStart()
{
setState(STARTING);
m->client->connect(); // onClientConnected() is connected to m->client->connected() signal.
return state();
}
Service::state_t Service::customStop()
{
if (m->thread->isRunning()) {
CUTEHMI_STUPID_QDEBUG("Stopping STUPiD client thread...");
m->thread->stop();
m->thread->quit();
m->thread->wait();
CUTEHMI_STUPID_QDEBUG("STUPiD client thread finished.");
}
setState(STOPPING);
m->client->disconnect();
return state();
}
void Service::onClientConnected()
{
CUTEHMI_STUPID_QDEBUG("Starting STUPiD client thread...");
m->thread->start();
setState(STARTED);
}
void Service::onClientDisconnected()
{
setState(STOPPED);
}
void Service::handleError(cutehmi::base::ErrorInfo errorInfo)
{
base::Prompt::Critical(errorInfo);
stop();
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datetime.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:09:05 $
*
* 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_tools.hxx"
#include <tools/datetime.hxx>
#include <rtl/math.hxx>
/*************************************************************************
|*
|* DateTime::IsBetween()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::IsBetween( const DateTime& rFrom,
const DateTime& rTo ) const
{
if ( (*this >= rFrom) && (*this <= rTo) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator >()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator >( const DateTime& rDateTime ) const
{
if ( (Date::operator>( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator>( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator <()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator <( const DateTime& rDateTime ) const
{
if ( (Date::operator<( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator<( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator >=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator >=( const DateTime& rDateTime ) const
{
if ( (Date::operator>( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator>=( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator <=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator <=( const DateTime& rDateTime ) const
{
if ( (Date::operator<( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator<=( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::GetSecFromDateTime()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
long DateTime::GetSecFromDateTime( const Date& rDate ) const
{
if ( Date::operator<( rDate ) )
return 0;
else
{
long nSec = Date( *this ) - rDate;
nSec *= 24UL*60*60;
long nHour = GetHour();
long nMin = GetMin();
nSec += (nHour*3600)+(nMin*60)+GetSec();
return nSec;
}
}
/*************************************************************************
|*
|* DateTime::GetSecFromDateTime()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
void DateTime::MakeDateTimeFromSec( const Date& rDate, ULONG nSec )
{
long nDays = nSec / (24UL*60*60);
((Date*)this)->operator=( rDate );
nSec -= nDays * (24UL*60*60);
USHORT nMin = (USHORT)(nSec / 60);
nSec -= nMin * 60;
((Time*)this)->operator=( Time( 0, nMin, (USHORT)nSec ) );
operator+=( nDays );
}
/*************************************************************************
|*
|* DateTime::operator +=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime& DateTime::operator +=( const Time& rTime )
{
Time aTime = *this;
aTime += rTime;
USHORT nHours = aTime.GetHour();
if ( aTime.GetTime() > 0 )
{
while ( nHours >= 24 )
{
Date::operator++();
nHours -= 24;
}
aTime.SetHour( nHours );
}
else if ( aTime.GetTime() != 0 )
{
while ( nHours >= 24 )
{
Date::operator--();
nHours -= 24;
}
Date::operator--();
aTime = Time( 24, 0, 0 )+aTime;
}
Time::operator=( aTime );
return *this;
}
/*************************************************************************
|*
|* DateTime::operator -=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime& DateTime::operator -=( const Time& rTime )
{
Time aTime = *this;
aTime -= rTime;
USHORT nHours = aTime.GetHour();
if ( aTime.GetTime() > 0 )
{
while ( nHours >= 24 )
{
Date::operator++();
nHours -= 24;
}
aTime.SetHour( nHours );
}
else if ( aTime.GetTime() != 0 )
{
while ( nHours >= 24 )
{
Date::operator--();
nHours -= 24;
}
Date::operator--();
aTime = Time( 24, 0, 0 )+aTime;
}
Time::operator=( aTime );
return *this;
}
/*************************************************************************
|*
|* DateTime::operator+()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, long nDays )
{
DateTime aDateTime( rDateTime );
aDateTime += nDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator-()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator -( const DateTime& rDateTime, long nDays )
{
DateTime aDateTime( rDateTime );
aDateTime -= nDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator+()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, const Time& rTime )
{
DateTime aDateTime( rDateTime );
aDateTime += rTime;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator-()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator -( const DateTime& rDateTime, const Time& rTime )
{
DateTime aDateTime( rDateTime );
aDateTime -= rTime;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator +=( double )
|*
*************************************************************************/
DateTime& DateTime::operator +=( double fTimeInDays )
{
double fInt, fFrac;
if ( fTimeInDays < 0.0 )
{
fInt = ::rtl::math::approxCeil( fTimeInDays );
fFrac = fInt <= fTimeInDays ? 0.0 : fTimeInDays - fInt;
}
else
{
fInt = ::rtl::math::approxFloor( fTimeInDays );
fFrac = fInt >= fTimeInDays ? 0.0 : fTimeInDays - fInt;
}
Date::operator+=( long(fInt) ); // full days
if ( fFrac )
{
Time aTime(0); // default ctor calls system time, we don't need that
fFrac *= 24UL * 60 * 60 * 1000; // time expressed in milliseconds
aTime.MakeTimeFromMS( long(fFrac) ); // method handles negative ms
operator+=( aTime );
}
return *this;
}
/*************************************************************************
|*
|* DateTime::operator +( double )
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, double fTimeInDays )
{
DateTime aDateTime( rDateTime );
aDateTime += fTimeInDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator -()
|*
*************************************************************************/
double operator -( const DateTime& rDateTime1, const DateTime& rDateTime2 )
{
long nDays = (const Date&) rDateTime1 - (const Date&) rDateTime2;
long nTime = rDateTime1.GetMSFromTime() - rDateTime2.GetMSFromTime();
if ( nTime )
{
double fTime = double(nTime);
fTime /= 24UL * 60 * 60 * 1000; // convert from milliseconds to fraction
if ( nDays < 0 && fTime > 0.0 )
fTime = 1.0 - fTime;
return double(nDays) + fTime;
}
return double(nDays);
}
void DateTime::GetWin32FileDateTime( sal_uInt32 & rLower, sal_uInt32 & rUpper )
{
const sal_Int64 a100nPerSecond = SAL_CONST_INT64( 10000000 );
const sal_Int64 a100nPerDay = a100nPerSecond * sal_Int64( 60 * 60 * 24 );
sal_Int64 nYears = GetYear() - 1601;
sal_Int64 nDays =
nYears * 365 +
nYears / 4 - nYears / 100 + nYears / 400 +
GetDayOfYear() - 1;
sal_Int64 aTime =
a100nPerDay * nDays +
a100nPerSecond * (
sal_Int64( GetSec() ) +
60 * sal_Int64( GetMin() ) +
60 * 60 * sal_Int64( GetHour() ) );
rLower = sal_uInt32( aTime % SAL_CONST_UINT64( 0x100000000 ) );
rUpper = sal_uInt32( aTime / SAL_CONST_UINT64( 0x100000000 ) );
}
DateTime DateTime::CreateFromWin32FileDateTime( const sal_uInt32 & rLower, const sal_uInt32 & rUpper )
{
const sal_Int64 a100nPerSecond = SAL_CONST_INT64( 10000000 );
const sal_Int64 a100nPerDay = a100nPerSecond * sal_Int64( 60 * 60 * 24 );
sal_Int64 aTime = sal_Int64(
sal_uInt64( rUpper ) * SAL_CONST_UINT64( 0x100000000 ) +
sal_uInt64( rLower ) );
sal_Int64 nDays = aTime / a100nPerDay;
sal_Int64 nYears =
( nDays -
( nDays / ( 4 * 365 ) ) +
( nDays / ( 100 * 365 ) ) -
( nDays / ( 400 * 365 ) ) ) / 365;
nDays -= nYears * 365 + nYears / 4 - nYears / 100 + nYears / 400;
USHORT nMonths = 0;
for( sal_Int64 nDaysCount = nDays; nDaysCount >= 0; )
{
nDays = nDaysCount;
nMonths ++;
nDaysCount -= Date(
1, nMonths, sal::static_int_cast< USHORT >(1601 + nYears) ).
GetDaysInMonth();
}
Date _aDate(
(USHORT)( nDays + 1 ), nMonths,
sal::static_int_cast< USHORT >(nYears + 1601) );
Time _aTime( ULONG( ( aTime / ( a100nPerSecond * 60 * 60 ) ) % sal_Int64( 24 ) ),
ULONG( ( aTime / ( a100nPerSecond * 60 ) ) % sal_Int64( 60 ) ),
ULONG( ( aTime / ( a100nPerSecond ) ) % sal_Int64( 60 ) ) );
return DateTime( _aDate, _aTime );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.84); FILE MERGED 2008/03/28 15:41:16 rt 1.9.84.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: datetime.cxx,v $
* $Revision: 1.10 $
*
* 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_tools.hxx"
#include <tools/datetime.hxx>
#include <rtl/math.hxx>
/*************************************************************************
|*
|* DateTime::IsBetween()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::IsBetween( const DateTime& rFrom,
const DateTime& rTo ) const
{
if ( (*this >= rFrom) && (*this <= rTo) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator >()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator >( const DateTime& rDateTime ) const
{
if ( (Date::operator>( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator>( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator <()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator <( const DateTime& rDateTime ) const
{
if ( (Date::operator<( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator<( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator >=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator >=( const DateTime& rDateTime ) const
{
if ( (Date::operator>( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator>=( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::operator <=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 18.05.92
|* Letzte Aenderung TH 18.05.92
|*
*************************************************************************/
BOOL DateTime::operator <=( const DateTime& rDateTime ) const
{
if ( (Date::operator<( rDateTime )) ||
(Date::operator==( rDateTime ) && Time::operator<=( rDateTime )) )
return TRUE;
else
return FALSE;
}
/*************************************************************************
|*
|* DateTime::GetSecFromDateTime()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
long DateTime::GetSecFromDateTime( const Date& rDate ) const
{
if ( Date::operator<( rDate ) )
return 0;
else
{
long nSec = Date( *this ) - rDate;
nSec *= 24UL*60*60;
long nHour = GetHour();
long nMin = GetMin();
nSec += (nHour*3600)+(nMin*60)+GetSec();
return nSec;
}
}
/*************************************************************************
|*
|* DateTime::GetSecFromDateTime()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
void DateTime::MakeDateTimeFromSec( const Date& rDate, ULONG nSec )
{
long nDays = nSec / (24UL*60*60);
((Date*)this)->operator=( rDate );
nSec -= nDays * (24UL*60*60);
USHORT nMin = (USHORT)(nSec / 60);
nSec -= nMin * 60;
((Time*)this)->operator=( Time( 0, nMin, (USHORT)nSec ) );
operator+=( nDays );
}
/*************************************************************************
|*
|* DateTime::operator +=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime& DateTime::operator +=( const Time& rTime )
{
Time aTime = *this;
aTime += rTime;
USHORT nHours = aTime.GetHour();
if ( aTime.GetTime() > 0 )
{
while ( nHours >= 24 )
{
Date::operator++();
nHours -= 24;
}
aTime.SetHour( nHours );
}
else if ( aTime.GetTime() != 0 )
{
while ( nHours >= 24 )
{
Date::operator--();
nHours -= 24;
}
Date::operator--();
aTime = Time( 24, 0, 0 )+aTime;
}
Time::operator=( aTime );
return *this;
}
/*************************************************************************
|*
|* DateTime::operator -=()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime& DateTime::operator -=( const Time& rTime )
{
Time aTime = *this;
aTime -= rTime;
USHORT nHours = aTime.GetHour();
if ( aTime.GetTime() > 0 )
{
while ( nHours >= 24 )
{
Date::operator++();
nHours -= 24;
}
aTime.SetHour( nHours );
}
else if ( aTime.GetTime() != 0 )
{
while ( nHours >= 24 )
{
Date::operator--();
nHours -= 24;
}
Date::operator--();
aTime = Time( 24, 0, 0 )+aTime;
}
Time::operator=( aTime );
return *this;
}
/*************************************************************************
|*
|* DateTime::operator+()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, long nDays )
{
DateTime aDateTime( rDateTime );
aDateTime += nDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator-()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator -( const DateTime& rDateTime, long nDays )
{
DateTime aDateTime( rDateTime );
aDateTime -= nDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator+()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, const Time& rTime )
{
DateTime aDateTime( rDateTime );
aDateTime += rTime;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator-()
|*
|* Beschreibung DATETIME.SDW
|* Ersterstellung TH 02.10.96
|* Letzte Aenderung TH 02.10.96
|*
*************************************************************************/
DateTime operator -( const DateTime& rDateTime, const Time& rTime )
{
DateTime aDateTime( rDateTime );
aDateTime -= rTime;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator +=( double )
|*
*************************************************************************/
DateTime& DateTime::operator +=( double fTimeInDays )
{
double fInt, fFrac;
if ( fTimeInDays < 0.0 )
{
fInt = ::rtl::math::approxCeil( fTimeInDays );
fFrac = fInt <= fTimeInDays ? 0.0 : fTimeInDays - fInt;
}
else
{
fInt = ::rtl::math::approxFloor( fTimeInDays );
fFrac = fInt >= fTimeInDays ? 0.0 : fTimeInDays - fInt;
}
Date::operator+=( long(fInt) ); // full days
if ( fFrac )
{
Time aTime(0); // default ctor calls system time, we don't need that
fFrac *= 24UL * 60 * 60 * 1000; // time expressed in milliseconds
aTime.MakeTimeFromMS( long(fFrac) ); // method handles negative ms
operator+=( aTime );
}
return *this;
}
/*************************************************************************
|*
|* DateTime::operator +( double )
|*
*************************************************************************/
DateTime operator +( const DateTime& rDateTime, double fTimeInDays )
{
DateTime aDateTime( rDateTime );
aDateTime += fTimeInDays;
return aDateTime;
}
/*************************************************************************
|*
|* DateTime::operator -()
|*
*************************************************************************/
double operator -( const DateTime& rDateTime1, const DateTime& rDateTime2 )
{
long nDays = (const Date&) rDateTime1 - (const Date&) rDateTime2;
long nTime = rDateTime1.GetMSFromTime() - rDateTime2.GetMSFromTime();
if ( nTime )
{
double fTime = double(nTime);
fTime /= 24UL * 60 * 60 * 1000; // convert from milliseconds to fraction
if ( nDays < 0 && fTime > 0.0 )
fTime = 1.0 - fTime;
return double(nDays) + fTime;
}
return double(nDays);
}
void DateTime::GetWin32FileDateTime( sal_uInt32 & rLower, sal_uInt32 & rUpper )
{
const sal_Int64 a100nPerSecond = SAL_CONST_INT64( 10000000 );
const sal_Int64 a100nPerDay = a100nPerSecond * sal_Int64( 60 * 60 * 24 );
sal_Int64 nYears = GetYear() - 1601;
sal_Int64 nDays =
nYears * 365 +
nYears / 4 - nYears / 100 + nYears / 400 +
GetDayOfYear() - 1;
sal_Int64 aTime =
a100nPerDay * nDays +
a100nPerSecond * (
sal_Int64( GetSec() ) +
60 * sal_Int64( GetMin() ) +
60 * 60 * sal_Int64( GetHour() ) );
rLower = sal_uInt32( aTime % SAL_CONST_UINT64( 0x100000000 ) );
rUpper = sal_uInt32( aTime / SAL_CONST_UINT64( 0x100000000 ) );
}
DateTime DateTime::CreateFromWin32FileDateTime( const sal_uInt32 & rLower, const sal_uInt32 & rUpper )
{
const sal_Int64 a100nPerSecond = SAL_CONST_INT64( 10000000 );
const sal_Int64 a100nPerDay = a100nPerSecond * sal_Int64( 60 * 60 * 24 );
sal_Int64 aTime = sal_Int64(
sal_uInt64( rUpper ) * SAL_CONST_UINT64( 0x100000000 ) +
sal_uInt64( rLower ) );
sal_Int64 nDays = aTime / a100nPerDay;
sal_Int64 nYears =
( nDays -
( nDays / ( 4 * 365 ) ) +
( nDays / ( 100 * 365 ) ) -
( nDays / ( 400 * 365 ) ) ) / 365;
nDays -= nYears * 365 + nYears / 4 - nYears / 100 + nYears / 400;
USHORT nMonths = 0;
for( sal_Int64 nDaysCount = nDays; nDaysCount >= 0; )
{
nDays = nDaysCount;
nMonths ++;
nDaysCount -= Date(
1, nMonths, sal::static_int_cast< USHORT >(1601 + nYears) ).
GetDaysInMonth();
}
Date _aDate(
(USHORT)( nDays + 1 ), nMonths,
sal::static_int_cast< USHORT >(nYears + 1601) );
Time _aTime( ULONG( ( aTime / ( a100nPerSecond * 60 * 60 ) ) % sal_Int64( 24 ) ),
ULONG( ( aTime / ( a100nPerSecond * 60 ) ) % sal_Int64( 60 ) ),
ULONG( ( aTime / ( a100nPerSecond ) ) % sal_Int64( 60 ) ) );
return DateTime( _aDate, _aTime );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/environment.h"
#include "base/memory/scoped_ptr.h"
#include "base/win/scoped_com_initializer.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_manager_base.h"
#if defined(OS_WIN)
#include "media/audio/win/audio_manager_win.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
using base::win::ScopedCOMInitializer;
using media::AudioDeviceNames;
// Test fixture which allows us to override the default enumeration API on
// Windows.
class AudioInputDeviceTest
: public ::testing::Test {
protected:
AudioInputDeviceTest() {
audio_manager_ = AudioManager::Create();
}
#if defined(OS_WIN)
bool SetMMDeviceEnumeration() {
AudioManagerWin* amw = static_cast<AudioManagerWin*>(audio_manager_.get());
// Windows Wave is used as default if Windows XP was detected =>
// return false since MMDevice is not supported on XP.
if (amw->enumeration_type() == AudioManagerWin::kWaveEnumeration)
return false;
amw->SetEnumerationType(AudioManagerWin::kMMDeviceEnumeration);
return true;
}
void SetWaveEnumeration() {
AudioManagerWin* amw = static_cast<AudioManagerWin*>(audio_manager_.get());
amw->SetEnumerationType(AudioManagerWin::kWaveEnumeration);
}
#endif
scoped_refptr<AudioManager> audio_manager_;
};
// Convenience method which ensures that we are not running on the build
// bots which lacks audio device support.
static bool CanRunAudioTests() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("CHROME_HEADLESS"))
return false;
return true;
}
// Helper method which verifies that the device list starts with a valid
// default record followed by non-default device names.
static void CheckDeviceNames(const AudioDeviceNames& device_names) {
if (!device_names.empty()) {
AudioDeviceNames::const_iterator it = device_names.begin();
// The first device in the list should always be the default device.
EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceName),
it->device_name);
EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceId), it->unique_id);
++it;
// Other devices should have non-empty name and id and should not contain
// default name or id.
while (it != device_names.end()) {
EXPECT_FALSE(it->device_name.empty());
EXPECT_FALSE(it->unique_id.empty());
EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceName),
it->device_name);
EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceId),
it->unique_id);
++it;
}
}
}
// Test that devices can be enumerated.
TEST_F(AudioInputDeviceTest, EnumerateDevices) {
if (!CanRunAudioTests())
return;
// The MMDevice API requires a correct COM environment.
ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA);
AudioDeviceNames device_names;
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
// Run additional tests for Windows since enumeration can be done using
// two different APIs. MMDevice is default for Vista and higher and Wave
// is default for XP and lower.
#if defined(OS_WIN)
// Override default enumeration API and force usage of Windows MMDevice.
// This test will only run on Windows Vista and higher.
TEST_F(AudioInputDeviceTest, EnumerateDevicesWinMMDevice) {
if (!CanRunAudioTests())
return;
// The MMDevice API requires a correct COM environment.
ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA);
AudioDeviceNames device_names;
if (!SetMMDeviceEnumeration()) {
// Usage of MMDevice will fail on XP and lower.
return;
}
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
// Override default enumeration API and force usage of Windows Wave.
// This test will run on Windows XP, Windows Vista and Windows 7.
TEST_F(AudioInputDeviceTest, EnumerateDevicesWinWave) {
if (!CanRunAudioTests())
return;
AudioDeviceNames device_names;
SetWaveEnumeration();
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
#endif
<commit_msg>Enable the AudioInputDevice tests on all try/build bots. These tests should all succeed even though the list of enumerated input devices may be empty.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/environment.h"
#include "base/memory/scoped_ptr.h"
#include "base/win/scoped_com_initializer.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_manager_base.h"
#if defined(OS_WIN)
#include "media/audio/win/audio_manager_win.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
using base::win::ScopedCOMInitializer;
using media::AudioDeviceNames;
// Test fixture which allows us to override the default enumeration API on
// Windows.
class AudioInputDeviceTest
: public ::testing::Test {
protected:
AudioInputDeviceTest() : com_init_(ScopedCOMInitializer::kMTA) {
audio_manager_ = AudioManager::Create();
}
#if defined(OS_WIN)
bool SetMMDeviceEnumeration() {
AudioManagerWin* amw = static_cast<AudioManagerWin*>(audio_manager_.get());
// Windows Wave is used as default if Windows XP was detected =>
// return false since MMDevice is not supported on XP.
if (amw->enumeration_type() == AudioManagerWin::kWaveEnumeration)
return false;
amw->SetEnumerationType(AudioManagerWin::kMMDeviceEnumeration);
return true;
}
void SetWaveEnumeration() {
AudioManagerWin* amw = static_cast<AudioManagerWin*>(audio_manager_.get());
amw->SetEnumerationType(AudioManagerWin::kWaveEnumeration);
}
#endif
// Helper method which verifies that the device list starts with a valid
// default record followed by non-default device names.
static void CheckDeviceNames(const AudioDeviceNames& device_names) {
if (!device_names.empty()) {
AudioDeviceNames::const_iterator it = device_names.begin();
// The first device in the list should always be the default device.
EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceName),
it->device_name);
EXPECT_EQ(std::string(AudioManagerBase::kDefaultDeviceId), it->unique_id);
++it;
// Other devices should have non-empty name and id and should not contain
// default name or id.
while (it != device_names.end()) {
EXPECT_FALSE(it->device_name.empty());
EXPECT_FALSE(it->unique_id.empty());
EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceName),
it->device_name);
EXPECT_NE(std::string(AudioManagerBase::kDefaultDeviceId),
it->unique_id);
++it;
}
} else {
// Log a warning so we can see the status on the build bots. No need to
// break the test though since this does successfully test the code and
// some failure cases.
LOG(WARNING) << "No input devices detected";
}
}
scoped_refptr<AudioManager> audio_manager_;
// The MMDevice API requires COM to be initialized on the current thread.
ScopedCOMInitializer com_init_;
};
// Test that devices can be enumerated.
TEST_F(AudioInputDeviceTest, EnumerateDevices) {
AudioDeviceNames device_names;
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
// Run additional tests for Windows since enumeration can be done using
// two different APIs. MMDevice is default for Vista and higher and Wave
// is default for XP and lower.
#if defined(OS_WIN)
// Override default enumeration API and force usage of Windows MMDevice.
// This test will only run on Windows Vista and higher.
TEST_F(AudioInputDeviceTest, EnumerateDevicesWinMMDevice) {
AudioDeviceNames device_names;
if (!SetMMDeviceEnumeration()) {
// Usage of MMDevice will fail on XP and lower.
LOG(WARNING) << "MM device enumeration is not supported.";
return;
}
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
// Override default enumeration API and force usage of Windows Wave.
// This test will run on Windows XP, Windows Vista and Windows 7.
TEST_F(AudioInputDeviceTest, EnumerateDevicesWinWave) {
AudioDeviceNames device_names;
SetWaveEnumeration();
audio_manager_->GetAudioInputDeviceNames(&device_names);
CheckDeviceNames(device_names);
}
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <sstream>
#include <stdexcept>
#include <SDL_image.h>
#include <GL/gl.h>
#include "Texture.h"
namespace Common {
Texture::Texture(const SDLSurface& surf, unsigned int startrow, unsigned int height)
{
setupSDLSurface(surf.getSurface(), startrow, height);
}
Texture::Texture(const char* filename, unsigned int startrow, unsigned int height)
{
SDLSurface surf(filename);
setupSDLSurface(surf.getSurface(), startrow, height);
}
Texture::Texture(const SDL_Surface* surf, unsigned int startrow, unsigned int height)
{
setupSDLSurface(surf, startrow, height);
}
void Texture::setupSDLSurface(const SDL_Surface* surf, unsigned int startrow, unsigned int height)
{
mTexture = loadTexture(surf, startrow, height);
mWidth = surf->w;
mHeight = surf->h;
}
GLuint Texture::loadTexture(const char* filename,
unsigned int startrow, unsigned int height)
{
SDLSurface surf(filename);
return loadTexture(surf.getSurface(), startrow, height);
}
GLuint Texture::loadTexture(const SDL_Surface* surf,
unsigned int startrow, unsigned int height)
{
bool hasAlpha = surf->format->BytesPerPixel == 4;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLenum format;
if(hasAlpha) {
if (surf->format->Rmask == 0x000000ff)
format = GL_RGBA;
else
format = GL_BGRA;
} else {
if (surf->format->Rmask == 0x000000ff)
format = GL_RGB;
else
format = GL_BGR;
}
glTexImage2D(GL_TEXTURE_2D, 0, surf->format->BytesPerPixel, surf->w, height ? height : surf->h,
0, format, GL_UNSIGNED_BYTE,
(char*)surf->pixels + startrow * surf->w * surf->format->BytesPerPixel);
return texture;
}
Texture::~Texture()
{
glDeleteTextures(1, &mTexture);
}
GLuint Texture::getTexture() const
{
return mTexture;
}
int Texture::getWidth() const
{
return mWidth;
}
int Texture::getHeight() const
{
return mHeight;
}
}
<commit_msg>make enums used when loading textures GL3 compatible<commit_after>#include <stdio.h>
#include <sstream>
#include <stdexcept>
#include <SDL_image.h>
#include <GL/gl.h>
#include "Texture.h"
namespace Common {
Texture::Texture(const SDLSurface& surf, unsigned int startrow, unsigned int height)
{
setupSDLSurface(surf.getSurface(), startrow, height);
}
Texture::Texture(const char* filename, unsigned int startrow, unsigned int height)
{
SDLSurface surf(filename);
setupSDLSurface(surf.getSurface(), startrow, height);
}
Texture::Texture(const SDL_Surface* surf, unsigned int startrow, unsigned int height)
{
setupSDLSurface(surf, startrow, height);
}
void Texture::setupSDLSurface(const SDL_Surface* surf, unsigned int startrow, unsigned int height)
{
mTexture = loadTexture(surf, startrow, height);
mWidth = surf->w;
mHeight = surf->h;
}
GLuint Texture::loadTexture(const char* filename,
unsigned int startrow, unsigned int height)
{
SDLSurface surf(filename);
return loadTexture(surf.getSurface(), startrow, height);
}
GLuint Texture::loadTexture(const SDL_Surface* surf,
unsigned int startrow, unsigned int height)
{
bool hasAlpha = surf->format->BytesPerPixel == 4;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLenum format;
if(hasAlpha) {
if (surf->format->Rmask == 0x000000ff)
format = GL_RGBA;
else
format = GL_BGRA;
} else {
if (surf->format->Rmask == 0x000000ff)
format = GL_RGB;
else
format = GL_BGR;
}
glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? GL_RGBA8 : GL_RGB8, surf->w, height ? height : surf->h,
0, format, GL_UNSIGNED_BYTE,
(char*)surf->pixels + startrow * surf->w * surf->format->BytesPerPixel);
return texture;
}
Texture::~Texture()
{
glDeleteTextures(1, &mTexture);
}
GLuint Texture::getTexture() const
{
return mTexture;
}
int Texture::getWidth() const
{
return mWidth;
}
int Texture::getHeight() const
{
return mHeight;
}
}
<|endoftext|> |
<commit_before>#ifndef CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
#define CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
#include <cpp-pcp-client/connector/timings.hpp>
#include <cpp-pcp-client/connector/client_metadata.hpp>
#include <cpp-pcp-client/util/thread.hpp>
#include <cpp-pcp-client/export.h>
#include <string>
#include <vector>
#include <memory>
#include <atomic>
#include <stdint.h>
// Forward declarations for boost::asio
namespace boost {
namespace asio {
namespace ssl {
class context;
}
}
} // namespace boost
// Forward declarations for websocketpp
namespace websocketpp {
template <typename T>
class client;
namespace config {
struct asio_tls_client;
}
namespace message_buffer {
namespace alloc {
template <typename message>
class con_msg_manager;
}
template <template<class> class con_msg_manager>
class message;
}
namespace lib{
using std::shared_ptr;
}
using connection_hdl = std::weak_ptr<void>;
} // namespace websocket
namespace PCPClient {
// Constants
static const std::string PING_PAYLOAD_DEFAULT { "" };
static const uint32_t CONNECTION_BACKOFF_MS { 2000 }; // [ms]
static const std::string DEFAULT_CLOSE_REASON { "Closed by client" };
// Configuration of the WebSocket transport layer
using WS_Client_Type = websocketpp::client<websocketpp::config::asio_tls_client>;
using WS_Context_Ptr = websocketpp::lib::shared_ptr<boost::asio::ssl::context>;
using WS_Connection_Handle = websocketpp::connection_hdl;
// Connection States
enum class ConnectionState {
initialized = -1,
connecting = 0,
open = 1,
closing = 2,
closed = 3
};
// Close Codes
// Implemented as a plain enum so they cast to Websocketpp's close::status::value
namespace CloseCodeValues {
enum value_ : uint16_t {
normal = 1000, // Normal connection closure
abnormal_close = 1006, // Abnormal
subprotocol_error = 3000 // Generic subprotocol error
};
} // namespace CloseCodeValues
using CloseCode = CloseCodeValues::value_;
//
// Connection
//
class LIBCPP_PCP_CLIENT_EXPORT Connection {
public:
/// The Connection class provides the necessary logic to establish
/// and use a PCP connection over WebSocket.
/// The constructor throws an connection_config_error if it fails
/// to configure the underlying WebSocket endpoint and the event
/// handlers.
Connection(std::string broker_ws_uri,
ClientMetadata client_metadata);
Connection(std::vector<std::string> broker_ws_uris,
ClientMetadata client_metadata);
~Connection();
/// Return the connection state
ConnectionState getConnectionState() const;
/// Set the onOpen callback.
void setOnOpenCallback(std::function<void()> onOpen_callback);
/// Set the onMessage callback
void setOnMessageCallback(
std::function<void(std::string msg)> onMessage_callback);
// Reset the onMessage and postLogin callbacks
void resetCallbacks();
/// Check the state of the WebSocket connection; in case it's not
/// open, try to re-open it.
/// Try to reopen for max_connect_attempts times or idefinetely,
/// in case that parameter is 0 (as by default). This is done by
/// following an exponential backoff.
/// Throw a connection_processing_error in case of error during a
/// connection attempt.
/// Throw a connection_fatal_error in case in case it doesn't
/// succeed after max_connect_attempts attempts.
void connect(int max_connect_attempts = 0);
/// Send a message to the broker.
/// Throw a connection_processing_error in case of failure while
/// sending.
void send(const std::string& msg);
void send(void* const serialized_msg_ptr, size_t msg_len);
/// Ping the broker.
/// Throw a connection_processing_error in case of failure.
void ping(const std::string& binary_payload = PING_PAYLOAD_DEFAULT);
/// Close the connection; reason and code are optional
/// (respectively default to "Closed by client" and 'normal' as
/// in rfc6455).
/// Throw a connection_processing_error in case of failure.
void close(CloseCode code = CloseCodeValues::normal,
const std::string& reason = DEFAULT_CLOSE_REASON);
private:
/// WebSocket URIs of PCP brokers; first entry is the default
std::vector<std::string> broker_ws_uris_;
/// Client metadata
ClientMetadata client_metadata_;
/// Transport layer connection handle
WS_Connection_Handle connection_handle_;
/// State of the connection (initialized, connecting, open,
/// closing, or closed)
std::atomic<ConnectionState> connection_state_;
/// Tracks the broker we should be trying to connect to.
/// Defaults to 0, and increments when a successful
/// connection and the first reconnect attempt against that
/// connection fail, or when an attempt to connect to a new
/// broker fails. This value modulo size of the broker list
/// identifies the current broker to target.
std::atomic<size_t> connection_target_index_;
/// Consecutive pong timeouts counter (NB: useful for debug msgs)
uint32_t consecutive_pong_timeouts_ { 0 };
/// Transport layer endpoint instance
std::unique_ptr<WS_Client_Type> endpoint_;
/// Transport layer event loop thread
std::shared_ptr<Util::thread> endpoint_thread_;
// Callback function called by the onOpen handler.
std::function<void()> onOpen_callback;
/// Callback function executed by the onMessage handler
std::function<void(const std::string& message)> onMessage_callback_;
/// Exponential backoff interval for re-connect
uint32_t connection_backoff_ms_ { CONNECTION_BACKOFF_MS };
/// Keep track of connection timings
ConnectionTimings connection_timings_;
/// To manage the connection state
Util::mutex state_mutex_;
/// Connect and wait until the connection is open or for the
/// configured connection_timeout
void connectAndWait();
/// Try closing the connection
void tryClose();
/// Stop the event loop thread and perform the necessary clean up
void cleanUp();
// Connect the endpoint
void connect_();
/// Return the current broker WebSocket URI to target
std::string const& getWsUri();
/// Switch broker WebSocket URI targets
void switchWsUri();
/// Event handlers
WS_Context_Ptr onTlsInit(WS_Connection_Handle hdl);
void onClose(WS_Connection_Handle hdl);
void onFail(WS_Connection_Handle hdl);
bool onPing(WS_Connection_Handle hdl, std::string binary_payload);
void onPong(WS_Connection_Handle hdl, std::string binary_payload);
void onPongTimeout(WS_Connection_Handle hdl, std::string binary_payload);
void onPreTCPInit(WS_Connection_Handle hdl);
void onPostTCPInit(WS_Connection_Handle hdl);
/// Handler executed by the transport layer in case of a
/// WebSocket onOpen event. Calls onOpen_callback_(); in case it
/// fails, the exception is filtered and the connection is closed.
void onOpen(WS_Connection_Handle hdl);
/// Handler executed by the transport layer in case of a
/// WebSocket onMessage event. Calls onMessage_callback_();
/// in case it fails, the exception is filtered and logged.
void onMessage(
WS_Connection_Handle hdl,
std::shared_ptr<
class websocketpp::message_buffer::message<
websocketpp::message_buffer::alloc::con_msg_manager>> msg);
};
} // namespace PCPClient
#endif // CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
<commit_msg>(maint) Fix typo in docstring<commit_after>#ifndef CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
#define CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
#include <cpp-pcp-client/connector/timings.hpp>
#include <cpp-pcp-client/connector/client_metadata.hpp>
#include <cpp-pcp-client/util/thread.hpp>
#include <cpp-pcp-client/export.h>
#include <string>
#include <vector>
#include <memory>
#include <atomic>
#include <stdint.h>
// Forward declarations for boost::asio
namespace boost {
namespace asio {
namespace ssl {
class context;
}
}
} // namespace boost
// Forward declarations for websocketpp
namespace websocketpp {
template <typename T>
class client;
namespace config {
struct asio_tls_client;
}
namespace message_buffer {
namespace alloc {
template <typename message>
class con_msg_manager;
}
template <template<class> class con_msg_manager>
class message;
}
namespace lib{
using std::shared_ptr;
}
using connection_hdl = std::weak_ptr<void>;
} // namespace websocket
namespace PCPClient {
// Constants
static const std::string PING_PAYLOAD_DEFAULT { "" };
static const uint32_t CONNECTION_BACKOFF_MS { 2000 }; // [ms]
static const std::string DEFAULT_CLOSE_REASON { "Closed by client" };
// Configuration of the WebSocket transport layer
using WS_Client_Type = websocketpp::client<websocketpp::config::asio_tls_client>;
using WS_Context_Ptr = websocketpp::lib::shared_ptr<boost::asio::ssl::context>;
using WS_Connection_Handle = websocketpp::connection_hdl;
// Connection States
enum class ConnectionState {
initialized = -1,
connecting = 0,
open = 1,
closing = 2,
closed = 3
};
// Close Codes
// Implemented as a plain enum so they cast to Websocketpp's close::status::value
namespace CloseCodeValues {
enum value_ : uint16_t {
normal = 1000, // Normal connection closure
abnormal_close = 1006, // Abnormal
subprotocol_error = 3000 // Generic subprotocol error
};
} // namespace CloseCodeValues
using CloseCode = CloseCodeValues::value_;
//
// Connection
//
class LIBCPP_PCP_CLIENT_EXPORT Connection {
public:
/// The Connection class provides the necessary logic to establish
/// and use a PCP connection over WebSocket.
/// The constructor throws an connection_config_error if it fails
/// to configure the underlying WebSocket endpoint and the event
/// handlers.
Connection(std::string broker_ws_uri,
ClientMetadata client_metadata);
Connection(std::vector<std::string> broker_ws_uris,
ClientMetadata client_metadata);
~Connection();
/// Return the connection state
ConnectionState getConnectionState() const;
/// Set the onOpen callback.
void setOnOpenCallback(std::function<void()> onOpen_callback);
/// Set the onMessage callback
void setOnMessageCallback(
std::function<void(std::string msg)> onMessage_callback);
// Reset the onMessage and postLogin callbacks
void resetCallbacks();
/// Check the state of the WebSocket connection; in case it's not
/// open, try to re-open it.
/// Try to reopen for max_connect_attempts times or indefinitely,
/// in case that parameter is 0 (as by default). This is done by
/// following an exponential backoff.
/// Throw a connection_processing_error in case of error during a
/// connection attempt.
/// Throw a connection_fatal_error in case in case it doesn't
/// succeed after max_connect_attempts attempts.
void connect(int max_connect_attempts = 0);
/// Send a message to the broker.
/// Throw a connection_processing_error in case of failure while
/// sending.
void send(const std::string& msg);
void send(void* const serialized_msg_ptr, size_t msg_len);
/// Ping the broker.
/// Throw a connection_processing_error in case of failure.
void ping(const std::string& binary_payload = PING_PAYLOAD_DEFAULT);
/// Close the connection; reason and code are optional
/// (respectively default to "Closed by client" and 'normal' as
/// in rfc6455).
/// Throw a connection_processing_error in case of failure.
void close(CloseCode code = CloseCodeValues::normal,
const std::string& reason = DEFAULT_CLOSE_REASON);
private:
/// WebSocket URIs of PCP brokers; first entry is the default
std::vector<std::string> broker_ws_uris_;
/// Client metadata
ClientMetadata client_metadata_;
/// Transport layer connection handle
WS_Connection_Handle connection_handle_;
/// State of the connection (initialized, connecting, open,
/// closing, or closed)
std::atomic<ConnectionState> connection_state_;
/// Tracks the broker we should be trying to connect to.
/// Defaults to 0, and increments when a successful
/// connection and the first reconnect attempt against that
/// connection fail, or when an attempt to connect to a new
/// broker fails. This value modulo size of the broker list
/// identifies the current broker to target.
std::atomic<size_t> connection_target_index_;
/// Consecutive pong timeouts counter (NB: useful for debug msgs)
uint32_t consecutive_pong_timeouts_ { 0 };
/// Transport layer endpoint instance
std::unique_ptr<WS_Client_Type> endpoint_;
/// Transport layer event loop thread
std::shared_ptr<Util::thread> endpoint_thread_;
// Callback function called by the onOpen handler.
std::function<void()> onOpen_callback;
/// Callback function executed by the onMessage handler
std::function<void(const std::string& message)> onMessage_callback_;
/// Exponential backoff interval for re-connect
uint32_t connection_backoff_ms_ { CONNECTION_BACKOFF_MS };
/// Keep track of connection timings
ConnectionTimings connection_timings_;
/// To manage the connection state
Util::mutex state_mutex_;
/// Connect and wait until the connection is open or for the
/// configured connection_timeout
void connectAndWait();
/// Try closing the connection
void tryClose();
/// Stop the event loop thread and perform the necessary clean up
void cleanUp();
// Connect the endpoint
void connect_();
/// Return the current broker WebSocket URI to target
std::string const& getWsUri();
/// Switch broker WebSocket URI targets
void switchWsUri();
/// Event handlers
WS_Context_Ptr onTlsInit(WS_Connection_Handle hdl);
void onClose(WS_Connection_Handle hdl);
void onFail(WS_Connection_Handle hdl);
bool onPing(WS_Connection_Handle hdl, std::string binary_payload);
void onPong(WS_Connection_Handle hdl, std::string binary_payload);
void onPongTimeout(WS_Connection_Handle hdl, std::string binary_payload);
void onPreTCPInit(WS_Connection_Handle hdl);
void onPostTCPInit(WS_Connection_Handle hdl);
/// Handler executed by the transport layer in case of a
/// WebSocket onOpen event. Calls onOpen_callback_(); in case it
/// fails, the exception is filtered and the connection is closed.
void onOpen(WS_Connection_Handle hdl);
/// Handler executed by the transport layer in case of a
/// WebSocket onMessage event. Calls onMessage_callback_();
/// in case it fails, the exception is filtered and logged.
void onMessage(
WS_Connection_Handle hdl,
std::shared_ptr<
class websocketpp::message_buffer::message<
websocketpp::message_buffer::alloc::con_msg_manager>> msg);
};
} // namespace PCPClient
#endif // CPP_PCP_CLIENT_SRC_CONNECTOR_CONNECTION_H_
<|endoftext|> |
<commit_before>
#include "film.h"
#include <numeric>
#include <iterator>
#include <algorithm>
using std::transform;
using std::back_inserter;
using std::copy;
using std::cout;
using std::ostream_iterator;
using std::accumulate;
Film::Film(uint w_, uint h_, ImageSampleFilter* f) : width(w_), height(h_), plate(w_ * h_), filter(f)
{
}
void Film::add_sample(const PixelSample& ps, const spectrum& s)
{
filter->add_sample(this, ps, s);
}
vector<spectrum> Film::pixel_list() const
{
vector<spectrum> ret;
transform(plate.begin(), plate.end(), std::back_inserter(ret),
[] (const FilmPixel& s) { return s.total / s.weight; });
return ret;
}
void Film::render_to_ppm(ostream& out, ToneMapper* mapper)
{
vector<spectrum> final;
vector<spectrum> raw = pixel_list();
mapper->tonemap(raw, final, width, height);
out << "P3 " << width << " " << height << " 255\n";
int i = 0;
for (auto& c: final)
{
out << int(c.x * 255) << " " << int(c.y * 255) << " " << int(c.z * 255) << " ";
if (++i % height == 0)
out << "\n";
}
}
void Film::render_to_console(ostream& out)
{
for (int y = height - 1; y >= 0; --y)
{
for (uint x = 0; x < width; ++x)
{
spectrum s = plate[index(x,y)].total;
if (norm(s) > 0.5)
out << '*';
else if (norm(s) > 0.25)
out << '.';
else
out << ' ';
}
out << '\n';
}
}
////////////////////////////////////////////////////////////////////////////////
void BoxFilter::add_sample(Film* film, const PixelSample& p, const spectrum& s) const
{
FilmPixel& fp = film->at(p.x, p.y);
fp.total += s;
fp.weight += 1;
}
////////////////////////////////////////////////////////////////////////////////
void CutoffToneMapper::tonemap(const vector<spectrum>& input, vector<spectrum>& output,
uint w, uint h) const
{
transform(input.begin(), input.end(), std::back_inserter(output),
[](const spectrum& s) { return s.clamp(0.0, 1.0); });
}
void LinearToneMapper::tonemap(const vector<spectrum>& input, vector<spectrum>& output,
uint w, uint h) const
{
spectrum M = accumulate(input.begin(), input.end(), spectrum::one, spectrum::max);
scalar cM = max(max(M.x, M.y), M.z);
transform(input.begin(), input.end(), std::back_inserter(output),
[&](const spectrum& s) { return s / cM; });
}
<commit_msg>PPM image output is no longer y-flipped<commit_after>
#include "film.h"
#include <numeric>
#include <iterator>
#include <algorithm>
using std::transform;
using std::back_inserter;
using std::copy;
using std::cout;
using std::ostream_iterator;
using std::accumulate;
Film::Film(uint w_, uint h_, ImageSampleFilter* f) : width(w_), height(h_), plate(w_ * h_), filter(f)
{
}
void Film::add_sample(const PixelSample& ps, const spectrum& s)
{
filter->add_sample(this, ps, s);
}
vector<spectrum> Film::pixel_list() const
{
vector<spectrum> ret;
for (const auto& p: plate)
ret.push_back( p.total / p.weight );
return ret;
}
void Film::render_to_ppm(ostream& out, ToneMapper* mapper)
{
vector<spectrum> final;
vector<spectrum> raw = pixel_list();
mapper->tonemap(raw, final, width, height);
out << "P3 " << width << " " << height << " 255\n";
for (int y = height - 1; y >= 0; --y)
{
for(uint x = 0; x < width; ++x)
{
const auto& c = final[index(x, y)];
out << int(c.x * 255) << " " << int(c.y * 255) << " " << int(c.z * 255) << " ";
}
out << "\n";
}
}
void Film::render_to_console(ostream& out)
{
for (int y = height - 1; y >= 0; --y)
{
for (uint x = 0; x < width; ++x)
{
spectrum s = plate[index(x,y)].total;
if (norm(s) > 0.5)
out << '*';
else if (norm(s) > 0.25)
out << '.';
else
out << ' ';
}
out << '\n';
}
}
////////////////////////////////////////////////////////////////////////////////
void BoxFilter::add_sample(Film* film, const PixelSample& p, const spectrum& s) const
{
FilmPixel& fp = film->at(p.x, p.y);
fp.total += s;
fp.weight += 1;
}
////////////////////////////////////////////////////////////////////////////////
void CutoffToneMapper::tonemap(const vector<spectrum>& input, vector<spectrum>& output,
uint w, uint h) const
{
transform(input.begin(), input.end(), std::back_inserter(output),
[](const spectrum& s) { return s.clamp(0.0, 1.0); });
}
void LinearToneMapper::tonemap(const vector<spectrum>& input, vector<spectrum>& output,
uint w, uint h) const
{
spectrum M = accumulate(input.begin(), input.end(), spectrum::one, spectrum::max);
scalar cM = max(max(M.x, M.y), M.z);
transform(input.begin(), input.end(), std::back_inserter(output),
[&](const spectrum& s) { return s / cM; });
}
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Berlin/Console.hh"
#include <Prague/Sys/FdSet.hh>
#include <Prague/Sys/Tracer.hh>
using namespace Prague;
using namespace Warsaw;
vector<DrawableTie<GGIDrawable> *> GGIConsole::drawables;
GGIConsole::GGIConsole()// throw (exception)
: autoplay(false)
{
ggiInit();
GGIDrawable *drawable = new GGIDrawable(0);
visual = drawable->vis;
size[0] = drawable->mode.visible.x;
size[1] = drawable->mode.visible.y;
pos[0] = 0;
pos[1] = 0;
res[0] = 0.1 * drawable->mode.visible.x / drawable->mode.size.x;
res[1] = 0.1 * drawable->mode.visible.y / drawable->mode.size.y;
drawables.push_back(new DrawableTie<Drawable>(drawable));
pipe(wakeupPipe);
}
GGIConsole::~GGIConsole()
{
for (vector<DrawableTie<GGIDrawable> *>::iterator i = drawables.begin(); i != drawables.end(); i++) delete *i;
close(wakeupPipe[0]);
close(wakeupPipe[1]);
ggiExit();
}
DrawableTie<GGIDrawable> *GGIConsole::drawable()
{
Trace trace("GGIConsole::drawable");
// if (!drawables.size()) drawables.push_back(new DrawableTie<Drawable>(new GGIDrawable(0)));
return drawables.front();
}
DrawableTie<GGIDrawable> *GGIConsole::newDrawable(PixelCoord w, PixelCoord h, PixelCoord d)
{
GGIDrawable *drawable = new GGIDrawable("display-memory");
long depth = GGI_AUTO;
switch (d)
{
case 1: depth = GT_8BIT; break;
case 2: depth = GT_16BIT; break;
case 3: depth = GT_24BIT; break;
case 4: depth = GT_32BIT; break;
default:
cerr << "GGIConsole: Warning: " << d << " bytes per pixel not supported" << endl;
break;
};
ggiSetGraphMode(drawable->vis, w, h, w, h, depth);
return new DrawableTie<GGIDrawable>(drawable);
}
static void readEvent(ggi_event &e)
{
unsigned int t;
cin >> t;
e.any.type = (char)t;
switch (e.any.type)
{
case evKeyPress:
case evKeyRepeat:
{
cin >> t;
e.key.sym = t;
break;
}
case evPtrRelative:
case evPtrAbsolute:
{
cin >> e.pmove.x
>> e.pmove.y;
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
break;
}
}
}
static void writeEvent(ggi_event &e)
{
cout << ((unsigned int)(e.any.type)) << ' ';
switch (e.any.type)
{
case evKeyPress:
case evKeyRepeat:
{
cout << ((unsigned int)(e.key.sym));
break;
}
case evPtrRelative:
case evPtrAbsolute:
{
cout << e.pmove.x << ' '
<< e.pmove.y;
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
break;
}
}
cout << endl;
}
Input::Event *GGIConsole::nextEvent()
{
Prague::Trace trace("GGI::Console::nextEvent");
ggi_event event;
ggi_event_mask mask = ggi_event_mask (emKeyboard | emPtrMove | emPtrButtonPress | emPtrButtonRelease);
ggi_event_mask move_mask = ggi_event_mask (emPtrMove);
int input = fileno(stdin);
Prague::FdSet rfdset;
rfdset.set(wakeupPipe[0]);
if (autoplay) rfdset.set(input);
int nfds = ggiEventSelect(visual, &mask, rfdset.max() + 1, rfdset, 0, 0, 0);
if (nfds == 0)
{
// no input from the outside world
ggiEventRead(visual, &event, mask);
if (event.any.type == evPtrRelative || event.any.type == evPtrAbsolute)
{
int m = ggiEventsQueued(visual, mask);
int n = ggiEventsQueued(visual, move_mask);
if (m == n) // nothing but a bunch of moves queued up
{
int x = event.pmove.x, y = event.pmove.y;
for (int i = 0; i < n; ++i)
{
// consume them all
ggiEventRead(visual, &event, move_mask);
if (event.any.type == evPtrRelative)
{
x += event.pmove.x;
y += event.pmove.y;
}
}
if (event.any.type == evPtrRelative)
{
event.pmove.x = x;
event.pmove.y = y;
}
}
}
if (autoplay) writeEvent(event);
return synthesize(event);
}
else
{
if (autoplay && rfdset.isset(input))
{
readEvent(event);
return synthesize(event);
}
else
{
if (rfdset.isset(wakeupPipe[0]))
{
char c; read(wakeupPipe[0], &c, 1);
return 0;
}
}
}
return 0;
}
void GGIConsole::wakeup() { char c = 'z'; write(wakeupPipe[1],&c,1);}
Input::Event *GGIConsole::synthesize(const ggi_event &e)
{
Input::Event_var event = new Input::Event;
switch (e.any.type)
{
case evKeyPress:
{
Input::Toggle toggle;
toggle.actuation = Input::Toggle::press;
toggle.number = e.key.sym;
event->length(1);
event[0].dev = 0;
event[0].attr.selection(toggle); event[0].attr._d(Input::key);
break;
}
case evKeyRepeat:
{
Input::Toggle toggle;
toggle.actuation = Input::Toggle::hold;
toggle.number = e.key.sym;
event->length(1);
event[0].dev = 0;
event[0].attr.selection(toggle); event[0].attr._d(Input::key);
break;
}
case evPtrRelative:
{
if (pos[0] + e.pmove.x >= 0 && pos[0] + e.pmove.x < size[0]) pos[0] += e.pmove.x;
if (pos[1] + e.pmove.y >= 0 && pos[1] + e.pmove.y < size[1]) pos[1] += e.pmove.y;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(1);
event[0].dev = 1;
event[0].attr.location(position);
break;
}
case evPtrAbsolute:
{
pos[0] = e.pmove.x;
pos[1] = e.pmove.y;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(1);
event[0].dev = 1;
event[0].attr.location(position);
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
Input::Toggle toggle;
if (e.any.type == evPtrButtonPress)
toggle.actuation = Input::Toggle::press;
else
toggle.actuation = Input::Toggle::release;
toggle.number = e.pbutton.button;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(2);
event[0].dev = 1;
event[0].attr.selection(toggle); event[0].attr._d(Input::button);
event[1].dev = 1;
event[1].attr.location(position);
break;
}
}
return event._retn();
}
GGIDrawable::GGIDrawable(const char *display) // throw (exception)
{
if (display) vis = ggiOpen(display, 0);
else vis = ggiOpen(0);
if (!vis) throw exception();
mode.visible.x = mode.visible.y = GGI_AUTO;
mode.virt.x = mode.virt.y = GGI_AUTO;
mode.size.x = GGI_AUTO;
mode.size.y = GGI_AUTO;
mode.dpp.x = mode.dpp.y = 1;
mode.graphtype = GT_AUTO;
mode.frames = 1;
if (ggiCheckMode(vis, &mode) == 0)
{
// Cannot set visual, even though GGI says it's ok???
if (ggiSetMode(vis, &mode) != 0) throw exception();
}
else
{
// Hmm. internal GGI problem. The mode GGI gave us still won't work.
if (ggiCheckMode(vis, &mode) != 0 || ggiSetMode(vis, &mode) != 0) throw exception();
}
mode.size = mode.visible; // awful hack around a ggi bug...
ggiAddFlags(vis, GGIFLAG_ASYNC);
}
GGIDrawable::~GGIDrawable()
{
ggiClose(vis);
}
DrawableTie<GGIDrawable>::PixelFormat GGIDrawable::pixelFormat()
{
DrawableTie<GGIDrawable>::PixelFormat format;
const ggi_pixelformat *pf = ggiGetPixelFormat(vis);
format.depth = pf->depth;
format.size = pf->size;
format.red_mask = pf->red_mask;
format.red_shift = pf->red_shift;
format.green_mask = pf->green_mask;
format.green_shift = pf->green_shift;
format.blue_mask = pf->blue_mask;
format.blue_shift = pf->blue_shift;
format.alpha_mask = pf->alpha_mask;
format.alpha_shift = pf->alpha_shift;
return format;
}
<commit_msg>little compatibility fix<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Berlin/Console.hh"
#include <Prague/Sys/FdSet.hh>
#include <Prague/Sys/Tracer.hh>
using namespace Prague;
using namespace Warsaw;
vector<DrawableTie<GGIDrawable> *> GGIConsole::drawables;
GGIConsole::GGIConsole(int &argc, char **argv)// throw (exception)
: autoplay(false)
{
ggiInit();
GGIDrawable *drawable = new GGIDrawable(0);
visual = drawable->vis;
size[0] = drawable->mode.visible.x;
size[1] = drawable->mode.visible.y;
pos[0] = 0;
pos[1] = 0;
res[0] = 0.1 * drawable->mode.visible.x / drawable->mode.size.x;
res[1] = 0.1 * drawable->mode.visible.y / drawable->mode.size.y;
drawables.push_back(new DrawableTie<Drawable>(drawable));
pipe(wakeupPipe);
}
GGIConsole::~GGIConsole()
{
for (vector<DrawableTie<GGIDrawable> *>::iterator i = drawables.begin(); i != drawables.end(); i++) delete *i;
close(wakeupPipe[0]);
close(wakeupPipe[1]);
ggiExit();
}
DrawableTie<GGIDrawable> *GGIConsole::drawable()
{
Trace trace("GGIConsole::drawable");
// if (!drawables.size()) drawables.push_back(new DrawableTie<Drawable>(new GGIDrawable(0)));
return drawables.front();
}
DrawableTie<GGIDrawable> *GGIConsole::newDrawable(PixelCoord w, PixelCoord h, PixelCoord d)
{
GGIDrawable *drawable = new GGIDrawable("display-memory");
long depth = GGI_AUTO;
switch (d)
{
case 1: depth = GT_8BIT; break;
case 2: depth = GT_16BIT; break;
case 3: depth = GT_24BIT; break;
case 4: depth = GT_32BIT; break;
default:
cerr << "GGIConsole: Warning: " << d << " bytes per pixel not supported" << endl;
break;
};
ggiSetGraphMode(drawable->vis, w, h, w, h, depth);
return new DrawableTie<GGIDrawable>(drawable);
}
static void readEvent(ggi_event &e)
{
unsigned int t;
cin >> t;
e.any.type = (char)t;
switch (e.any.type)
{
case evKeyPress:
case evKeyRepeat:
{
cin >> t;
e.key.sym = t;
break;
}
case evPtrRelative:
case evPtrAbsolute:
{
cin >> e.pmove.x
>> e.pmove.y;
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
break;
}
}
}
static void writeEvent(ggi_event &e)
{
cout << ((unsigned int)(e.any.type)) << ' ';
switch (e.any.type)
{
case evKeyPress:
case evKeyRepeat:
{
cout << ((unsigned int)(e.key.sym));
break;
}
case evPtrRelative:
case evPtrAbsolute:
{
cout << e.pmove.x << ' '
<< e.pmove.y;
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
break;
}
}
cout << endl;
}
Input::Event *GGIConsole::nextEvent()
{
Prague::Trace trace("GGI::Console::nextEvent");
ggi_event event;
ggi_event_mask mask = ggi_event_mask (emKeyboard | emPtrMove | emPtrButtonPress | emPtrButtonRelease);
ggi_event_mask move_mask = ggi_event_mask (emPtrMove);
int input = fileno(stdin);
Prague::FdSet rfdset;
rfdset.set(wakeupPipe[0]);
if (autoplay) rfdset.set(input);
int nfds = ggiEventSelect(visual, &mask, rfdset.max() + 1, rfdset, 0, 0, 0);
if (nfds == 0)
{
// no input from the outside world
ggiEventRead(visual, &event, mask);
if (event.any.type == evPtrRelative || event.any.type == evPtrAbsolute)
{
int m = ggiEventsQueued(visual, mask);
int n = ggiEventsQueued(visual, move_mask);
if (m == n) // nothing but a bunch of moves queued up
{
int x = event.pmove.x, y = event.pmove.y;
for (int i = 0; i < n; ++i)
{
// consume them all
ggiEventRead(visual, &event, move_mask);
if (event.any.type == evPtrRelative)
{
x += event.pmove.x;
y += event.pmove.y;
}
}
if (event.any.type == evPtrRelative)
{
event.pmove.x = x;
event.pmove.y = y;
}
}
}
if (autoplay) writeEvent(event);
return synthesize(event);
}
else
{
if (autoplay && rfdset.isset(input))
{
readEvent(event);
return synthesize(event);
}
else
{
if (rfdset.isset(wakeupPipe[0]))
{
char c; read(wakeupPipe[0], &c, 1);
return 0;
}
}
}
return 0;
}
void GGIConsole::wakeup() { char c = 'z'; write(wakeupPipe[1],&c,1);}
Input::Event *GGIConsole::synthesize(const ggi_event &e)
{
Input::Event_var event = new Input::Event;
switch (e.any.type)
{
case evKeyPress:
{
Input::Toggle toggle;
toggle.actuation = Input::Toggle::press;
toggle.number = e.key.sym;
event->length(1);
event[0].dev = 0;
event[0].attr.selection(toggle); event[0].attr._d(Input::key);
break;
}
case evKeyRepeat:
{
Input::Toggle toggle;
toggle.actuation = Input::Toggle::hold;
toggle.number = e.key.sym;
event->length(1);
event[0].dev = 0;
event[0].attr.selection(toggle); event[0].attr._d(Input::key);
break;
}
case evPtrRelative:
{
if (pos[0] + e.pmove.x >= 0 && pos[0] + e.pmove.x < size[0]) pos[0] += e.pmove.x;
if (pos[1] + e.pmove.y >= 0 && pos[1] + e.pmove.y < size[1]) pos[1] += e.pmove.y;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(1);
event[0].dev = 1;
event[0].attr.location(position);
break;
}
case evPtrAbsolute:
{
pos[0] = e.pmove.x;
pos[1] = e.pmove.y;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(1);
event[0].dev = 1;
event[0].attr.location(position);
break;
}
case evPtrButtonPress:
case evPtrButtonRelease:
{
Input::Toggle toggle;
if (e.any.type == evPtrButtonPress)
toggle.actuation = Input::Toggle::press;
else
toggle.actuation = Input::Toggle::release;
toggle.number = e.pbutton.button;
Input::Position position;
position.x = pos[0]/res[0];
position.y = pos[1]/res[1];
position.z = 0;
event->length(2);
event[0].dev = 1;
event[0].attr.selection(toggle); event[0].attr._d(Input::button);
event[1].dev = 1;
event[1].attr.location(position);
break;
}
}
return event._retn();
}
GGIDrawable::GGIDrawable(const char *display) // throw (exception)
{
if (display) vis = ggiOpen(display, 0);
else vis = ggiOpen(0);
if (!vis) throw exception();
mode.visible.x = mode.visible.y = GGI_AUTO;
mode.virt.x = mode.virt.y = GGI_AUTO;
mode.size.x = GGI_AUTO;
mode.size.y = GGI_AUTO;
mode.dpp.x = mode.dpp.y = 1;
mode.graphtype = GT_AUTO;
mode.frames = 1;
if (ggiCheckMode(vis, &mode) == 0)
{
// Cannot set visual, even though GGI says it's ok???
if (ggiSetMode(vis, &mode) != 0) throw exception();
}
else
{
// Hmm. internal GGI problem. The mode GGI gave us still won't work.
if (ggiCheckMode(vis, &mode) != 0 || ggiSetMode(vis, &mode) != 0) throw exception();
}
mode.size = mode.visible; // awful hack around a ggi bug...
ggiAddFlags(vis, GGIFLAG_ASYNC);
}
GGIDrawable::~GGIDrawable()
{
ggiClose(vis);
}
DrawableTie<GGIDrawable>::PixelFormat GGIDrawable::pixelFormat()
{
DrawableTie<GGIDrawable>::PixelFormat format;
const ggi_pixelformat *pf = ggiGetPixelFormat(vis);
format.depth = pf->depth;
format.size = pf->size;
format.red_mask = pf->red_mask;
format.red_shift = pf->red_shift;
format.green_mask = pf->green_mask;
format.green_shift = pf->green_shift;
format.blue_mask = pf->blue_mask;
format.blue_shift = pf->blue_shift;
format.alpha_mask = pf->alpha_mask;
format.alpha_shift = pf->alpha_shift;
return format;
}
<|endoftext|> |
<commit_before>#include "cmake.h"
#include "sourcefile.h"
#include <regex>
#include "singletons.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
CMake::CMake(const boost::filesystem::path &path) {
const auto find_cmake_project=[this](const boost::filesystem::path &cmake_path) {
for(auto &line: juci::filesystem::read_lines(cmake_path)) {
const std::regex project_regex("^ *project *\\(.*$");
std::smatch sm;
if(std::regex_match(line, sm, project_regex)) {
return true;
}
}
return false;
};
auto search_path=boost::filesystem::path(path);
auto search_cmake_path=search_path;
search_cmake_path+="/CMakeLists.txt";
if(boost::filesystem::exists(search_cmake_path))
paths.emplace(paths.begin(), search_cmake_path);
if(find_cmake_project(search_cmake_path))
project_path=search_path;
else {
do {
search_path=search_path.parent_path();
search_cmake_path=search_path;
search_cmake_path+="/CMakeLists.txt";
if(boost::filesystem::exists(search_cmake_path))
paths.emplace(paths.begin(), search_cmake_path);
if(find_cmake_project(search_cmake_path)) {
project_path=search_path;
break;
}
} while(search_path!=search_path.root_directory());
}
if(project_path!="") {
if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(project_path.string()+"/compile_commands.json"))
create_compile_commands(project_path);
}
}
bool CMake::create_compile_commands(const boost::filesystem::path &path) {
Singleton::terminal()->print("Creating "+path.string()+"/compile_commands.json\n");
if(Singleton::terminal()->execute(Singleton::Config::terminal()->cmake_command+" . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON", path)==EXIT_SUCCESS) {
#ifdef _WIN32 //Temporary fix to MSYS2's libclang
auto compile_commands_path=path;
compile_commands_path+="/compile_commands.json";
auto compile_commands_file=juci::filesystem::read(compile_commands_path);
size_t pos=0;
while((pos=compile_commands_file.find("-I/", pos))!=std::string::npos) {
if(pos+3<compile_commands_file.size()) {
std::string drive;
drive+=compile_commands_file[pos+3];
compile_commands_file.replace(pos, 4, "-I"+drive+":");
}
else
break;
}
juci::filesystem::write(compile_commands_path, compile_commands_file);
#endif
return true;
}
return false;
}
void CMake::read_files() {
for(auto &path: paths)
files.emplace_back(juci::filesystem::read(path));
}
void CMake::remove_tabs() {
for(auto &file: files) {
for(auto &chr: file) {
if(chr=='\t')
chr=' ';
}
}
}
void CMake::remove_comments() {
for(auto &file: files) {
size_t pos=0;
size_t comment_start;
bool inside_comment=false;
while(pos<file.size()) {
if(!inside_comment && file[pos]=='#') {
comment_start=pos;
inside_comment=true;
}
if(inside_comment && file[pos]=='\n') {
file.erase(comment_start, pos-comment_start);
pos-=pos-comment_start;
inside_comment=false;
}
pos++;
}
if(inside_comment)
file.erase(comment_start);
}
}
void CMake::remove_newlines_inside_parentheses() {
for(auto &file: files) {
size_t pos=0;
bool inside_para=false;
bool inside_quote=false;
char last_char=0;
while(pos<file.size()) {
if(!inside_quote && file[pos]=='"' && last_char!='\\')
inside_quote=true;
else if(inside_quote && file[pos]=='"' && last_char!='\\')
inside_quote=false;
else if(!inside_quote && file[pos]=='(')
inside_para=true;
else if(!inside_quote && file[pos]==')')
inside_para=false;
else if(inside_para && file[pos]=='\n')
file.replace(pos, 1, 1, ' ');
last_char=file[pos];
pos++;
}
}
}
void CMake::find_variables() {
for(auto &file: files) {
size_t pos=0;
while(pos<file.size()) {
auto start_line=pos;
auto end_line=file.find('\n', start_line);
if(end_line==std::string::npos)
end_line=file.size();
if(end_line>start_line) {
auto line=file.substr(start_line, end_line-start_line);
const std::regex set_regex("^ *set *\\( *([A-Za-z_][A-Za-z_0-9]*) +(.*)\\) *$");
std::smatch sm;
if(std::regex_match(line, sm, set_regex)) {
std::string data=sm[2];
while(data.size()>0 && data.back()==' ')
data.pop_back();
parse_variable_parameters(data);
variables[sm[1]]=data;
}
}
pos=end_line+1;
}
}
}
void CMake::parse_variable_parameters(std::string &data) {
size_t pos=0;
bool inside_quote=false;
char last_char=0;
while(pos<data.size()) {
if(!inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=true;
data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test}
pos--;
}
else if(inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=false;
data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test}
pos--;
}
else if(!inside_quote && data[pos]==' ' && pos+1<data.size() && data[pos+1]==' ') {
data.erase(pos, 1);
pos--;
}
last_char=data[pos];
pos++;
}
for(auto &var: variables) {
auto pos=data.find("${"+var.first+'}');
while(pos!=std::string::npos) {
data.replace(pos, var.first.size()+3, var.second);
pos=data.find("${"+var.first+'}');
}
}
//Remove variables we do not know:
pos=data.find("${");
auto pos_end=data.find("}", pos+2);
while(pos!=std::string::npos && pos_end!=std::string::npos) {
data.erase(pos, pos_end-pos+1);
pos=data.find("${");
pos_end=data.find("}", pos+2);
}
}
void CMake::parse() {
read_files();
remove_tabs();
remove_comments();
remove_newlines_inside_parentheses();
find_variables();
parsed=true;
}
std::vector<std::string> CMake::get_function_parameters(std::string &data) {
std::vector<std::string> parameters;
size_t pos=0;
size_t parameter_pos=0;
bool inside_quote=false;
char last_char=0;
while(pos<data.size()) {
if(!inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=true;
data.erase(pos, 1);
pos--;
}
else if(inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=false;
data.erase(pos, 1);
pos--;
}
else if(!inside_quote && pos+1<data.size() && data[pos]==' ' && data[pos+1]==' ') {
data.erase(pos, 1);
pos--;
}
else if(!inside_quote && data[pos]==' ') {
parameters.emplace_back(data.substr(parameter_pos, pos-parameter_pos));
if(pos+1<data.size())
parameter_pos=pos+1;
}
last_char=data[pos];
pos++;
}
parameters.emplace_back(data.substr(parameter_pos));
for(auto &var: variables) {
for(auto ¶meter: parameters) {
auto pos=parameter.find("${"+var.first+'}');
while(pos!=std::string::npos) {
parameter.replace(pos, var.first.size()+3, var.second);
pos=parameter.find("${"+var.first+'}');
}
}
}
return parameters;
}
std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > CMake::get_functions_parameters(const std::string &name) {
if(!parsed)
parse();
std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > functions;
size_t file_c=0;
for(auto &file: files) {
size_t pos=0;
while(pos<file.size()) {
auto start_line=pos;
auto end_line=file.find('\n', start_line);
if(end_line==std::string::npos)
end_line=file.size();
if(end_line>start_line) {
auto line=file.substr(start_line, end_line-start_line);
const std::regex function_regex("^ *"+name+" *\\( *(.*)\\) *$");
std::smatch sm;
if(std::regex_match(line, sm, function_regex)) {
std::string data=sm[1];
while(data.size()>0 && data.back()==' ')
data.pop_back();
auto parameters=get_function_parameters(data);
functions.emplace(functions.begin(), paths[file_c], parameters);
}
}
pos=end_line+1;
}
file_c++;
}
return functions;
}
<commit_msg>Minor fix to smatch use in cmake.cc<commit_after>#include "cmake.h"
#include "sourcefile.h"
#include <regex>
#include "singletons.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
CMake::CMake(const boost::filesystem::path &path) {
const auto find_cmake_project=[this](const boost::filesystem::path &cmake_path) {
for(auto &line: juci::filesystem::read_lines(cmake_path)) {
const std::regex project_regex("^ *project *\\(.*$");
std::smatch sm;
if(std::regex_match(line, sm, project_regex)) {
return true;
}
}
return false;
};
auto search_path=boost::filesystem::path(path);
auto search_cmake_path=search_path;
search_cmake_path+="/CMakeLists.txt";
if(boost::filesystem::exists(search_cmake_path))
paths.emplace(paths.begin(), search_cmake_path);
if(find_cmake_project(search_cmake_path))
project_path=search_path;
else {
do {
search_path=search_path.parent_path();
search_cmake_path=search_path;
search_cmake_path+="/CMakeLists.txt";
if(boost::filesystem::exists(search_cmake_path))
paths.emplace(paths.begin(), search_cmake_path);
if(find_cmake_project(search_cmake_path)) {
project_path=search_path;
break;
}
} while(search_path!=search_path.root_directory());
}
if(project_path!="") {
if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(project_path.string()+"/compile_commands.json"))
create_compile_commands(project_path);
}
}
bool CMake::create_compile_commands(const boost::filesystem::path &path) {
Singleton::terminal()->print("Creating "+path.string()+"/compile_commands.json\n");
if(Singleton::terminal()->execute(Singleton::Config::terminal()->cmake_command+" . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON", path)==EXIT_SUCCESS) {
#ifdef _WIN32 //Temporary fix to MSYS2's libclang
auto compile_commands_path=path;
compile_commands_path+="/compile_commands.json";
auto compile_commands_file=juci::filesystem::read(compile_commands_path);
size_t pos=0;
while((pos=compile_commands_file.find("-I/", pos))!=std::string::npos) {
if(pos+3<compile_commands_file.size()) {
std::string drive;
drive+=compile_commands_file[pos+3];
compile_commands_file.replace(pos, 4, "-I"+drive+":");
}
else
break;
}
juci::filesystem::write(compile_commands_path, compile_commands_file);
#endif
return true;
}
return false;
}
void CMake::read_files() {
for(auto &path: paths)
files.emplace_back(juci::filesystem::read(path));
}
void CMake::remove_tabs() {
for(auto &file: files) {
for(auto &chr: file) {
if(chr=='\t')
chr=' ';
}
}
}
void CMake::remove_comments() {
for(auto &file: files) {
size_t pos=0;
size_t comment_start;
bool inside_comment=false;
while(pos<file.size()) {
if(!inside_comment && file[pos]=='#') {
comment_start=pos;
inside_comment=true;
}
if(inside_comment && file[pos]=='\n') {
file.erase(comment_start, pos-comment_start);
pos-=pos-comment_start;
inside_comment=false;
}
pos++;
}
if(inside_comment)
file.erase(comment_start);
}
}
void CMake::remove_newlines_inside_parentheses() {
for(auto &file: files) {
size_t pos=0;
bool inside_para=false;
bool inside_quote=false;
char last_char=0;
while(pos<file.size()) {
if(!inside_quote && file[pos]=='"' && last_char!='\\')
inside_quote=true;
else if(inside_quote && file[pos]=='"' && last_char!='\\')
inside_quote=false;
else if(!inside_quote && file[pos]=='(')
inside_para=true;
else if(!inside_quote && file[pos]==')')
inside_para=false;
else if(inside_para && file[pos]=='\n')
file.replace(pos, 1, 1, ' ');
last_char=file[pos];
pos++;
}
}
}
void CMake::find_variables() {
for(auto &file: files) {
size_t pos=0;
while(pos<file.size()) {
auto start_line=pos;
auto end_line=file.find('\n', start_line);
if(end_line==std::string::npos)
end_line=file.size();
if(end_line>start_line) {
auto line=file.substr(start_line, end_line-start_line);
const std::regex set_regex("^ *set *\\( *([A-Za-z_][A-Za-z_0-9]*) +(.*)\\) *$");
std::smatch sm;
if(std::regex_match(line, sm, set_regex)) {
auto data=sm[2].str();
while(data.size()>0 && data.back()==' ')
data.pop_back();
parse_variable_parameters(data);
variables[sm[1].str()]=data;
}
}
pos=end_line+1;
}
}
}
void CMake::parse_variable_parameters(std::string &data) {
size_t pos=0;
bool inside_quote=false;
char last_char=0;
while(pos<data.size()) {
if(!inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=true;
data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test}
pos--;
}
else if(inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=false;
data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test}
pos--;
}
else if(!inside_quote && data[pos]==' ' && pos+1<data.size() && data[pos+1]==' ') {
data.erase(pos, 1);
pos--;
}
last_char=data[pos];
pos++;
}
for(auto &var: variables) {
auto pos=data.find("${"+var.first+'}');
while(pos!=std::string::npos) {
data.replace(pos, var.first.size()+3, var.second);
pos=data.find("${"+var.first+'}');
}
}
//Remove variables we do not know:
pos=data.find("${");
auto pos_end=data.find("}", pos+2);
while(pos!=std::string::npos && pos_end!=std::string::npos) {
data.erase(pos, pos_end-pos+1);
pos=data.find("${");
pos_end=data.find("}", pos+2);
}
}
void CMake::parse() {
read_files();
remove_tabs();
remove_comments();
remove_newlines_inside_parentheses();
find_variables();
parsed=true;
}
std::vector<std::string> CMake::get_function_parameters(std::string &data) {
std::vector<std::string> parameters;
size_t pos=0;
size_t parameter_pos=0;
bool inside_quote=false;
char last_char=0;
while(pos<data.size()) {
if(!inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=true;
data.erase(pos, 1);
pos--;
}
else if(inside_quote && data[pos]=='"' && last_char!='\\') {
inside_quote=false;
data.erase(pos, 1);
pos--;
}
else if(!inside_quote && pos+1<data.size() && data[pos]==' ' && data[pos+1]==' ') {
data.erase(pos, 1);
pos--;
}
else if(!inside_quote && data[pos]==' ') {
parameters.emplace_back(data.substr(parameter_pos, pos-parameter_pos));
if(pos+1<data.size())
parameter_pos=pos+1;
}
last_char=data[pos];
pos++;
}
parameters.emplace_back(data.substr(parameter_pos));
for(auto &var: variables) {
for(auto ¶meter: parameters) {
auto pos=parameter.find("${"+var.first+'}');
while(pos!=std::string::npos) {
parameter.replace(pos, var.first.size()+3, var.second);
pos=parameter.find("${"+var.first+'}');
}
}
}
return parameters;
}
std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > CMake::get_functions_parameters(const std::string &name) {
if(!parsed)
parse();
std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > functions;
size_t file_c=0;
for(auto &file: files) {
size_t pos=0;
while(pos<file.size()) {
auto start_line=pos;
auto end_line=file.find('\n', start_line);
if(end_line==std::string::npos)
end_line=file.size();
if(end_line>start_line) {
auto line=file.substr(start_line, end_line-start_line);
const std::regex function_regex("^ *"+name+" *\\( *(.*)\\) *$");
std::smatch sm;
if(std::regex_match(line, sm, function_regex)) {
auto data=sm[1].str();
while(data.size()>0 && data.back()==' ')
data.pop_back();
auto parameters=get_function_parameters(data);
functions.emplace(functions.begin(), paths[file_c], parameters);
}
}
pos=end_line+1;
}
file_c++;
}
return functions;
}
<|endoftext|> |
<commit_before>//
// scan.cpp
// See the file "LICENSE.md" for the full license governing this code.
//
#include "compile.h"
#if COMPILE_DMZ
#include "scan.h"
#include "expiry_categorize.h"
#include "expiry_seg.h"
#define SCAN_FOREVER 0 // useful for performance profiling
#define EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS 1000 // once the card number has been successfully identified, allow a bit more time to figure out the expiry
#define kDecayFactor 0.8f
#define kMinStability 0.7f
void scanner_initialize(ScannerState *state) {
scanner_reset(state);
}
void scanner_reset(ScannerState *state) {
state->count15 = 0;
state->count16 = 0;
state->aggregated15 = NumberScores::Zero();
state->aggregated16 = NumberScores::Zero();
scan_analytics_init(&state->session_analytics);
state->timeOfCardNumberCompletionInMilliseconds = 0;
state->scan_expiry = false;
state->expiry_month = 0;
state->expiry_year = 0;
state->expiry_groups.clear();
state->name_groups.clear();
}
void scanner_add_frame(ScannerState *state, IplImage *y, FrameScanResult *result) {
scanner_add_frame_with_expiry(state, y, false, result);
}
void scanner_add_frame_with_expiry(ScannerState *state, IplImage *y, bool scan_expiry, FrameScanResult *result) {
bool still_need_to_collect_card_number = (state->timeOfCardNumberCompletionInMilliseconds == 0);
bool still_need_to_scan_expiry = scan_expiry && (state->expiry_month == 0 || state->expiry_year == 0);
// Don't bother with a bunch of assertions about y here,
// since the frame reader will make them anyway.
scan_card_image(y, still_need_to_collect_card_number, still_need_to_scan_expiry, result);
if (result->upside_down) {
return;
}
scan_analytics_record_frame(&state->session_analytics, result);
// TODO: Scene change detection?
if (!result->usable) {
return;
}
#if SCAN_EXPIRY
if (still_need_to_scan_expiry) {
state->scan_expiry = true;
expiry_extract(y, state->expiry_groups, result->expiry_groups, &state->expiry_month, &state->expiry_year);
state->name_groups = result->name_groups; // for now, for the debugging display
}
#endif
if (still_need_to_collect_card_number) {
state->mostRecentUsableHSeg = result->hseg;
state->mostRecentUsableVSeg = result->vseg;
if(result->hseg.n_offsets == 15) {
state->aggregated15 *= kDecayFactor;
state->aggregated15 += result->scores * (1 - kDecayFactor);
state->count15++;
} else if(result->hseg.n_offsets == 16) {
state->aggregated16 *= kDecayFactor;
state->aggregated16 += result->scores * (1 - kDecayFactor);
state->count16++;
} else {
assert(false);
}
}
}
void scanner_result(ScannerState *state, ScannerResult *result) {
result->complete = false; // until we change our minds otherwise...avoids having to set this at all the possible early exits
#if SCAN_FOREVER
return;
#endif
if (state->timeOfCardNumberCompletionInMilliseconds > 0) {
*result = state->successfulCardNumberResult;
}
else {
uint16_t max_count = MAX(state->count15, state->count16);
uint16_t min_count = MIN(state->count15, state->count16);
// We want a three frame lead at a bare minimum.
// Also guarantees we have at least three frames, period. :)
if(max_count - min_count < 3) {
return;
}
// Want a significant opinion about whether visa or amex
if(min_count * 2 > max_count) {
return;
}
result->hseg = state->mostRecentUsableHSeg;
result->vseg = state->mostRecentUsableVSeg;
// TODO: Sanity check the scores distributions
// TODO: Do something else sophisticated here -- look at confidences, distributions, stability, hysteresis, etc.
NumberScores aggregated;
if(state->count15 > state->count16) {
result->n_numbers = 15;
aggregated = state->aggregated15;
} else {
result->n_numbers = 16;
aggregated = state->aggregated16;
}
// Calculate result predictions
// At the same time, put it in a convenient format for the basic consistency checks
uint8_t number_as_u8s[16];
dmz_debug_print("Stability: ");
for(uint8_t i = 0; i < result->n_numbers; i++) {
NumberScores::Index r, c;
float max_score = aggregated.row(i).maxCoeff(&r, &c);
float sum = aggregated.row(i).sum();
result->predictions(i, 0) = c;
number_as_u8s[i] = (uint8_t)c;
float stability = max_score / sum;
dmz_debug_print("%d ", (int) ceilf(stability * 100));
// Bail early if low stability
if (stability < kMinStability) {
dmz_debug_print("\n");
return;
}
}
dmz_debug_print("\n");
// Don't return a number that fails basic prefix sanity checks
CardType card_type = dmz_card_info_for_prefix_and_length(number_as_u8s, result->n_numbers, false).card_type;
if(card_type != CardTypeAmbiguous &&
card_type != CardTypeUnrecognized &&
dmz_passes_luhn_checksum(number_as_u8s, result->n_numbers)) {
dmz_debug_print("CARD NUMBER SCANNED SUCCESSFULLY.\n");
struct timeval time;
gettimeofday(&time, NULL);
state->timeOfCardNumberCompletionInMilliseconds = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000));
state->successfulCardNumberResult = *result;
}
}
// Once the card number has been successfully scanned, then wait a bit longer for successful expiry scan (if collecting expiry)
if (state->timeOfCardNumberCompletionInMilliseconds > 0) {
#if SCAN_EXPIRY
if (state->scan_expiry) {
#else
if (false) {
#endif
struct timeval time;
gettimeofday(&time, NULL);
long now = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000));
if ((state->expiry_month > 0 && state->expiry_year > 0) ||
now - state->timeOfCardNumberCompletionInMilliseconds > EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS) {
result->expiry_month = state->expiry_month;
result->expiry_year = state->expiry_year;
#if DMZ_DEBUG
result->expiry_groups = state->expiry_groups;
result->name_groups = state->name_groups;
#endif
result->complete = true;
dmz_debug_print("Extra time for expiry scan: %6.3f seconds\n", ((float)(now - state->timeOfCardNumberCompletionInMilliseconds)) / 1000.0f);
}
}
else {
result->expiry_month = 0;
result->expiry_year = 0;
result->complete = true;
}
}
}
void scanner_destroy(ScannerState *state) {
// currently a no-op
}
#endif // COMPILE_DMZ
<commit_msg>Disable stability and luhn check for now<commit_after>//
// scan.cpp
// See the file "LICENSE.md" for the full license governing this code.
//
#include "compile.h"
#if COMPILE_DMZ
#include "scan.h"
#include "expiry_categorize.h"
#include "expiry_seg.h"
#define SCAN_FOREVER 0 // useful for performance profiling
#define EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS 1000 // once the card number has been successfully identified, allow a bit more time to figure out the expiry
#define kDecayFactor 0.8f
#define kMinStability 0.7f
void scanner_initialize(ScannerState *state) {
scanner_reset(state);
}
void scanner_reset(ScannerState *state) {
state->count15 = 0;
state->count16 = 0;
state->aggregated15 = NumberScores::Zero();
state->aggregated16 = NumberScores::Zero();
scan_analytics_init(&state->session_analytics);
state->timeOfCardNumberCompletionInMilliseconds = 0;
state->scan_expiry = false;
state->expiry_month = 0;
state->expiry_year = 0;
state->expiry_groups.clear();
state->name_groups.clear();
}
void scanner_add_frame(ScannerState *state, IplImage *y, FrameScanResult *result) {
scanner_add_frame_with_expiry(state, y, false, result);
}
void scanner_add_frame_with_expiry(ScannerState *state, IplImage *y, bool scan_expiry, FrameScanResult *result) {
bool still_need_to_collect_card_number = (state->timeOfCardNumberCompletionInMilliseconds == 0);
bool still_need_to_scan_expiry = scan_expiry && (state->expiry_month == 0 || state->expiry_year == 0);
// Don't bother with a bunch of assertions about y here,
// since the frame reader will make them anyway.
scan_card_image(y, still_need_to_collect_card_number, still_need_to_scan_expiry, result);
if (result->upside_down) {
return;
}
scan_analytics_record_frame(&state->session_analytics, result);
// TODO: Scene change detection?
if (!result->usable) {
return;
}
#if SCAN_EXPIRY
if (still_need_to_scan_expiry) {
state->scan_expiry = true;
expiry_extract(y, state->expiry_groups, result->expiry_groups, &state->expiry_month, &state->expiry_year);
state->name_groups = result->name_groups; // for now, for the debugging display
}
#endif
if (still_need_to_collect_card_number) {
state->mostRecentUsableHSeg = result->hseg;
state->mostRecentUsableVSeg = result->vseg;
if(result->hseg.n_offsets == 15) {
state->aggregated15 *= kDecayFactor;
state->aggregated15 += result->scores * (1 - kDecayFactor);
state->count15++;
} else if(result->hseg.n_offsets == 16) {
state->aggregated16 *= kDecayFactor;
state->aggregated16 += result->scores * (1 - kDecayFactor);
state->count16++;
} else {
assert(false);
}
}
}
void scanner_result(ScannerState *state, ScannerResult *result) {
result->complete = false; // until we change our minds otherwise...avoids having to set this at all the possible early exits
#if SCAN_FOREVER
return;
#endif
if (state->timeOfCardNumberCompletionInMilliseconds > 0) {
*result = state->successfulCardNumberResult;
}
else {
uint16_t max_count = MAX(state->count15, state->count16);
uint16_t min_count = MIN(state->count15, state->count16);
// We want a three frame lead at a bare minimum.
// Also guarantees we have at least three frames, period. :)
if(max_count - min_count < 3) {
return;
}
// Want a significant opinion about whether visa or amex
if(min_count * 2 > max_count) {
return;
}
result->hseg = state->mostRecentUsableHSeg;
result->vseg = state->mostRecentUsableVSeg;
// TODO: Sanity check the scores distributions
// TODO: Do something else sophisticated here -- look at confidences, distributions, stability, hysteresis, etc.
NumberScores aggregated;
if(state->count15 > state->count16) {
result->n_numbers = 15;
aggregated = state->aggregated15;
} else {
result->n_numbers = 16;
aggregated = state->aggregated16;
}
// Calculate result predictions
// At the same time, put it in a convenient format for the basic consistency checks
uint8_t number_as_u8s[16];
dmz_debug_print("Stability: ");
for(uint8_t i = 0; i < result->n_numbers; i++) {
NumberScores::Index r, c;
float max_score = aggregated.row(i).maxCoeff(&r, &c);
float sum = aggregated.row(i).sum();
result->predictions(i, 0) = c;
number_as_u8s[i] = (uint8_t)c;
float stability = max_score / sum;
dmz_debug_print("%d ", (int) ceilf(stability * 100));
// Bail early if low stability
// if (stability < kMinStability) {
// dmz_debug_print("\n");
// return;
// }
}
dmz_debug_print("\n");
// Don't return a number that fails basic prefix sanity checks
CardType card_type = dmz_card_info_for_prefix_and_length(number_as_u8s, result->n_numbers, false).card_type;
// if(card_type != CardTypeAmbiguous &&
// card_type != CardTypeUnrecognized &&
// dmz_passes_luhn_checksum(number_as_u8s, result->n_numbers)) {
if (true) {
dmz_debug_print("CARD NUMBER SCANNED SUCCESSFULLY.\n");
struct timeval time;
gettimeofday(&time, NULL);
state->timeOfCardNumberCompletionInMilliseconds = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000));
state->successfulCardNumberResult = *result;
}
}
// Once the card number has been successfully scanned, then wait a bit longer for successful expiry scan (if collecting expiry)
if (state->timeOfCardNumberCompletionInMilliseconds > 0) {
#if SCAN_EXPIRY
if (state->scan_expiry) {
#else
if (false) {
#endif
struct timeval time;
gettimeofday(&time, NULL);
long now = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000));
if ((state->expiry_month > 0 && state->expiry_year > 0) ||
now - state->timeOfCardNumberCompletionInMilliseconds > EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS) {
result->expiry_month = state->expiry_month;
result->expiry_year = state->expiry_year;
#if DMZ_DEBUG
result->expiry_groups = state->expiry_groups;
result->name_groups = state->name_groups;
#endif
result->complete = true;
dmz_debug_print("Extra time for expiry scan: %6.3f seconds\n", ((float)(now - state->timeOfCardNumberCompletionInMilliseconds)) / 1000.0f);
}
}
else {
result->expiry_month = 0;
result->expiry_year = 0;
result->complete = true;
}
}
}
void scanner_destroy(ScannerState *state) {
// currently a no-op
}
#endif // COMPILE_DMZ
<|endoftext|> |
<commit_before>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Flags.hpp>
#include <utility>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Flags
* \brief Core class used to combine enumeration values into flags bitfield
*/
/*!
* \brief Constructs a Flags object using a bitfield
*
* \param value Bitfield to be used
*
* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).
*/
template<typename E>
constexpr Flags<E>::Flags(BitField value) :
m_value(value)
{
}
/*!
* \brief Constructs a Flags object using an Enum value
*
* \param enumVal enumVal
*
* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).
*/
template<typename E>
constexpr Flags<E>::Flags(E enumVal) :
Flags(GetFlagValue(enumVal))
{
}
/*!
* \brief Clear all flags
*
* \see Test
*/
template<typename E>
void Flags<E>::Clear()
{
m_value = 0;
}
/*!
* \brief Clear some flags
*
* \param flags Flags to be cleared
*
* \see Test
*/
template<typename E>
void Flags<E>::Clear(const Flags& flags)
{
m_value &= ~flags.m_value;
}
/*!
* \brief Enable some flags
*
* \param flags Flags to be enabled
*
* \see Clear
* \see Test
*/
template<typename E>
void Flags<E>::Set(const Flags& flags)
{
m_value |= flags.m_value;
}
/*!
* \brief Tests if all flags from a Flags object are enabled
* \return True if all tested flags are enabled.
*
* \see Clear
*/
template<typename E>
constexpr bool Flags<E>::Test(const Flags& flags) const
{
return (m_value & flags.m_value) == flags.m_value;
}
/*!
* \brief Tests any flag
* \return True if any flag is enabled.
*
* This will convert to a boolean value allowing to check if any flag is set.
*/
template<typename E>
constexpr Flags<E>::operator bool() const
{
return m_value != 0;
}
/*!
* \brief Converts to an integer
* \return Enabled flags as a integer
*
* This will only works if the integer type is large enough to store all flags states
*/
template<typename E>
template<typename T, typename>
constexpr Flags<E>::operator T() const
{
return m_value;
}
/*!
* \brief Reverse flag states
* \return Opposite enabled flags
*
* This will returns a copy of the Flags object with reversed flags states.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator~() const
{
return Flags((~m_value) & ValueMask);
}
/*!
* \brief Compare flag states
* \return Shared flags
*
* \param rhs Flags to compare with.
*
* This will returns a copy of the Flags object with only enabled flags in common with the parameter
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const
{
return Flags(m_value & rhs.m_value);
}
/*!
* \brief Combine flag states
* \return Combined flags
*
* This will returns a copy of the Flags object with combined flags from the parameter.
*
* \param rhs Flags to combine with.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const
{
return Flags(m_value | rhs.m_value);
}
/*!
* \brief XOR flag states
* \return XORed flags.
*
* \param rhs Flags to XOR with.
*
* This performs a XOR (Exclusive OR) on a copy of the flag object.
* This will returns a copy of the object with disabled common flags and enabled unique ones.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const
{
return Flags((m_value ^ rhs.m_value) & ValueMask);
}
/*!
* \brief Check equality with flag object
* \return True if both flags objects have the same states.
*
* \param rhs Flags to compare with.
*
* Compare two Flags object and returns true if the flag states are identical.
*/
template<typename E>
constexpr bool Flags<E>::operator==(const Flags& rhs) const
{
return m_value == rhs.m_value;
}
/*!
* \brief Check inequality with flag object
* \return True if both flags objects have different states.
*
* \param rhs Flags to compare with.
*
* Compare two Flags object and returns true if the flag states are identical.
*/
template<typename E>
constexpr bool Flags<E>::operator!=(const Flags& rhs) const
{
return !operator==(rhs);
}
/*!
* \brief Combine flag states
* \return A reference to the object.
*
* \param rhs Flags to combine with.
*
* This will enable flags which are enabled in parameter object and not in Flag object.
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)
{
m_value |= rhs.m_value;
return *this;
}
/*!
* \brief Compare flag states
* \return A reference to the object.
*
* \param rhs Flags to compare with.
*
* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)
{
m_value &= rhs.m_value;
return *this;
}
/*!
* \brief XOR flag states
* \return A reference to the object.
*
* \param rhs Flags to XOR with.
*
* This performs a XOR (Exclusive OR) on the flag object.
* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)
{
m_value ^= rhs.m_value;
m_value &= ValueMask;
return *this;
}
/*!
* \brief Returns a bitfield corresponding to an enum value.
* \return Bitfield representation of the enum value
*
* \param enumValue Enumeration value to get as a bitfield.
*
* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.
*/
template<typename E>
constexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)
{
if constexpr (AutoFlag)
return 1U << static_cast<BitField>(enumValue);
else
return enumValue;
}
/*!
* \brief Compare flag states
* \return Compared flags
*
* This will returns a copy of the Flags object compared with the enum state.
*
* \param lhs Enum to compare with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator&(E lhs, Flags<E> rhs)
{
return rhs & lhs;
}
/*!
* \brief Combine flag states
* \return Combined flags
*
* This will returns a copy of the Flags object combined with the enum state.
*
* \param lhs Enum to combine with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator|(E lhs, Flags<E> rhs)
{
return rhs | lhs;
}
/*!
* \brief XOR flag states
* \return XORed flags
*
* This will returns a copy of the Flags object XORed with the enum state.
*
* \param lhs Enum to XOR with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator^(E lhs, Flags<E> rhs)
{
return rhs ^ lhs;
}
namespace FlagsOperators
{
/*!
* \brief Override binary NOT operator on enum to turns into a Flags object.
* \return A Flags object with reversed bits.
*
* \param lhs Enumeration value to reverse.
*
* Returns a Flags object with all state enabled except for the enum one.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)
{
return ~Flags<E>(lhs);
}
/*!
* \brief Override binary AND operator on enum to turns into a Flags object.
* \return A Flags object with compare enum states.
*
* \param lhs First enumeration value to compare.
* \param rhs Second enumeration value to compare.
*
* Returns a Flags object with compared states from the two enumeration values.
* In this case, only one flag will be enabled if both enumeration values are the same.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)
{
return Flags<E>(lhs) & rhs;
}
/*!
* \brief Override binary OR operator on enum to turns into a Flags object.
* \return A Flags object with combined enum states.
*
* \param lhs First enumeration value to combine.
* \param rhs Second enumeration value to combine.
*
* Returns a Flags object with combined states from the two enumeration values.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)
{
return Flags<E>(lhs) | rhs;
}
/*!
* \brief Override binary XOR operator on enum to turns into a Flags object.
* \return A Flags object with XORed enum states.
*
* \param lhs First enumeration value to compare.
* \param rhs Second enumeration value to compare.
*
* Returns a Flags object with XORed states from the two enumeration values.
* In this case, two flags will be enabled if both the enumeration values are different.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)
{
return Flags<E>(lhs) ^ rhs;
}
}
}
namespace std
{
template<typename E>
struct hash<Nz::Flags<E>>
{
std::size_t operator()(const Nz::Flags<E>& flags)
{
using UnderlyingType = typename Nz::Flags<E>::BitField;
using Hasher = hash<UnderlyingType>;
Hasher hasher;
return hasher(static_cast<UnderlyingType>(flags));
}
};
}
#include <Nazara/Core/DebugOff.hpp>
<commit_msg>Core/Flags: Fix std::hash include<commit_after>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Flags.hpp>
#include <functional>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Flags
* \brief Core class used to combine enumeration values into flags bitfield
*/
/*!
* \brief Constructs a Flags object using a bitfield
*
* \param value Bitfield to be used
*
* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).
*/
template<typename E>
constexpr Flags<E>::Flags(BitField value) :
m_value(value)
{
}
/*!
* \brief Constructs a Flags object using an Enum value
*
* \param enumVal enumVal
*
* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).
*/
template<typename E>
constexpr Flags<E>::Flags(E enumVal) :
Flags(GetFlagValue(enumVal))
{
}
/*!
* \brief Clear all flags
*
* \see Test
*/
template<typename E>
void Flags<E>::Clear()
{
m_value = 0;
}
/*!
* \brief Clear some flags
*
* \param flags Flags to be cleared
*
* \see Test
*/
template<typename E>
void Flags<E>::Clear(const Flags& flags)
{
m_value &= ~flags.m_value;
}
/*!
* \brief Enable some flags
*
* \param flags Flags to be enabled
*
* \see Clear
* \see Test
*/
template<typename E>
void Flags<E>::Set(const Flags& flags)
{
m_value |= flags.m_value;
}
/*!
* \brief Tests if all flags from a Flags object are enabled
* \return True if all tested flags are enabled.
*
* \see Clear
*/
template<typename E>
constexpr bool Flags<E>::Test(const Flags& flags) const
{
return (m_value & flags.m_value) == flags.m_value;
}
/*!
* \brief Tests any flag
* \return True if any flag is enabled.
*
* This will convert to a boolean value allowing to check if any flag is set.
*/
template<typename E>
constexpr Flags<E>::operator bool() const
{
return m_value != 0;
}
/*!
* \brief Converts to an integer
* \return Enabled flags as a integer
*
* This will only works if the integer type is large enough to store all flags states
*/
template<typename E>
template<typename T, typename>
constexpr Flags<E>::operator T() const
{
return m_value;
}
/*!
* \brief Reverse flag states
* \return Opposite enabled flags
*
* This will returns a copy of the Flags object with reversed flags states.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator~() const
{
return Flags((~m_value) & ValueMask);
}
/*!
* \brief Compare flag states
* \return Shared flags
*
* \param rhs Flags to compare with.
*
* This will returns a copy of the Flags object with only enabled flags in common with the parameter
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const
{
return Flags(m_value & rhs.m_value);
}
/*!
* \brief Combine flag states
* \return Combined flags
*
* This will returns a copy of the Flags object with combined flags from the parameter.
*
* \param rhs Flags to combine with.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const
{
return Flags(m_value | rhs.m_value);
}
/*!
* \brief XOR flag states
* \return XORed flags.
*
* \param rhs Flags to XOR with.
*
* This performs a XOR (Exclusive OR) on a copy of the flag object.
* This will returns a copy of the object with disabled common flags and enabled unique ones.
*/
template<typename E>
constexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const
{
return Flags((m_value ^ rhs.m_value) & ValueMask);
}
/*!
* \brief Check equality with flag object
* \return True if both flags objects have the same states.
*
* \param rhs Flags to compare with.
*
* Compare two Flags object and returns true if the flag states are identical.
*/
template<typename E>
constexpr bool Flags<E>::operator==(const Flags& rhs) const
{
return m_value == rhs.m_value;
}
/*!
* \brief Check inequality with flag object
* \return True if both flags objects have different states.
*
* \param rhs Flags to compare with.
*
* Compare two Flags object and returns true if the flag states are identical.
*/
template<typename E>
constexpr bool Flags<E>::operator!=(const Flags& rhs) const
{
return !operator==(rhs);
}
/*!
* \brief Combine flag states
* \return A reference to the object.
*
* \param rhs Flags to combine with.
*
* This will enable flags which are enabled in parameter object and not in Flag object.
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)
{
m_value |= rhs.m_value;
return *this;
}
/*!
* \brief Compare flag states
* \return A reference to the object.
*
* \param rhs Flags to compare with.
*
* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)
{
m_value &= rhs.m_value;
return *this;
}
/*!
* \brief XOR flag states
* \return A reference to the object.
*
* \param rhs Flags to XOR with.
*
* This performs a XOR (Exclusive OR) on the flag object.
* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.
*/
template<typename E>
/*constexpr*/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)
{
m_value ^= rhs.m_value;
m_value &= ValueMask;
return *this;
}
/*!
* \brief Returns a bitfield corresponding to an enum value.
* \return Bitfield representation of the enum value
*
* \param enumValue Enumeration value to get as a bitfield.
*
* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.
*/
template<typename E>
constexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)
{
if constexpr (AutoFlag)
return 1U << static_cast<BitField>(enumValue);
else
return enumValue;
}
/*!
* \brief Compare flag states
* \return Compared flags
*
* This will returns a copy of the Flags object compared with the enum state.
*
* \param lhs Enum to compare with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator&(E lhs, Flags<E> rhs)
{
return rhs & lhs;
}
/*!
* \brief Combine flag states
* \return Combined flags
*
* This will returns a copy of the Flags object combined with the enum state.
*
* \param lhs Enum to combine with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator|(E lhs, Flags<E> rhs)
{
return rhs | lhs;
}
/*!
* \brief XOR flag states
* \return XORed flags
*
* This will returns a copy of the Flags object XORed with the enum state.
*
* \param lhs Enum to XOR with flags.
* \param rhs Flags object.
*/
template<typename E>
constexpr Flags<E> operator^(E lhs, Flags<E> rhs)
{
return rhs ^ lhs;
}
namespace FlagsOperators
{
/*!
* \brief Override binary NOT operator on enum to turns into a Flags object.
* \return A Flags object with reversed bits.
*
* \param lhs Enumeration value to reverse.
*
* Returns a Flags object with all state enabled except for the enum one.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)
{
return ~Flags<E>(lhs);
}
/*!
* \brief Override binary AND operator on enum to turns into a Flags object.
* \return A Flags object with compare enum states.
*
* \param lhs First enumeration value to compare.
* \param rhs Second enumeration value to compare.
*
* Returns a Flags object with compared states from the two enumeration values.
* In this case, only one flag will be enabled if both enumeration values are the same.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)
{
return Flags<E>(lhs) & rhs;
}
/*!
* \brief Override binary OR operator on enum to turns into a Flags object.
* \return A Flags object with combined enum states.
*
* \param lhs First enumeration value to combine.
* \param rhs Second enumeration value to combine.
*
* Returns a Flags object with combined states from the two enumeration values.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)
{
return Flags<E>(lhs) | rhs;
}
/*!
* \brief Override binary XOR operator on enum to turns into a Flags object.
* \return A Flags object with XORed enum states.
*
* \param lhs First enumeration value to compare.
* \param rhs Second enumeration value to compare.
*
* Returns a Flags object with XORed states from the two enumeration values.
* In this case, two flags will be enabled if both the enumeration values are different.
*/
template<typename E>
constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)
{
return Flags<E>(lhs) ^ rhs;
}
}
}
namespace std
{
template<typename E>
struct hash<Nz::Flags<E>>
{
std::size_t operator()(const Nz::Flags<E>& flags)
{
using UnderlyingType = typename Nz::Flags<E>::BitField;
using Hasher = hash<UnderlyingType>;
Hasher hasher;
return hasher(static_cast<UnderlyingType>(flags));
}
};
}
#include <Nazara/Core/DebugOff.hpp>
<|endoftext|> |
<commit_before>//
// Copyright 2012 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.
//
#include "api/util.hpp"
#include "core/program.hpp"
#include <sstream>
using namespace clover;
namespace {
void validate_build_program_common(const program &prog, cl_uint num_devs,
const cl_device_id *d_devs,
void (*pfn_notify)(cl_program, void *),
void *user_data) {
if ((!pfn_notify && user_data))
throw error(CL_INVALID_VALUE);
if (prog.kernel_ref_count())
throw error(CL_INVALID_OPERATION);
if (any_of([&](const device &dev) {
return !count(dev, prog.context().devices());
}, objs<allow_empty_tag>(d_devs, num_devs)))
throw error(CL_INVALID_DEVICE);
}
}
CLOVER_API cl_program
clCreateProgramWithSource(cl_context d_ctx, cl_uint count,
const char **strings, const size_t *lengths,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
std::string source;
if (!count || !strings ||
any_of(is_zero(), range(strings, count)))
throw error(CL_INVALID_VALUE);
// Concatenate all the provided fragments together
for (unsigned i = 0; i < count; ++i)
source += (lengths && lengths[i] ?
std::string(strings[i], strings[i] + lengths[i]) :
std::string(strings[i]));
// ...and create a program object for them.
ret_error(r_errcode, CL_SUCCESS);
return new program(ctx, source);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_program
clCreateProgramWithBinary(cl_context d_ctx, cl_uint n,
const cl_device_id *d_devs,
const size_t *lengths,
const unsigned char **binaries,
cl_int *r_status, cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto devs = objs(d_devs, n);
if (!lengths || !binaries)
throw error(CL_INVALID_VALUE);
if (any_of([&](const device &dev) {
return !count(dev, ctx.devices());
}, devs))
throw error(CL_INVALID_DEVICE);
// Deserialize the provided binaries,
std::vector<std::pair<cl_int, module>> result = map(
[](const unsigned char *p, size_t l) -> std::pair<cl_int, module> {
if (!p || !l)
return { CL_INVALID_VALUE, {} };
try {
std::stringbuf bin( { (char*)p, l } );
std::istream s(&bin);
return { CL_SUCCESS, module::deserialize(s) };
} catch (std::istream::failure &e) {
return { CL_INVALID_BINARY, {} };
}
},
range(binaries, n),
range(lengths, n));
// update the status array,
if (r_status)
copy(map(keys(), result), r_status);
if (any_of(key_equals(CL_INVALID_VALUE), result))
throw error(CL_INVALID_VALUE);
if (any_of(key_equals(CL_INVALID_BINARY), result))
throw error(CL_INVALID_BINARY);
// initialize a program object with them.
ret_error(r_errcode, CL_SUCCESS);
return new program(ctx, devs, map(values(), result));
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_program
clCreateProgramWithBuiltInKernels(cl_context d_ctx, cl_uint n,
const cl_device_id *d_devs,
const char *kernel_names,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto devs = objs(d_devs, n);
if (any_of([&](const device &dev) {
return !count(dev, ctx.devices());
}, devs))
throw error(CL_INVALID_DEVICE);
// No currently supported built-in kernels.
throw error(CL_INVALID_VALUE);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_int
clRetainProgram(cl_program d_prog) try {
obj(d_prog).retain();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clReleaseProgram(cl_program d_prog) try {
if (obj(d_prog).release())
delete pobj(d_prog);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clBuildProgram(cl_program d_prog, cl_uint num_devs,
const cl_device_id *d_devs, const char *p_opts,
void (*pfn_notify)(cl_program, void *),
void *user_data) try {
auto &prog = obj(d_prog);
auto devs = (d_devs ? objs(d_devs, num_devs) :
ref_vector<device>(prog.context().devices()));
auto opts = (p_opts ? p_opts : "");
validate_build_program_common(prog, num_devs, d_devs, pfn_notify, user_data);
if (prog.has_source) {
prog.compile(devs, opts);
prog.link(devs, opts, { prog });
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clCompileProgram(cl_program d_prog, cl_uint num_devs,
const cl_device_id *d_devs, const char *p_opts,
cl_uint num_headers, const cl_program *d_header_progs,
const char **header_names,
void (*pfn_notify)(cl_program, void *),
void *user_data) try {
auto &prog = obj(d_prog);
auto devs = (d_devs ? objs(d_devs, num_devs) :
ref_vector<device>(prog.context().devices()));
auto opts = (p_opts ? p_opts : "");
header_map headers;
validate_build_program_common(prog, num_devs, d_devs, pfn_notify, user_data);
if (bool(num_headers) != bool(header_names))
throw error(CL_INVALID_VALUE);
if (!prog.has_source)
throw error(CL_INVALID_OPERATION);
for_each([&](const char *name, const program &header) {
if (!header.has_source)
throw error(CL_INVALID_OPERATION);
if (!any_of(key_equals(name), headers))
headers.push_back(std::pair<std::string, std::string>(
name, header.source()));
},
range(header_names, num_headers),
objs<allow_empty_tag>(d_header_progs, num_headers));
prog.compile(devs, opts, headers);
return CL_SUCCESS;
} catch (invalid_build_options_error &e) {
return CL_INVALID_COMPILER_OPTIONS;
} catch (build_error &e) {
return CL_COMPILE_PROGRAM_FAILURE;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_program
clLinkProgram(cl_context d_ctx, cl_uint num_devs, const cl_device_id *d_devs,
const char *p_opts, cl_uint num_progs, const cl_program *d_progs,
void (*pfn_notify)(cl_program, void *), void *user_data,
cl_int *r_errcode) {
CLOVER_NOT_SUPPORTED_UNTIL("1.2");
ret_error(r_errcode, CL_LINKER_NOT_AVAILABLE);
return NULL;
}
CLOVER_API cl_int
clUnloadCompiler() {
return CL_SUCCESS;
}
CLOVER_API cl_int
clUnloadPlatformCompiler(cl_platform_id d_platform) {
return CL_SUCCESS;
}
CLOVER_API cl_int
clGetProgramInfo(cl_program d_prog, cl_program_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &prog = obj(d_prog);
switch (param) {
case CL_PROGRAM_REFERENCE_COUNT:
buf.as_scalar<cl_uint>() = prog.ref_count();
break;
case CL_PROGRAM_CONTEXT:
buf.as_scalar<cl_context>() = desc(prog.context());
break;
case CL_PROGRAM_NUM_DEVICES:
buf.as_scalar<cl_uint>() = (prog.devices().size() ?
prog.devices().size() :
prog.context().devices().size());
break;
case CL_PROGRAM_DEVICES:
buf.as_vector<cl_device_id>() = (prog.devices().size() ?
descs(prog.devices()) :
descs(prog.context().devices()));
break;
case CL_PROGRAM_SOURCE:
buf.as_string() = prog.source();
break;
case CL_PROGRAM_BINARY_SIZES:
buf.as_vector<size_t>() = map([&](const device &dev) {
return prog.build(dev).binary.size();
},
prog.devices());
break;
case CL_PROGRAM_BINARIES:
buf.as_matrix<unsigned char>() = map([&](const device &dev) {
std::stringbuf bin;
std::ostream s(&bin);
prog.build(dev).binary.serialize(s);
return bin.str();
},
prog.devices());
break;
case CL_PROGRAM_NUM_KERNELS:
buf.as_scalar<cl_uint>() = prog.symbols().size();
break;
case CL_PROGRAM_KERNEL_NAMES:
buf.as_string() = fold([](const std::string &a, const module::symbol &s) {
return ((a.empty() ? "" : a + ";") + s.name);
}, std::string(), prog.symbols());
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clGetProgramBuildInfo(cl_program d_prog, cl_device_id d_dev,
cl_program_build_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &prog = obj(d_prog);
auto &dev = obj(d_dev);
if (!count(dev, prog.context().devices()))
return CL_INVALID_DEVICE;
switch (param) {
case CL_PROGRAM_BUILD_STATUS:
buf.as_scalar<cl_build_status>() = prog.build(dev).status();
break;
case CL_PROGRAM_BUILD_OPTIONS:
buf.as_string() = prog.build(dev).opts;
break;
case CL_PROGRAM_BUILD_LOG:
buf.as_string() = prog.build(dev).log;
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
<commit_msg>clover: Trivial cleanups for api/program.cpp.<commit_after>//
// Copyright 2012 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.
//
#include "api/util.hpp"
#include "core/program.hpp"
#include <sstream>
using namespace clover;
namespace {
void
validate_build_common(const program &prog, cl_uint num_devs,
const cl_device_id *d_devs,
void (*pfn_notify)(cl_program, void *),
void *user_data) {
if (!pfn_notify && user_data)
throw error(CL_INVALID_VALUE);
if (prog.kernel_ref_count())
throw error(CL_INVALID_OPERATION);
if (any_of([&](const device &dev) {
return !count(dev, prog.context().devices());
}, objs<allow_empty_tag>(d_devs, num_devs)))
throw error(CL_INVALID_DEVICE);
}
}
CLOVER_API cl_program
clCreateProgramWithSource(cl_context d_ctx, cl_uint count,
const char **strings, const size_t *lengths,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
std::string source;
if (!count || !strings ||
any_of(is_zero(), range(strings, count)))
throw error(CL_INVALID_VALUE);
// Concatenate all the provided fragments together
for (unsigned i = 0; i < count; ++i)
source += (lengths && lengths[i] ?
std::string(strings[i], strings[i] + lengths[i]) :
std::string(strings[i]));
// ...and create a program object for them.
ret_error(r_errcode, CL_SUCCESS);
return new program(ctx, source);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_program
clCreateProgramWithBinary(cl_context d_ctx, cl_uint n,
const cl_device_id *d_devs,
const size_t *lengths,
const unsigned char **binaries,
cl_int *r_status, cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto devs = objs(d_devs, n);
if (!lengths || !binaries)
throw error(CL_INVALID_VALUE);
if (any_of([&](const device &dev) {
return !count(dev, ctx.devices());
}, devs))
throw error(CL_INVALID_DEVICE);
// Deserialize the provided binaries,
std::vector<std::pair<cl_int, module>> result = map(
[](const unsigned char *p, size_t l) -> std::pair<cl_int, module> {
if (!p || !l)
return { CL_INVALID_VALUE, {} };
try {
std::stringbuf bin( { (char*)p, l } );
std::istream s(&bin);
return { CL_SUCCESS, module::deserialize(s) };
} catch (std::istream::failure &e) {
return { CL_INVALID_BINARY, {} };
}
},
range(binaries, n),
range(lengths, n));
// update the status array,
if (r_status)
copy(map(keys(), result), r_status);
if (any_of(key_equals(CL_INVALID_VALUE), result))
throw error(CL_INVALID_VALUE);
if (any_of(key_equals(CL_INVALID_BINARY), result))
throw error(CL_INVALID_BINARY);
// initialize a program object with them.
ret_error(r_errcode, CL_SUCCESS);
return new program(ctx, devs, map(values(), result));
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_program
clCreateProgramWithBuiltInKernels(cl_context d_ctx, cl_uint n,
const cl_device_id *d_devs,
const char *kernel_names,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto devs = objs(d_devs, n);
if (any_of([&](const device &dev) {
return !count(dev, ctx.devices());
}, devs))
throw error(CL_INVALID_DEVICE);
// No currently supported built-in kernels.
throw error(CL_INVALID_VALUE);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_int
clRetainProgram(cl_program d_prog) try {
obj(d_prog).retain();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clReleaseProgram(cl_program d_prog) try {
if (obj(d_prog).release())
delete pobj(d_prog);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clBuildProgram(cl_program d_prog, cl_uint num_devs,
const cl_device_id *d_devs, const char *p_opts,
void (*pfn_notify)(cl_program, void *),
void *user_data) try {
auto &prog = obj(d_prog);
auto devs = (d_devs ? objs(d_devs, num_devs) :
ref_vector<device>(prog.context().devices()));
auto opts = (p_opts ? p_opts : "");
validate_build_common(prog, num_devs, d_devs, pfn_notify, user_data);
if (prog.has_source) {
prog.compile(devs, opts);
prog.link(devs, opts, { prog });
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clCompileProgram(cl_program d_prog, cl_uint num_devs,
const cl_device_id *d_devs, const char *p_opts,
cl_uint num_headers, const cl_program *d_header_progs,
const char **header_names,
void (*pfn_notify)(cl_program, void *),
void *user_data) try {
auto &prog = obj(d_prog);
auto devs = (d_devs ? objs(d_devs, num_devs) :
ref_vector<device>(prog.context().devices()));
auto opts = (p_opts ? p_opts : "");
header_map headers;
validate_build_common(prog, num_devs, d_devs, pfn_notify, user_data);
if (bool(num_headers) != bool(header_names))
throw error(CL_INVALID_VALUE);
if (!prog.has_source)
throw error(CL_INVALID_OPERATION);
for_each([&](const char *name, const program &header) {
if (!header.has_source)
throw error(CL_INVALID_OPERATION);
if (!any_of(key_equals(name), headers))
headers.push_back(std::pair<std::string, std::string>(
name, header.source()));
},
range(header_names, num_headers),
objs<allow_empty_tag>(d_header_progs, num_headers));
prog.compile(devs, opts, headers);
return CL_SUCCESS;
} catch (invalid_build_options_error &e) {
return CL_INVALID_COMPILER_OPTIONS;
} catch (build_error &e) {
return CL_COMPILE_PROGRAM_FAILURE;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_program
clLinkProgram(cl_context d_ctx, cl_uint num_devs, const cl_device_id *d_devs,
const char *p_opts, cl_uint num_progs, const cl_program *d_progs,
void (*pfn_notify)(cl_program, void *), void *user_data,
cl_int *r_errcode) {
CLOVER_NOT_SUPPORTED_UNTIL("1.2");
ret_error(r_errcode, CL_LINKER_NOT_AVAILABLE);
return NULL;
}
CLOVER_API cl_int
clUnloadCompiler() {
return CL_SUCCESS;
}
CLOVER_API cl_int
clUnloadPlatformCompiler(cl_platform_id d_platform) {
return CL_SUCCESS;
}
CLOVER_API cl_int
clGetProgramInfo(cl_program d_prog, cl_program_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &prog = obj(d_prog);
switch (param) {
case CL_PROGRAM_REFERENCE_COUNT:
buf.as_scalar<cl_uint>() = prog.ref_count();
break;
case CL_PROGRAM_CONTEXT:
buf.as_scalar<cl_context>() = desc(prog.context());
break;
case CL_PROGRAM_NUM_DEVICES:
buf.as_scalar<cl_uint>() = (prog.devices().size() ?
prog.devices().size() :
prog.context().devices().size());
break;
case CL_PROGRAM_DEVICES:
buf.as_vector<cl_device_id>() = (prog.devices().size() ?
descs(prog.devices()) :
descs(prog.context().devices()));
break;
case CL_PROGRAM_SOURCE:
buf.as_string() = prog.source();
break;
case CL_PROGRAM_BINARY_SIZES:
buf.as_vector<size_t>() = map([&](const device &dev) {
return prog.build(dev).binary.size();
},
prog.devices());
break;
case CL_PROGRAM_BINARIES:
buf.as_matrix<unsigned char>() = map([&](const device &dev) {
std::stringbuf bin;
std::ostream s(&bin);
prog.build(dev).binary.serialize(s);
return bin.str();
},
prog.devices());
break;
case CL_PROGRAM_NUM_KERNELS:
buf.as_scalar<cl_uint>() = prog.symbols().size();
break;
case CL_PROGRAM_KERNEL_NAMES:
buf.as_string() = fold([](const std::string &a, const module::symbol &s) {
return ((a.empty() ? "" : a + ";") + s.name);
}, std::string(), prog.symbols());
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clGetProgramBuildInfo(cl_program d_prog, cl_device_id d_dev,
cl_program_build_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &prog = obj(d_prog);
auto &dev = obj(d_dev);
if (!count(dev, prog.context().devices()))
return CL_INVALID_DEVICE;
switch (param) {
case CL_PROGRAM_BUILD_STATUS:
buf.as_scalar<cl_build_status>() = prog.build(dev).status();
break;
case CL_PROGRAM_BUILD_OPTIONS:
buf.as_string() = prog.build(dev).opts;
break;
case CL_PROGRAM_BUILD_LOG:
buf.as_string() = prog.build(dev).log;
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/sample_logits_op.h"
#include "paddle/fluid/operators/math/sample_prob.h"
namespace paddle {
namespace operators {
class SampleLogitsOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("Logits",
"(Tensor, default: Tensor<float>), The unscaled log probabilities "
"which is a 2-D tensor with shape [N x K]. N is the batch_size, "
"and K is the class number.");
AddInput("Labels",
"(Tensor) The ground truth which is a 2-D tensor. Labels is a "
"Tensor<int64> with shape [N x NT], where NT is the number of"
"true labels for each example.");
AddInput("CustomizedSamples",
"(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
"NT + S],"
" where N is the batch size, NT is the number of true labels "
"and S is the number of negtive sample for each example."
"The first NT elements of each row should be the same with true "
"labels, "
"followed by S custom negtive samples. This tensor"
"is only used when use_customized_samples is true.")
.AsDispensable();
AddInput(
"CustomizedProbabilities",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
"The tensor has the same shape with CustomSamples,"
"and each element represents probability of element in CustomSamples. "
"This "
"tensor is only used when use_customized_samples is true.")
.AsDispensable();
AddOutput("Samples",
"(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
"NT + S]."
"The outputs value of sampler, including NT true lables and S "
"negetive samples "
"for each example. This will be used in"
"backward calculation.")
.AsIntermediate();
AddOutput(
"Probabilities",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
"The probabilites of sampled positive and negtive labels.")
.AsIntermediate();
AddOutput("SampledLogits",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape"
"[N, NT + S]. The outputs value of sampled logits, which will be"
"used in backward propagation.")
.AsIntermediate();
AddOutput(
"SampledLabels",
"(Tensor, default: Tensor<int64>), A 2-D tensor. The sampled labels"
"with shape [N, NT]. The tonsor contains hard labels as input to "
" softmax op, that is 0, 1, …, NT-1 because of the first NT elements"
" of Sampels are positive lables.");
AddAttr<bool>(
"use_customized_samples",
"An indicator whether to use customized samples with probabilities, if "
"True"
"the operator will use customized samples and customized probabilities"
"otherwise, the operator will generate them by itself.")
.SetDefault(false);
AddAttr<bool>(
"uniq",
"An indicator whether to sample non-repetitive negtive labels, if True"
"the operator will sample negtive labels without replacement."
"Otherwise, the operator will sample negtive labels with replacement.")
.SetDefault(true);
AddAttr<bool>(
"remove_accidental_hits",
"An indicator whether to remove accidental hits when samples hits true"
"labels, the removal is implemented by subtracting the corresponding"
"logits by float_max to subpress their softmax to be zero.")
.SetDefault(true);
AddAttr<int>("num_samples", "The number of negative samples.");
AddAttr<int>("seed", "Random seed for generating samples").SetDefault(0);
AddComment(R"DOC(
"""
Computes sampled output training logits and labels suitable for implementing
sampled softmax.
"""
)DOC");
}
};
class SampleLogitsOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Logits"),
"Input(Logits) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("Labels"),
"Input(Labels) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("Samples"),
"Output(Samples) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("Probabilities"),
"Output(Probabilities) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("SampledLogits"),
"Output(SampledLogits) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("SampledLabels"),
"Output(SampledLabels) should be not null.");
auto logits_dims = ctx->GetInputDim("Logits");
auto labels_dims = ctx->GetInputDim("Labels");
PADDLE_ENFORCE_EQ(
logits_dims.size(), 2UL,
"The logits of softmax_with_cross_entropy should be a 2-D tensor.");
PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
"The labels should be a 2-D tensor.");
const int num_samples = ctx->Attrs().Get<int>("num_samples");
const int num_sampled_classes = labels_dims[1] + num_samples;
ctx->SetOutputDim("Samples", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("Probabilities", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("SampledLogits", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("SampledLabels", {logits_dims[0], labels_dims[1]});
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = framework::GetDataTypeOfVar(ctx.InputVar("Logits"));
framework::OpKernelType kt =
framework::OpKernelType(data_type, ctx.device_context());
return kt;
}
};
// UNDERSTAND: InferShape for Grad
class SampleLogitsOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Logits"),
"Input(Logits) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Labels"),
"Input(Labels) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("Samples"),
"Input(Samples) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("SampledLogits"),
"Input(SampledLogits) should be not null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("SampledLogits")),
"Input(SampledLogits@Grad) should not be null.");
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")),
"Output(Logits@Grad) should be not null.");
auto logit_dims = ctx->GetInputDim("Logits");
auto label_dims = ctx->GetInputDim("Labels");
PADDLE_ENFORCE_EQ(label_dims.size(), 2UL,
"The label should be a 2-D tensor.");
PADDLE_ENFORCE_EQ(logit_dims.size(), 2UL,
"The logits should be a 2-D tensor.");
ctx->SetOutputDim(framework::GradVarName("Logits"),
ctx->GetInputDim("Logits"));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = framework::GetDataTypeOfVar(
ctx.InputVar(framework::GradVarName("SampledLogits")));
framework::OpKernelType kt =
framework::OpKernelType(data_type, ctx.device_context());
return kt;
}
};
// UNDERSTAND: what's the rule for making a GradMaker TODO
class SampleLogitsGradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
protected:
std::unique_ptr<framework::OpDesc> Apply() const override {
auto* grad_op = new framework::OpDesc();
grad_op->SetType("sample_logits_grad");
grad_op->SetInput("Logits", Input("Logits"));
grad_op->SetInput("Labels", Input("Labels"));
grad_op->SetInput("Samples", Output("Samples"));
grad_op->SetInput("SampledLogits", Output("SampledLogits"));
grad_op->SetInput(framework::GradVarName("SampledLogits"),
OutputGrad("SampledLogits"));
grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits"));
grad_op->SetAttrMap(Attrs());
return std::unique_ptr<framework::OpDesc>(grad_op);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(sample_logits, ops::SampleLogitsOp, ops::SampleLogitsOpMaker,
ops::SampleLogitsGradMaker);
REGISTER_OPERATOR(sample_logits_grad, ops::SampleLogitsOpGrad);
REGISTER_OP_CPU_KERNEL(sample_logits, ops::SampleLogitsKernel<float>,
ops::SampleLogitsKernel<double>);
REGISTER_OP_CPU_KERNEL(sample_logits_grad, ops::SampleLogitsGradKernel<float>,
ops::SampleLogitsGradKernel<double>);
<commit_msg>remove non-ascii charactor test=develop<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/sample_logits_op.h"
#include "paddle/fluid/operators/math/sample_prob.h"
namespace paddle {
namespace operators {
class SampleLogitsOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("Logits",
"(Tensor, default: Tensor<float>), The unscaled log probabilities "
"which is a 2-D tensor with shape [N x K]. N is the batch_size, "
"and K is the class number.");
AddInput("Labels",
"(Tensor) The ground truth which is a 2-D tensor. Labels is a "
"Tensor<int64> with shape [N x NT], where NT is the number of"
"true labels for each example.");
AddInput("CustomizedSamples",
"(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
"NT + S],"
" where N is the batch size, NT is the number of true labels "
"and S is the number of negtive sample for each example."
"The first NT elements of each row should be the same with true "
"labels, "
"followed by S custom negtive samples. This tensor"
"is only used when use_customized_samples is true.")
.AsDispensable();
AddInput(
"CustomizedProbabilities",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
"The tensor has the same shape with CustomSamples,"
"and each element represents probability of element in CustomSamples. "
"This "
"tensor is only used when use_customized_samples is true.")
.AsDispensable();
AddOutput("Samples",
"(Tensor, default: Tensor<int64_t>), A 2-D tensor with shape [N, "
"NT + S]."
"The outputs value of sampler, including NT true lables and S "
"negetive samples "
"for each example. This will be used in"
"backward calculation.")
.AsIntermediate();
AddOutput(
"Probabilities",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape [N, NT + S]."
"The probabilites of sampled positive and negtive labels.")
.AsIntermediate();
AddOutput("SampledLogits",
"(Tensor, default: Tensor<float>), A 2-D tensor with shape"
"[N, NT + S]. The outputs value of sampled logits, which will be"
"used in backward propagation.")
.AsIntermediate();
AddOutput(
"SampledLabels",
"(Tensor, default: Tensor<int64>), A 2-D tensor. The sampled labels"
"with shape [N, NT]. The tonsor contains hard labels as input to "
" softmax op, that is 0, 1, ..., NT-1 because of the first NT elements"
" of Sampels are positive lables.");
AddAttr<bool>(
"use_customized_samples",
"An indicator whether to use customized samples with probabilities, if "
"True"
"the operator will use customized samples and customized probabilities"
"otherwise, the operator will generate them by itself.")
.SetDefault(false);
AddAttr<bool>(
"uniq",
"An indicator whether to sample non-repetitive negtive labels, if True"
"the operator will sample negtive labels without replacement."
"Otherwise, the operator will sample negtive labels with replacement.")
.SetDefault(true);
AddAttr<bool>(
"remove_accidental_hits",
"An indicator whether to remove accidental hits when samples hits true"
"labels, the removal is implemented by subtracting the corresponding"
"logits by float_max to subpress their softmax to be zero.")
.SetDefault(true);
AddAttr<int>("num_samples", "The number of negative samples.");
AddAttr<int>("seed", "Random seed for generating samples").SetDefault(0);
AddComment(R"DOC(
"""
Computes sampled output training logits and labels suitable for implementing
sampled softmax.
"""
)DOC");
}
};
class SampleLogitsOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Logits"),
"Input(Logits) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("Labels"),
"Input(Labels) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("Samples"),
"Output(Samples) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("Probabilities"),
"Output(Probabilities) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("SampledLogits"),
"Output(SampledLogits) should be not null.");
PADDLE_ENFORCE(ctx->HasOutput("SampledLabels"),
"Output(SampledLabels) should be not null.");
auto logits_dims = ctx->GetInputDim("Logits");
auto labels_dims = ctx->GetInputDim("Labels");
PADDLE_ENFORCE_EQ(
logits_dims.size(), 2UL,
"The logits of softmax_with_cross_entropy should be a 2-D tensor.");
PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
"The labels should be a 2-D tensor.");
const int num_samples = ctx->Attrs().Get<int>("num_samples");
const int num_sampled_classes = labels_dims[1] + num_samples;
ctx->SetOutputDim("Samples", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("Probabilities", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("SampledLogits", {logits_dims[0], num_sampled_classes});
ctx->SetOutputDim("SampledLabels", {logits_dims[0], labels_dims[1]});
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = framework::GetDataTypeOfVar(ctx.InputVar("Logits"));
framework::OpKernelType kt =
framework::OpKernelType(data_type, ctx.device_context());
return kt;
}
};
// UNDERSTAND: InferShape for Grad
class SampleLogitsOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Logits"),
"Input(Logits) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Labels"),
"Input(Labels) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("Samples"),
"Input(Samples) should be not null.");
PADDLE_ENFORCE(ctx->HasInput("SampledLogits"),
"Input(SampledLogits) should be not null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("SampledLogits")),
"Input(SampledLogits@Grad) should not be null.");
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")),
"Output(Logits@Grad) should be not null.");
auto logit_dims = ctx->GetInputDim("Logits");
auto label_dims = ctx->GetInputDim("Labels");
PADDLE_ENFORCE_EQ(label_dims.size(), 2UL,
"The label should be a 2-D tensor.");
PADDLE_ENFORCE_EQ(logit_dims.size(), 2UL,
"The logits should be a 2-D tensor.");
ctx->SetOutputDim(framework::GradVarName("Logits"),
ctx->GetInputDim("Logits"));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = framework::GetDataTypeOfVar(
ctx.InputVar(framework::GradVarName("SampledLogits")));
framework::OpKernelType kt =
framework::OpKernelType(data_type, ctx.device_context());
return kt;
}
};
// UNDERSTAND: what's the rule for making a GradMaker TODO
class SampleLogitsGradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
protected:
std::unique_ptr<framework::OpDesc> Apply() const override {
auto* grad_op = new framework::OpDesc();
grad_op->SetType("sample_logits_grad");
grad_op->SetInput("Logits", Input("Logits"));
grad_op->SetInput("Labels", Input("Labels"));
grad_op->SetInput("Samples", Output("Samples"));
grad_op->SetInput("SampledLogits", Output("SampledLogits"));
grad_op->SetInput(framework::GradVarName("SampledLogits"),
OutputGrad("SampledLogits"));
grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits"));
grad_op->SetAttrMap(Attrs());
return std::unique_ptr<framework::OpDesc>(grad_op);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(sample_logits, ops::SampleLogitsOp, ops::SampleLogitsOpMaker,
ops::SampleLogitsGradMaker);
REGISTER_OPERATOR(sample_logits_grad, ops::SampleLogitsOpGrad);
REGISTER_OP_CPU_KERNEL(sample_logits, ops::SampleLogitsKernel<float>,
ops::SampleLogitsKernel<double>);
REGISTER_OP_CPU_KERNEL(sample_logits_grad, ops::SampleLogitsGradKernel<float>,
ops::SampleLogitsGradKernel<double>);
<|endoftext|> |
<commit_before>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <cstdint>
#include <cstdio>
#include <thread>
#include <array>
#include <csignal>
#include <cinttypes>
#include "util/CommandOptionParser.h"
#include "Configuration.h"
#include "Aeron.h"
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running(true);
void sigIntHandler(int)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optChannel = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger = 'l';
struct Settings
{
std::string dirPrefix = "";
std::string channel = samples::configuration::DEFAULT_CHANNEL;
std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
long long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
};
typedef std::array<std::uint8_t, 256> buffer_t;
Settings parseCmdLine(CommandOptionParser &cp, int argc, char **argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.channel = cp.getOption(optChannel).getParam(0, s.channel);
s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, INT64_MAX, s.numberOfMessages);
s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);
return s;
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption(optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption(optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption(optChannel, 1, 1, "channel Channel."));
cp.addOption(CommandOption(optStreamId, 1, 1, "streamId Stream ID."));
cp.addOption(CommandOption(optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption(optLinger, 1, 1, "milliseconds Linger timeout in milliseconds."));
signal(SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
std::cout << "Publishing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl;
aeron::Context context;
if (!settings.dirPrefix.empty())
{
context.aeronDir(settings.dirPrefix);
}
context.newPublicationHandler(
[](const std::string &channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
std::shared_ptr<Aeron> aeron = Aeron::connect(context);
// add the publication to start the process
std::int64_t id = aeron->addPublication(settings.channel, settings.streamId);
std::shared_ptr<Publication> publication = aeron->findPublication(id);
// wait for the publication to be valid
while (!publication)
{
std::this_thread::yield();
publication = aeron->findPublication(id);
}
const std::int64_t channelStatus = publication->channelStatus();
std::cout << "Publication channel status (id=" << publication->channelStatusId() << ") "
<< (channelStatus == ChannelEndpointStatus::CHANNEL_ENDPOINT_ACTIVE ?
"ACTIVE" : std::to_string(channelStatus))
<< std::endl;
AERON_DECL_ALIGNED(buffer_t buffer, 16);
concurrent::AtomicBuffer srcBuffer(&buffer[0], buffer.size());
char message[256];
for (std::int64_t i = 0; i < settings.numberOfMessages && running; i++)
{
#if _MSC_VER
const int messageLen = ::sprintf_s(message, sizeof(message), "Hello World! %" PRId64, i);
#else
const int messageLen = ::snprintf(message, sizeof(message), "Hello World! %" PRId64, i);
#endif
srcBuffer.putBytes(0, reinterpret_cast<std::uint8_t *>(message), messageLen);
std::cout << "offering " << i << "/" << settings.numberOfMessages << " - ";
std::cout.flush();
const std::int64_t result = publication->offer(srcBuffer, 0, messageLen);
if (result > 0)
{
std::cout << "yay!" << std::endl;
}
else if (BACK_PRESSURED == result)
{
std::cout << "Offer failed due to back pressure" << std::endl;
}
else if (NOT_CONNECTED == result)
{
std::cout << "Offer failed because publisher is not connected to a subscriber" << std::endl;
}
else if (ADMIN_ACTION == result)
{
std::cout << "Offer failed because of an administration action in the system" << std::endl;
}
else if (PUBLICATION_CLOSED == result)
{
std::cout << "Offer failed publication is closed" << std::endl;
}
else
{
std::cout << "Offer failed due to unknown reason" << result << std::endl;
}
if (!publication->isConnected())
{
std::cout << "No active subscribers detected" << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Done sending." << std::endl;
if (settings.lingerTimeoutMs > 0)
{
std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
}
}
catch (const CommandOptionException &e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (const SourcedException &e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (const std::exception &e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<commit_msg>[C++] Samples tidy up.<commit_after>/*
* Copyright 2014-2020 Real Logic Limited.
*
* 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
*
* https://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 <cstdint>
#include <cstdio>
#include <thread>
#include <array>
#include <csignal>
#include <cinttypes>
#include "util/CommandOptionParser.h"
#include "Configuration.h"
#include "Aeron.h"
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running(true);
void sigIntHandler(int)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optChannel = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger = 'l';
struct Settings
{
std::string dirPrefix = "";
std::string channel = samples::configuration::DEFAULT_CHANNEL;
std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
long long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
};
typedef std::array<std::uint8_t, 256> buffer_t;
Settings parseCmdLine(CommandOptionParser &cp, int argc, char **argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.channel = cp.getOption(optChannel).getParam(0, s.channel);
s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, INT64_MAX, s.numberOfMessages);
s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);
return s;
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption(optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption(optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption(optChannel, 1, 1, "channel Channel."));
cp.addOption(CommandOption(optStreamId, 1, 1, "streamId Stream ID."));
cp.addOption(CommandOption(optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption(optLinger, 1, 1, "milliseconds Linger timeout in milliseconds."));
signal(SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
std::cout << "Publishing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl;
aeron::Context context;
if (!settings.dirPrefix.empty())
{
context.aeronDir(settings.dirPrefix);
}
context.newPublicationHandler(
[](const std::string &channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
std::shared_ptr<Aeron> aeron = Aeron::connect(context);
// add the publication to start the process
std::int64_t id = aeron->addPublication(settings.channel, settings.streamId);
std::shared_ptr<Publication> publication = aeron->findPublication(id);
// wait for the publication to be valid
while (!publication)
{
std::this_thread::yield();
publication = aeron->findPublication(id);
}
const std::int64_t channelStatus = publication->channelStatus();
std::cout << "Publication channel status (id=" << publication->channelStatusId() << ") "
<< (channelStatus == ChannelEndpointStatus::CHANNEL_ENDPOINT_ACTIVE ?
"ACTIVE" : std::to_string(channelStatus))
<< std::endl;
AERON_DECL_ALIGNED(buffer_t buffer, 16);
concurrent::AtomicBuffer srcBuffer(&buffer[0], buffer.size());
char message[256];
for (std::int64_t i = 0; i < settings.numberOfMessages && running; i++)
{
#if _MSC_VER
const int messageLen = ::sprintf_s(message, sizeof(message), "Hello World! %" PRId64, i);
#else
const int messageLen = ::snprintf(message, sizeof(message), "Hello World! %" PRId64, i);
#endif
srcBuffer.putBytes(0, reinterpret_cast<std::uint8_t *>(message), messageLen);
std::cout << "offering " << i << "/" << settings.numberOfMessages << " - ";
std::cout.flush();
const std::int64_t result = publication->offer(srcBuffer, 0, messageLen);
if (result > 0)
{
std::cout << "yay!" << std::endl;
}
else if (BACK_PRESSURED == result)
{
std::cout << "Offer failed due to back pressure" << std::endl;
}
else if (NOT_CONNECTED == result)
{
std::cout << "Offer failed because publisher is not connected to a subscriber" << std::endl;
}
else if (ADMIN_ACTION == result)
{
std::cout << "Offer failed because of an administration action in the system" << std::endl;
}
else if (PUBLICATION_CLOSED == result)
{
std::cout << "Offer failed publication is closed" << std::endl;
}
else
{
std::cout << "Offer failed due to unknown reason " << result << std::endl;
}
if (!publication->isConnected())
{
std::cout << "No active subscribers detected" << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Done sending." << std::endl;
if (settings.lingerTimeoutMs > 0)
{
std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
}
}
catch (const CommandOptionException &e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (const SourcedException &e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (const std::exception &e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief Aql, list of running queries
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/QueryList.h"
#include "Aql/Query.h"
#include "Basics/ReadLocker.h"
#include "Basics/WriteLocker.h"
#include "VocBase/vocbase.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- struct QueryEntry
// -----------------------------------------------------------------------------
QueryEntry::QueryEntry (TRI_voc_tick_t id,
char const* queryString,
size_t queryLength,
double started)
: id(id),
queryString(queryString),
queryLength(queryLength),
started(started) {
}
// -----------------------------------------------------------------------------
// --SECTION-- struct QueryEntryCopy
// -----------------------------------------------------------------------------
QueryEntryCopy::QueryEntryCopy (TRI_voc_tick_t id,
std::string const& queryString,
double started,
double runTime)
: id(id),
queryString(queryString),
started(started),
runTime(runTime) {
}
// -----------------------------------------------------------------------------
// --SECTION-- class QueryList
// -----------------------------------------------------------------------------
double const QueryList::DefaultSlowQueryThreshold = 10.0;
size_t const QueryList::DefaultMaxSlowQueries = 64;
size_t const QueryList::DefaultMaxQueryStringLength = 4096;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief create a query list
////////////////////////////////////////////////////////////////////////////////
QueryList::QueryList (TRI_vocbase_t* vocbase)
: _vocbase(vocbase),
_lock(),
_current(),
_slow(),
_slowCount(0),
_enabled(false),
_trackSlowQueries(true),
_slowQueryThreshold(QueryList::DefaultSlowQueryThreshold),
_maxSlowQueries(QueryList::DefaultMaxSlowQueries),
_maxQueryStringLength(QueryList::DefaultMaxQueryStringLength) {
_current.reserve(64);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroy a query list
////////////////////////////////////////////////////////////////////////////////
QueryList::~QueryList () {
WRITE_LOCKER(_lock);
for (auto it : _current) {
delete it.second;
}
_current.clear();
_slow.clear();
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief insert a query
////////////////////////////////////////////////////////////////////////////////
void QueryList::insert (Query const* query,
double stamp) {
// no query string
if (query->queryString() == nullptr || ! _enabled) {
return;
}
try {
std::unique_ptr<QueryEntry> entry(new QueryEntry(
query->id(),
query->queryString(),
query->queryLength(),
stamp
));
WRITE_LOCKER(_lock);
auto it = _current.emplace(std::make_pair(query->id(), entry.get()));
if (it.second) {
entry.release();
}
}
catch (...) {
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a query
////////////////////////////////////////////////////////////////////////////////
void QueryList::remove (Query const* query,
double now) {
// no query string
if (query->queryString() == nullptr || ! _enabled) {
return;
}
QueryEntry* entry = nullptr;
{
WRITE_LOCKER(_lock);
auto it = _current.find(query->id());
if (it != _current.end()) {
entry = (*it).second;
_current.erase(it);
TRI_ASSERT(entry != nullptr);
try {
// check if we need to push the query into the list of slow queries
if (_slowQueryThreshold >= 0.0 &&
now - entry->started >= _slowQueryThreshold) {
// yes.
size_t const maxLength = _maxQueryStringLength;
size_t length = entry->queryLength;
if (length > maxLength) {
length = maxLength;
// do not create invalid UTF-8 sequences
while (length > 0) {
uint8_t c = entry->queryString[length - 1];
if ((c & 0b10000000) == 0) {
// single-byte character
break;
}
--length;
// start of a multi-byte sequence
if ((c & 0b11000000) == 0b11000000) {
// decrease length by one more, so we the string contains the
// last part of the previous (multi-byte?) sequence
break;
}
}
}
_slow.emplace_back(QueryEntryCopy(
entry->id,
std::string(entry->queryString, length).append(entry->queryLength > maxLength ? "..." : ""),
entry->started,
now - entry->started
));
if (++_slowCount > _maxSlowQueries) {
// free first element
_slow.pop_front();
--_slowCount;
}
}
}
catch (...) {
}
}
}
if (entry != nullptr) {
delete entry;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the list of currently running queries
////////////////////////////////////////////////////////////////////////////////
std::vector<QueryEntryCopy> QueryList::listCurrent () {
double const now = TRI_microtime();
std::vector<QueryEntryCopy> result;
{
size_t const maxLength = _maxQueryStringLength;
READ_LOCKER(_lock);
result.reserve(_current.size());
for (auto const& it : _current) {
auto entry = it.second;
if (entry == nullptr ||
entry->queryString == nullptr) {
continue;
}
size_t length = entry->queryLength;
if (length > maxLength) {
length = maxLength;
// do not create invalid UTF-8 sequences
while (length > 0) {
uint8_t c = entry->queryString[length - 1];
if ((c & 0b10000000) == 0) {
// single-byte character
break;
}
--length;
// start of a multi-byte sequence
if ((c & 0b11000000) == 0b11000000) {
// decrease length by one more, so we the string contains the
// last part of the previous (multi-byte?) sequence
break;
}
}
}
result.emplace_back(QueryEntryCopy(
entry->id,
std::string(entry->queryString, length).append(entry->queryLength > maxLength ? "..." : ""),
entry->started,
now - entry->started
));
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the list of slow queries
////////////////////////////////////////////////////////////////////////////////
std::vector<QueryEntryCopy> QueryList::listSlow () {
std::vector<QueryEntryCopy> result;
{
READ_LOCKER(_lock);
result.reserve(_slow.size());
result.assign(_slow.begin(), _slow.end());
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief clear the list of slow queries
////////////////////////////////////////////////////////////////////////////////
void QueryList::clearSlow () {
WRITE_LOCKER(_lock);
_slow.clear();
_slowCount = 0;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>enable query tracking by default<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief Aql, list of running queries
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/QueryList.h"
#include "Aql/Query.h"
#include "Basics/ReadLocker.h"
#include "Basics/WriteLocker.h"
#include "VocBase/vocbase.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- struct QueryEntry
// -----------------------------------------------------------------------------
QueryEntry::QueryEntry (TRI_voc_tick_t id,
char const* queryString,
size_t queryLength,
double started)
: id(id),
queryString(queryString),
queryLength(queryLength),
started(started) {
}
// -----------------------------------------------------------------------------
// --SECTION-- struct QueryEntryCopy
// -----------------------------------------------------------------------------
QueryEntryCopy::QueryEntryCopy (TRI_voc_tick_t id,
std::string const& queryString,
double started,
double runTime)
: id(id),
queryString(queryString),
started(started),
runTime(runTime) {
}
// -----------------------------------------------------------------------------
// --SECTION-- class QueryList
// -----------------------------------------------------------------------------
double const QueryList::DefaultSlowQueryThreshold = 10.0;
size_t const QueryList::DefaultMaxSlowQueries = 64;
size_t const QueryList::DefaultMaxQueryStringLength = 4096;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief create a query list
////////////////////////////////////////////////////////////////////////////////
QueryList::QueryList (TRI_vocbase_t* vocbase)
: _vocbase(vocbase),
_lock(),
_current(),
_slow(),
_slowCount(0),
_enabled(true),
_trackSlowQueries(true),
_slowQueryThreshold(QueryList::DefaultSlowQueryThreshold),
_maxSlowQueries(QueryList::DefaultMaxSlowQueries),
_maxQueryStringLength(QueryList::DefaultMaxQueryStringLength) {
_current.reserve(64);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroy a query list
////////////////////////////////////////////////////////////////////////////////
QueryList::~QueryList () {
WRITE_LOCKER(_lock);
for (auto it : _current) {
delete it.second;
}
_current.clear();
_slow.clear();
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief insert a query
////////////////////////////////////////////////////////////////////////////////
void QueryList::insert (Query const* query,
double stamp) {
// no query string
if (query->queryString() == nullptr || ! _enabled) {
return;
}
try {
std::unique_ptr<QueryEntry> entry(new QueryEntry(
query->id(),
query->queryString(),
query->queryLength(),
stamp
));
WRITE_LOCKER(_lock);
auto it = _current.emplace(std::make_pair(query->id(), entry.get()));
if (it.second) {
entry.release();
}
}
catch (...) {
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a query
////////////////////////////////////////////////////////////////////////////////
void QueryList::remove (Query const* query,
double now) {
// no query string
if (query->queryString() == nullptr || ! _enabled) {
return;
}
QueryEntry* entry = nullptr;
{
WRITE_LOCKER(_lock);
auto it = _current.find(query->id());
if (it != _current.end()) {
entry = (*it).second;
_current.erase(it);
TRI_ASSERT(entry != nullptr);
try {
// check if we need to push the query into the list of slow queries
if (_slowQueryThreshold >= 0.0 &&
now - entry->started >= _slowQueryThreshold) {
// yes.
size_t const maxLength = _maxQueryStringLength;
size_t length = entry->queryLength;
if (length > maxLength) {
length = maxLength;
// do not create invalid UTF-8 sequences
while (length > 0) {
uint8_t c = entry->queryString[length - 1];
if ((c & 0b10000000) == 0) {
// single-byte character
break;
}
--length;
// start of a multi-byte sequence
if ((c & 0b11000000) == 0b11000000) {
// decrease length by one more, so we the string contains the
// last part of the previous (multi-byte?) sequence
break;
}
}
}
_slow.emplace_back(QueryEntryCopy(
entry->id,
std::string(entry->queryString, length).append(entry->queryLength > maxLength ? "..." : ""),
entry->started,
now - entry->started
));
if (++_slowCount > _maxSlowQueries) {
// free first element
_slow.pop_front();
--_slowCount;
}
}
}
catch (...) {
}
}
}
if (entry != nullptr) {
delete entry;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the list of currently running queries
////////////////////////////////////////////////////////////////////////////////
std::vector<QueryEntryCopy> QueryList::listCurrent () {
double const now = TRI_microtime();
std::vector<QueryEntryCopy> result;
{
size_t const maxLength = _maxQueryStringLength;
READ_LOCKER(_lock);
result.reserve(_current.size());
for (auto const& it : _current) {
auto entry = it.second;
if (entry == nullptr ||
entry->queryString == nullptr) {
continue;
}
size_t length = entry->queryLength;
if (length > maxLength) {
length = maxLength;
// do not create invalid UTF-8 sequences
while (length > 0) {
uint8_t c = entry->queryString[length - 1];
if ((c & 0b10000000) == 0) {
// single-byte character
break;
}
--length;
// start of a multi-byte sequence
if ((c & 0b11000000) == 0b11000000) {
// decrease length by one more, so we the string contains the
// last part of the previous (multi-byte?) sequence
break;
}
}
}
result.emplace_back(QueryEntryCopy(
entry->id,
std::string(entry->queryString, length).append(entry->queryLength > maxLength ? "..." : ""),
entry->started,
now - entry->started
));
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the list of slow queries
////////////////////////////////////////////////////////////////////////////////
std::vector<QueryEntryCopy> QueryList::listSlow () {
std::vector<QueryEntryCopy> result;
{
READ_LOCKER(_lock);
result.reserve(_slow.size());
result.assign(_slow.begin(), _slow.end());
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief clear the list of slow queries
////////////////////////////////////////////////////////////////////////////////
void QueryList::clearSlow () {
WRITE_LOCKER(_lock);
_slow.clear();
_slowCount = 0;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before><commit_msg>MSAA VSMs seem to now work on Qualcomm h/w<commit_after><|endoftext|> |
<commit_before>/*
* KDots
* Copyright (c) 2011-2012 Minh Ngo <ignotusp@fedoraproject.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "dottable.hpp"
#include "polygonfinder.hpp"
#include "stepqueue.hpp"
namespace KDots
{
DotTable::DotTable (const GameConfig& config, QObject *parent)
: QObject (parent)
, m_graph (config.m_width, config.m_height)
, m_steps (config.m_mode == DEFAULT_MODE
? new StepQueue (config.m_firstOwner)
: new ExtraStepQueue (config.m_firstOwner))
, m_config (config)
{
}
GameConfig DotTable::gameConfig () const
{
return m_config;
}
namespace
{
Point getPrevPoint (Polygon_ptr& polygon, Polygon::const_iterator current)
{
const int currentY = current->y ();
for (Polygon::const_iterator prev = current;;)
{
if (prev == polygon->begin ())
prev = --polygon->end ();
else
--prev;
if (prev->y () != currentY)
return *prev;
}
}
Point getNextPoint (Polygon_ptr& polygon, int& shift, Polygon::const_iterator current)
{
const int currentY = current->y ();
shift = 0;
for (Polygon::const_iterator next = current;;)
{
++shift;
if (next == --polygon->end ())
next = polygon->begin ();
else
++next;
if (next->y () != currentY)
return *next;
}
}
bool isInPolygon (Polygon_ptr polygon, const Point& point)
{
// k - a count of points in the same line with "point" object
// i - crosses count
int i = 0, shift;
Polygon::const_iterator itr = polygon->begin (), itrEnd = polygon->end ();
while (itr != itrEnd)
{
if (itr->y () != point.y ())
{
++itr;
continue;
}
const Point& prevPoint = getPrevPoint (polygon, itr);
const Point& nextPoint = getNextPoint (polygon, shift, itr);
if (itr->x () < point.x () && prevPoint.y () != nextPoint.y () && shift == 1)
++i;
++itr;
}
return i % 2;
}
}
void DotTable::pushPoint (const Point& point)
{
GraphPoint& currentPoint = m_graph[point];
if (currentPoint.owner () != NONE || currentPoint.isCaptured ())
return;
const Owner current = m_steps->getCurrentOwner ();
currentPoint.setOwner (current);
m_steps->addPoint (point);
PolygonFinder findPolygon (m_graph, current);
//O(n)
const PolyList& polyList = findPolygon (point);
const std::list<Point>& points = m_steps->getPoints (StepQueue::other (current));
if (points.empty () || polyList.empty ())
{
m_steps->nextStep ();
emit nextPlayer (point);
return;
}
for (int k = 0, j; k < m_graph.width (); ++k)
{
for (j = 0; j < m_graph.height (); ++j)
{
GraphPoint& gpoint = m_graph[k][j];
if (gpoint.isCaptured () || gpoint.owner () == current)
continue;
for (Polygon_ptr polygon : polyList)
{
const Point newPoint (k, j);
if (isInPolygon (polygon, newPoint))
{
if (gpoint.owner () == StepQueue::other (current))
{
polygon->setFilled (true);
m_steps->addCaptured ();
}
gpoint.capture ();
break;
}
}
}
}
drawPolygon (polyList);
m_steps->nextStep ();
emit nextPlayer (point);
}
void DotTable::drawPolygon (PolyList polygons)
{
for (Polygon_ptr polygon : polygons)
{
if (!polygon->isFilled ())
continue;
polygon->setOwner (m_steps->getCurrentOwner ());
m_polygons.push_back (polygon);
Point prevPoint = polygon->back ();
for (const Point& currPoint : *polygon.get ())
{
m_graph.addEdge (prevPoint, currPoint);
prevPoint = currPoint;
}
}
}
}
#include "include/dottable.moc"
<commit_msg>Fixing the game engine<commit_after>/*
* KDots
* Copyright (c) 2011-2012 Minh Ngo <ignotusp@fedoraproject.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "dottable.hpp"
#include "polygonfinder.hpp"
#include "stepqueue.hpp"
#define BOARD_LOOP_BEGIN(X_ITER, Y_ITER) \
for (int X_ITER = 0, Y_ITER; X_ITER < m_graph.width (); ++X_ITER) \
{ \
for (Y_ITER = 0; Y_ITER < m_graph.height (); ++Y_ITER) \
{
#define BOARD_LOOP_END }}
namespace KDots
{
DotTable::DotTable (const GameConfig& config, QObject *parent)
: QObject (parent)
, m_graph (config.m_width, config.m_height)
, m_steps (config.m_mode == DEFAULT_MODE
? new StepQueue (config.m_firstOwner)
: new ExtraStepQueue (config.m_firstOwner))
, m_config (config)
{
}
GameConfig DotTable::gameConfig () const
{
return m_config;
}
namespace
{
Point getPrevPoint (Polygon_ptr& polygon, Polygon::const_iterator current)
{
const int currentY = current->y ();
for (Polygon::const_iterator prev = current;;)
{
if (prev == polygon->begin ())
prev = --polygon->end ();
else
--prev;
if (prev->y () != currentY)
return *prev;
}
}
Point getNextPoint (Polygon_ptr& polygon, int& shift, Polygon::const_iterator current)
{
const int currentY = current->y ();
shift = 0;
for (Polygon::const_iterator next = current;;)
{
++shift;
if (next == --polygon->end ())
next = polygon->begin ();
else
++next;
if (next->y () != currentY)
return *next;
}
}
bool isInPolygon (Polygon_ptr polygon, const Point& point)
{
// k - a count of points in the same line with "point" object
// i - crosses count
int i = 0, shift;
Polygon::const_iterator itr = polygon->begin (), itrEnd = polygon->end ();
while (itr != itrEnd)
{
if (itr->y () != point.y ())
{
++itr;
continue;
}
const Point& prevPoint = getPrevPoint (polygon, itr);
const Point& nextPoint = getNextPoint (polygon, shift, itr);
if (itr->x () < point.x () && prevPoint.y () != nextPoint.y () && shift == 1)
++i;
++itr;
}
return i % 2;
}
}
void DotTable::pushPoint (const Point& point)
{
GraphPoint& currentPoint = m_graph[point];
if (currentPoint.owner () != NONE || currentPoint.isCaptured ())
return;
const Owner current = m_steps->getCurrentOwner ();
currentPoint.setOwner (current);
m_steps->addPoint (point);
PolygonFinder findPolygon (m_graph, current);
//O(n)
const PolyList& polyList = findPolygon (point);
const std::list<Point>& points = m_steps->getPoints (StepQueue::other (current));
if (points.empty () || polyList.empty ())
{
m_steps->nextStep ();
emit nextPlayer (point);
return;
}
const Owner otherOwner = StepQueue::other (current);
BOARD_LOOP_BEGIN (k, j)
GraphPoint& gpoint = m_graph[k][j];
if (gpoint.isCaptured () || gpoint.owner () != otherOwner)
continue;
for (Polygon_ptr polygon : polyList)
{
const Point newPoint (k, j);
if (isInPolygon (polygon, newPoint))
{
if (gpoint.owner () == otherOwner)
{
polygon->setFilled (true);
m_steps->addCaptured ();
}
gpoint.capture ();
break;
}
}
BOARD_LOOP_END;
BOARD_LOOP_BEGIN (k, j)
GraphPoint& gpoint = m_graph[k][j];
if (gpoint.isCaptured () || gpoint.owner () != NONE)
continue;
for (Polygon_ptr polygon : polyList)
{
const Point newPoint (k, j);
if (isInPolygon (polygon, newPoint) && polygon->isFilled ())
{
gpoint.capture ();
break;
}
}
BOARD_LOOP_END;
drawPolygon (polyList);
m_steps->nextStep ();
emit nextPlayer (point);
}
void DotTable::drawPolygon (PolyList polygons)
{
for (Polygon_ptr polygon : polygons)
{
if (!polygon->isFilled ())
continue;
polygon->setOwner (m_steps->getCurrentOwner ());
m_polygons.push_back (polygon);
Point prevPoint = polygon->back ();
for (const Point& currPoint : *polygon.get ())
{
m_graph.addEdge (prevPoint, currPoint);
prevPoint = currPoint;
}
}
}
}
#undef BOARD_LOOP_BEGIN
#undef BOARD_LOOP_END
#include "include/dottable.moc"
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_XML_PARSE_HPP
#define TORRENT_XML_PARSE_HPP
namespace libtorrent
{
enum
{
xml_start_tag,
xml_end_tag,
xml_empty_tag,
xml_declaration_tag,
xml_string,
xml_attribute,
xml_comment,
xml_parse_error
};
// callback(int type, char const* str, char const* str2)
// str2 is only used for attributes. str is name and str2 is value
template <class CallbackType>
void xml_parse(char* p, char* end, CallbackType callback)
{
for(;p != end; ++p)
{
char const* start = p;
char const* val_start = 0;
int token;
// look for tag start
for(; *p != '<' && p != end; ++p);
if (p != start)
{
if (p != end)
{
assert(*p == '<');
*p = 0;
}
token = xml_string;
callback(token, start, val_start);
if (p != end) *p = '<';
}
if (p == end) break;
// skip '<'
++p;
// parse the name of the tag.
for (start = p; p != end && *p != '>' && *p != ' '; ++p);
char* tag_name_end = p;
// skip the attributes for now
for (; p != end && *p != '>'; ++p);
// parse error
if (p == end)
{
token = xml_parse_error;
start = "unexpected end of file";
callback(token, start, val_start);
break;
}
assert(*p == '>');
// save the character that terminated the tag name
// it could be both '>' and ' '.
char save = *tag_name_end;
*tag_name_end = 0;
char* tag_end = p;
if (*start == '/')
{
++start;
token = xml_end_tag;
callback(token, start, val_start);
}
else if (*(p-1) == '/')
{
*(p-1) = 0;
token = xml_empty_tag;
callback(token, start, val_start);
*(p-1) = '/';
tag_end = p - 1;
}
else if (*start == '?' && *(p-1) == '?')
{
*(p-1) = 0;
++start;
token = xml_declaration_tag;
callback(token, start, val_start);
*(p-1) = '?';
tag_end = p - 1;
}
else if (start + 5 < p && memcmp(start, "!--", 3) == 0 && memcmp(p-2, "--", 2) == 0)
{
start += 3;
*(p-2) = 0;
token = xml_comment;
callback(token, start, val_start);
*(p-2) = '-';
tag_end = p - 2;
}
else
{
token = xml_start_tag;
callback(token, start, val_start);
}
*tag_name_end = save;
// parse attributes
for (char* i = tag_name_end; i < tag_end; ++i)
{
// find start of attribute name
for (; i != tag_end && (*i == ' ' || *i == '\t'); ++i);
if (i == tag_end) break;
start = i;
// find end of attribute name
for (; i != tag_end && *i != '=' && *i != ' ' && *i != '\t'; ++i);
char* name_end = i;
// look for equality sign
for (; i != tag_end && *i != '='; ++i);
if (i == tag_end)
{
token = xml_parse_error;
val_start = 0;
start = "garbage inside element brackets";
callback(token, start, val_start);
break;
}
++i;
for (; i != tag_end && (*i == ' ' || *i == '\t'); ++i);
// check for parse error (values must be quoted)
if (i == tag_end || (*i != '\'' && *i != '\"'))
{
token = xml_parse_error;
val_start = 0;
start = "unquoted attribute value";
callback(token, start, val_start);
break;
}
char quote = *i;
++i;
val_start = i;
for (; i != tag_end && *i != quote; ++i);
// parse error (missing end quote)
if (i == tag_end)
{
token = xml_parse_error;
val_start = 0;
start = "missing end quote on attribute";
callback(token, start, val_start);
break;
}
save = *i;
*i = 0;
*name_end = 0;
token = xml_attribute;
callback(token, start, val_start);
*name_end = '=';
*i = save;
}
}
}
}
#endif
<commit_msg>xml parser fixes<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_XML_PARSE_HPP
#define TORRENT_XML_PARSE_HPP
#include <cctype>
namespace libtorrent
{
enum
{
xml_start_tag,
xml_end_tag,
xml_empty_tag,
xml_declaration_tag,
xml_string,
xml_attribute,
xml_comment,
xml_parse_error
};
// callback(int type, char const* name, char const* val)
// str2 is only used for attributes. name is element or attribute
// name and val is attribute value
template <class CallbackType>
void xml_parse(char* p, char* end, CallbackType callback)
{
for(;p != end; ++p)
{
char const* start = p;
char const* val_start = 0;
int token;
// look for tag start
for(; *p != '<' && p != end; ++p);
if (p != start)
{
if (p != end)
{
assert(*p == '<');
*p = 0;
}
token = xml_string;
callback(token, start, val_start);
if (p != end) *p = '<';
}
if (p == end) break;
// skip '<'
++p;
// parse the name of the tag.
for (start = p; p != end && *p != '>' && !std::isspace(*p); ++p);
char* tag_name_end = p;
// skip the attributes for now
for (; p != end && *p != '>'; ++p);
// parse error
if (p == end)
{
token = xml_parse_error;
start = "unexpected end of file";
callback(token, start, val_start);
break;
}
assert(*p == '>');
// save the character that terminated the tag name
// it could be both '>' and ' '.
char save = *tag_name_end;
*tag_name_end = 0;
char* tag_end = p;
if (*start == '/')
{
++start;
token = xml_end_tag;
callback(token, start, val_start);
}
else if (*(p-1) == '/')
{
*(p-1) = 0;
token = xml_empty_tag;
callback(token, start, val_start);
*(p-1) = '/';
tag_end = p - 1;
}
else if (*start == '?' && *(p-1) == '?')
{
*(p-1) = 0;
++start;
token = xml_declaration_tag;
callback(token, start, val_start);
*(p-1) = '?';
tag_end = p - 1;
}
else if (start + 5 < p && memcmp(start, "!--", 3) == 0 && memcmp(p-2, "--", 2) == 0)
{
start += 3;
*(p-2) = 0;
token = xml_comment;
callback(token, start, val_start);
*(p-2) = '-';
tag_end = p - 2;
}
else
{
token = xml_start_tag;
callback(token, start, val_start);
}
*tag_name_end = save;
// parse attributes
for (char* i = tag_name_end; i < tag_end; ++i)
{
// find start of attribute name
for (; i != tag_end && std::isspace(*i); ++i);
if (i == tag_end) break;
start = i;
// find end of attribute name
for (; i != tag_end && *i != '=' && !std::isspace(*i); ++i);
char* name_end = i;
// look for equality sign
for (; i != tag_end && *i != '='; ++i);
if (i == tag_end)
{
token = xml_parse_error;
val_start = 0;
start = "garbage inside element brackets";
callback(token, start, val_start);
break;
}
++i;
for (; i != tag_end && std::isspace(*i); ++i);
// check for parse error (values must be quoted)
if (i == tag_end || (*i != '\'' && *i != '\"'))
{
token = xml_parse_error;
val_start = 0;
start = "unquoted attribute value";
callback(token, start, val_start);
break;
}
char quote = *i;
++i;
val_start = i;
for (; i != tag_end && *i != quote; ++i);
// parse error (missing end quote)
if (i == tag_end)
{
token = xml_parse_error;
val_start = 0;
start = "missing end quote on attribute";
callback(token, start, val_start);
break;
}
save = *i;
*i = 0;
*name_end = 0;
token = xml_attribute;
callback(token, start, val_start);
*name_end = '=';
*i = save;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
* File: toolChecker.cpp
* Author: Matthew Rollings
* Date: 19/06/2015
*
* Description : Root checking JNI NDK code
*
****************************************************************************/
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>> System Includes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
// Android headers
#include <jni.h>
#include <android/log.h>
// String / file headers
#include <string.h>
#include <stdio.h>
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>>> User Includes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
#include "toolChecker.h"
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>>> Constant Macros <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
// LOGCAT
/* Set to 1 to enable debug log traces. */
#define DEBUG 1
#define LOG_TAG "RootBeer"
#define LOGD(...) if (DEBUG) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__);
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__);
const char *paths[8] = {
"/sbin/su",
"/system/bin/su",
"/system/xbin/su",
"/data/local/xbin/su",
"/data/local/bin/su",
"/system/sd/xbin/su",
"/system/bin/failsafe/su",
"/data/local/su"
};
/*****************************************************************************
* Description: Checks if a file exists
*
* Parameters: fname - filename to check
*
* Return value: 0 - non-existant / not visible, 1 - exists
*
*****************************************************************************/
int exists(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
LOGD("LOOKING FOR BINRARY: %s PRESENT!!!",fname);
fclose(file);
return 1;
}
LOGD("LOOKING FOR BINRARY: %s Absent :(",fname);
return 0;
}
/*****************************************************************************
* Description: Checks for root binaries
*
* Parameters: env - Java environment pointer
* thiz - javaobject
*
* Return value: int number of su binaries found
*
*****************************************************************************/
int Java_com_scottyab_rootbeer_RootBeerNative_checkForRoot( JNIEnv* env, jobject thiz )
{
int binariesFound = 0;
for(int i = 0 ; i < 8; i ++){
binariesFound+=exists(paths[i]);
}
return binariesFound>0;
}
<commit_msg>updated su locations to check in native lib<commit_after>/****************************************************************************
* File: toolChecker.cpp
* Author: Matthew Rollings
* Date: 19/06/2015
*
* Description : Root checking JNI NDK code
*
****************************************************************************/
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>> System Includes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
// Android headers
#include <jni.h>
#include <android/log.h>
// String / file headers
#include <string.h>
#include <stdio.h>
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>>> User Includes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
#include "toolChecker.h"
/****************************************************************************
*>>>>>>>>>>>>>>>>>>>>>>>>>> Constant Macros <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*
****************************************************************************/
// LOGCAT
/* Set to 1 to enable debug log traces. */
#define DEBUG 1
#define LOG_TAG "RootBeer"
#define LOGD(...) if (DEBUG) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__);
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__);
const char *paths[8] = {
"/data/local/",
"/data/local/bin/",
"/data/local/xbin/",
"/sbin/",
"/system/bin/",
"/system/bin/.ext/",
"/system/bin/failsafe/",
"/system/sd/xbin/",
"/system/usr/we-need-root/",
"/system/xbin/"
};
/*****************************************************************************
* Description: Checks if a file exists
*
* Parameters: fname - filename to check
*
* Return value: 0 - non-existant / not visible, 1 - exists
*
*****************************************************************************/
int exists(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
LOGD("LOOKING FOR BINRARY: %s PRESENT!!!",fname);
fclose(file);
return 1;
}
LOGD("LOOKING FOR BINRARY: %s Absent :(",fname);
return 0;
}
/*****************************************************************************
* Description: Checks for root binaries
*
* Parameters: env - Java environment pointer
* thiz - javaobject
*
* Return value: int number of su binaries found
*
*****************************************************************************/
int Java_com_scottyab_rootbeer_RootBeerNative_checkForRoot( JNIEnv* env, jobject thiz )
{
int binariesFound = 0;
for(int i = 0 ; i < 8; i ++){
binariesFound+=exists(paths[i]);
}
return binariesFound>0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware 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.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QQueue>
#include <QVarLengthArray>
#include <QDebug>
// CTK includes
#include "ctkDependencyGraph.h"
// STD includes
#include <iostream>
#define MAXV 100
#define MAXDEGREE 50
//----------------------------------------------------------------------------
class ctkDependencyGraph::ctkInternal
{
public:
ctkInternal(ctkDependencyGraph* p);
/// Compute indegree
void computeOutdegrees(QVarLengthArray<int, MAXV>& computedOutdegrees);
/// Traverse tree using Depth-first_search
void traverseUsingDFS(int v);
/// Called each time an edge is visited
void processEdge(int from, int to);
/// Called each time a vertex is processed
void processVertex(int v);
/// Retrieve the path between two vertices
void findPathDFS(int from, int to, QList<int>& path);
/// Recursive function used by findPaths to retrieve the path between two vertices
void findPathsRec(int from, int to, QList<int>* path, QList<QList<int>* >& paths);
void setEdge(int vertice, int degree, int value);
int edge(int vertice, int degree);
void verticesWithIndegree(int indegree, QList<int>& list);
/// See http://en.wikipedia.org/wiki/Adjacency_list
QVarLengthArray<QVarLengthArray<int,MAXDEGREE>*, MAXV+1> Edges;
QVarLengthArray<int, MAXV+1> OutDegree;
QVarLengthArray<int, MAXV+1> InDegree;
int NVertices;
int NEdges;
/// Structure used by DFS
/// See http://en.wikipedia.org/wiki/Depth-first_search
QVarLengthArray<bool, MAXV> Processed; // processed vertices
QVarLengthArray<bool, MAXV> Discovered; // discovered vertices
QVarLengthArray<int, MAXV> Parent; // relation discovered
bool Abort; // Flag indicating if traverse should be aborted
bool Verbose;
bool CycleDetected;
int CycleOrigin;
int CycleEnd;
QList<int> ListOfEdgeToExclude;
/// Pointer to the public API
ctkDependencyGraph* P;
};
//----------------------------------------------------------------------------
// ctkInternal methods
//----------------------------------------------------------------------------
ctkDependencyGraph::ctkInternal::ctkInternal(ctkDependencyGraph* p)
{
Q_ASSERT(p);
this->P = p;
this->NVertices = 0;
this->NEdges = 0;
this->Abort = false;
this->Verbose = false;
this->CycleDetected = false;
this->CycleOrigin = 0;
this->CycleEnd = 0;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::computeOutdegrees(QVarLengthArray<int, MAXV>& computedOutdegrees)
{
for (int i=1; i <= this->NVertices; i++)
{
computedOutdegrees[i] = 0;
}
for (int i=1; i <= this->NVertices; i++)
{
for (int j=0; j < this->OutDegree[i]; j++)
{
computedOutdegrees[ this->edge(i,j) ] ++;
}
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::traverseUsingDFS(int v)
{
// allow for search termination
if (this->Abort)
{
return;
}
this->Discovered[v] = true;
this->processVertex(v);
int y; // successor vertex
for (int i=0; i<this->OutDegree[v]; i++)
{
y = this->edge(v, i);
if (this->P->shouldExcludeEdge(this->edge(v, i)) == false)
{
if (this->Discovered[y] == false)
{
this->Parent[y] = v;
this->traverseUsingDFS(y);
}
else
{
if (this->Processed[y] == false)
{
this->processEdge(v,y);
}
}
}
if (this->Abort)
{
return;
}
}
this->Processed[v] = true;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::processEdge(int from, int to)
{
if (this->Discovered[to] == true)
{
this->CycleDetected = true;
this->CycleOrigin = to;
this->CycleEnd = from;
if (this->Verbose)
{
QList<int> path;
this->findPathDFS(from, to, path);
qWarning() << "Cycle detected from " << to << " to " << from;
qWarning() << " " << path;
path.clear();
this->findPathDFS(to, from, path);
qWarning() << " " << path;
}
this->Abort = true;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::processVertex(int v)
{
if (this->Verbose)
{
qDebug() << "processed vertex " << v;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::setEdge(int vertice, int degree, int value)
{
Q_ASSERT(vertice <= this->NVertices);
Q_ASSERT(degree < MAXDEGREE);
(*this->Edges[vertice])[degree] = value;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::ctkInternal::edge(int vertice, int degree)
{
Q_ASSERT(vertice <= this->NVertices);
Q_ASSERT(degree < MAXDEGREE);
return (*this->Edges[vertice])[degree];
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::findPathDFS(int from, int to, QList<int>& path)
{
if ((from == to) || (to == -1))
{
path << from;
}
else
{
this->findPathDFS(from, this->Parent[to], path);
path << to;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::findPathsRec(
int from, int to, QList<int>* path, QList<QList<int>* >& paths)
{
if (from == to)
{
return;
}
QList<int> branch(*path);
int child = from;
for (int j=0; j < this->OutDegree[child]; j++)
{
if (j == 0)
{
int parent = this->edge(child, j);
*path << parent;
this->findPathsRec(parent, to, path, paths);
}
else
{
int parent = this->edge(child, j);
// Copy path and add it to the list
QList<int>* pathCopy = new QList<int>(branch);
paths << pathCopy;
*pathCopy << parent;
this->findPathsRec(parent, to, pathCopy, paths);
}
}
}
void ctkDependencyGraph::ctkInternal::verticesWithIndegree(int indegree, QList<int>& list)
{
Q_ASSERT(indegree >= 0);
for (int i=1; i <= this->NVertices; i++)
{
if (this->InDegree[i] == indegree)
{
list << i;
}
}
}
//----------------------------------------------------------------------------
// ctkDependencyGraph methods
//----------------------------------------------------------------------------
ctkDependencyGraph::ctkDependencyGraph(int nvertices)
{
this->Internal = new ctkInternal(this);
this->Internal->NVertices = nvertices;
// Resize internal array
this->Internal->Processed.resize(nvertices + 1);
this->Internal->Discovered.resize(nvertices + 1);
this->Internal->Parent.resize(nvertices + 1);
this->Internal->Edges.resize(nvertices + 1);
this->Internal->OutDegree.resize(nvertices + 1);
this->Internal->InDegree.resize(nvertices + 1);
for (int i=1; i <= nvertices; i++)
{
this->Internal->OutDegree[i] = 0;
this->Internal->InDegree[i] = 0;
}
// initialize Edge adjacency list
for (int i=0; i <= nvertices; i++)
{
this->Internal->Edges[i] = new QVarLengthArray<int, MAXDEGREE>();
this->Internal->Edges[i]->resize(MAXDEGREE);
}
// initialize search
for (int i=1; i <= nvertices; i++)
{
this->Internal->Processed[i] = false;
this->Internal->Discovered[i] = false;
this->Internal->Parent[i] = -1;
}
}
//----------------------------------------------------------------------------
ctkDependencyGraph::~ctkDependencyGraph()
{
// Clean memory
for (int i=0; i <= this->Internal->NVertices; i++)
{
delete this->Internal->Edges[i];
}
delete this->Internal;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::printAdditionalInfo()
{
qDebug() << "ctkDependencyGraph (" << this << ")" << endl
<< " NVertices:" << this->numberOfVertices() << endl
<< " NEdges:" << this->numberOfEdges() << endl
<< " Abort:" << this->Internal->Abort;
qDebug() << " [Processed]";
for(int i=1; i < this->Internal->Processed.size(); i++)
{
qDebug() << i << "->" << this->Internal->Processed[i];
}
qDebug() << " [Discovered]";
for(int i=1; i < this->Internal->Discovered.size(); i++)
{
qDebug() << i << "->" << this->Internal->Discovered[i];
}
qDebug() << " [Parent]";
for(int i=1; i < this->Internal->Parent.size(); i++)
{
qDebug() << i << "->" << this->Internal->Parent[i];
}
qDebug() << " [Graph]";
this->printGraph();
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::printGraph()
{
for(int i=1; i <= this->Internal->NVertices; i++)
{
std::cout << i << ":";
for (int j=0; j < this->Internal->OutDegree[i]; j++)
{
std::cout << " " << this->Internal->edge(i, j);
}
std::cout << std::endl;
}
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::numberOfVertices()
{
return this->Internal->NVertices;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::numberOfEdges()
{
return this->Internal->NEdges;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::setVerbose(bool verbose)
{
this->Internal->Verbose = verbose;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::setEdgeListToExclude(const QList<int>& list)
{
this->Internal->ListOfEdgeToExclude = list;
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::shouldExcludeEdge(int edge)
{
return this->Internal->ListOfEdgeToExclude.contains(edge);
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::checkForCycle()
{
if (this->Internal->NEdges > 0)
{
// get a valid vertice Id
int verticeId = 1;
this->Internal->traverseUsingDFS(verticeId);
}
return this->cycleDetected();
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::cycleDetected()
{
return this->Internal->CycleDetected;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::cycleOrigin()
{
return this->Internal->CycleOrigin;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::cycleEnd()
{
return this->Internal->CycleEnd;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::insertEdge(int from, int to)
{
Q_ASSERT(from > 0 && from <= this->Internal->NVertices);
Q_ASSERT(to > 0 && to <= this->Internal->NVertices);
// resize if needed
int capacity = this->Internal->Edges[from]->capacity();
if (this->Internal->OutDegree[from] > capacity)
{
this->Internal->Edges[from]->resize(capacity + capacity * 0.3);
}
this->Internal->setEdge(from, this->Internal->OutDegree[from], to);
this->Internal->OutDegree[from]++;
this->Internal->InDegree[to]++;
this->Internal->NEdges++;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::findPaths(int from, int to, QList<QList<int>* >& paths)
{
QList<int>* path = new QList<int>;
*path << from;
paths << path;
this->Internal->findPathsRec(from, to, path, paths);
QList<int> pathToRemove;
// Remove list no ending with the requested element
int i = 0;
while (!paths.isEmpty() && i < paths.size())
{
QList<int>* p = paths[i];
Q_ASSERT(p);
if (p->last() != to)
{
paths.removeAt(i);
delete p;
}
else
{
i++;
}
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::findPath(int from, int to, QList<int>& path)
{
int child = from;
int parent = this->Internal->edge(child, 0);
path << child;
while (parent > 0)
{
path << parent;
if (parent == to)
{
break;
}
child = parent;
parent = this->Internal->edge(child, 0);
}
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::topologicalSort(QList<int>& sorted)
{
QVarLengthArray<int, MAXV> outdegree; // outdegree of each vertex
QQueue<int> zeroout; // vertices of outdegree 0
int x, y; // current and next vertex
outdegree.resize(this->Internal->NVertices + 1);
// resize if needed
if (this->Internal->NVertices > MAXV)
{
outdegree.resize(this->Internal->NVertices);
}
this->Internal->computeOutdegrees(outdegree);
for (int i=1; i <= this->Internal->NVertices; i++)
{
if (outdegree[i] == 0)
{
zeroout.enqueue(i);
}
}
int j=0;
while (zeroout.empty() == false)
{
j = j+1;
x = zeroout.dequeue();
sorted << x;
for (int i=0; i < this->Internal->OutDegree[x]; i++)
{
y = this->Internal->edge(x, i);
outdegree[y] --;
if (outdegree[y] == 0)
{
zeroout.enqueue(y);
}
}
}
if (j != this->Internal->NVertices)
{
return false;
}
return true;
}
void ctkDependencyGraph::sourceVertices(QList<int>& sources)
{
this->Internal->verticesWithIndegree(0, sources);
}
<commit_msg>ENH: DependencyGraph: Set the parent even in the case when a vertex has already been discovered. In the case of a cycle, this allows for correct paths for diagnosing the problem. Example:<commit_after>/*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware 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.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QQueue>
#include <QVarLengthArray>
#include <QDebug>
// CTK includes
#include "ctkDependencyGraph.h"
// STD includes
#include <iostream>
#define MAXV 100
#define MAXDEGREE 50
//----------------------------------------------------------------------------
class ctkDependencyGraph::ctkInternal
{
public:
ctkInternal(ctkDependencyGraph* p);
/// Compute indegree
void computeOutdegrees(QVarLengthArray<int, MAXV>& computedOutdegrees);
/// Traverse tree using Depth-first_search
void traverseUsingDFS(int v);
/// Called each time an edge is visited
void processEdge(int from, int to);
/// Called each time a vertex is processed
void processVertex(int v);
/// Retrieve the path between two vertices
void findPathDFS(int from, int to, QList<int>& path);
/// Recursive function used by findPaths to retrieve the path between two vertices
void findPathsRec(int from, int to, QList<int>* path, QList<QList<int>* >& paths);
void setEdge(int vertice, int degree, int value);
int edge(int vertice, int degree);
void verticesWithIndegree(int indegree, QList<int>& list);
/// See http://en.wikipedia.org/wiki/Adjacency_list
QVarLengthArray<QVarLengthArray<int,MAXDEGREE>*, MAXV+1> Edges;
QVarLengthArray<int, MAXV+1> OutDegree;
QVarLengthArray<int, MAXV+1> InDegree;
int NVertices;
int NEdges;
/// Structure used by DFS
/// See http://en.wikipedia.org/wiki/Depth-first_search
QVarLengthArray<bool, MAXV> Processed; // processed vertices
QVarLengthArray<bool, MAXV> Discovered; // discovered vertices
QVarLengthArray<int, MAXV> Parent; // relation discovered
bool Abort; // Flag indicating if traverse should be aborted
bool Verbose;
bool CycleDetected;
int CycleOrigin;
int CycleEnd;
QList<int> ListOfEdgeToExclude;
/// Pointer to the public API
ctkDependencyGraph* P;
};
//----------------------------------------------------------------------------
// ctkInternal methods
//----------------------------------------------------------------------------
ctkDependencyGraph::ctkInternal::ctkInternal(ctkDependencyGraph* p)
{
Q_ASSERT(p);
this->P = p;
this->NVertices = 0;
this->NEdges = 0;
this->Abort = false;
this->Verbose = false;
this->CycleDetected = false;
this->CycleOrigin = 0;
this->CycleEnd = 0;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::computeOutdegrees(QVarLengthArray<int, MAXV>& computedOutdegrees)
{
for (int i=1; i <= this->NVertices; i++)
{
computedOutdegrees[i] = 0;
}
for (int i=1; i <= this->NVertices; i++)
{
for (int j=0; j < this->OutDegree[i]; j++)
{
computedOutdegrees[ this->edge(i,j) ] ++;
}
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::traverseUsingDFS(int v)
{
// allow for search termination
if (this->Abort)
{
return;
}
this->Discovered[v] = true;
this->processVertex(v);
int y; // successor vertex
for (int i=0; i<this->OutDegree[v]; i++)
{
y = this->edge(v, i);
if (this->P->shouldExcludeEdge(this->edge(v, i)) == false)
{
this->Parent[y] = v;
if (this->Discovered[y] == false)
{
this->traverseUsingDFS(y);
}
else
{
if (this->Processed[y] == false)
{
this->processEdge(v,y);
}
}
}
if (this->Abort)
{
return;
}
}
this->Processed[v] = true;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::processEdge(int from, int to)
{
if (this->Discovered[to] == true)
{
this->CycleDetected = true;
this->CycleOrigin = to;
this->CycleEnd = from;
if (this->Verbose)
{
QList<int> path;
this->findPathDFS(from, to, path);
qWarning() << "Cycle detected from " << to << " to " << from;
qWarning() << " " << path;
path.clear();
this->findPathDFS(to, from, path);
qWarning() << " " << path;
}
this->Abort = true;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::processVertex(int v)
{
if (this->Verbose)
{
qDebug() << "processed vertex " << v;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::setEdge(int vertice, int degree, int value)
{
Q_ASSERT(vertice <= this->NVertices);
Q_ASSERT(degree < MAXDEGREE);
(*this->Edges[vertice])[degree] = value;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::ctkInternal::edge(int vertice, int degree)
{
Q_ASSERT(vertice <= this->NVertices);
Q_ASSERT(degree < MAXDEGREE);
return (*this->Edges[vertice])[degree];
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::findPathDFS(int from, int to, QList<int>& path)
{
if ((from == to) || (to == -1))
{
path << from;
}
else
{
this->findPathDFS(from, this->Parent[to], path);
path << to;
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::ctkInternal::findPathsRec(
int from, int to, QList<int>* path, QList<QList<int>* >& paths)
{
if (from == to)
{
return;
}
QList<int> branch(*path);
int child = from;
for (int j=0; j < this->OutDegree[child]; j++)
{
if (j == 0)
{
int parent = this->edge(child, j);
*path << parent;
this->findPathsRec(parent, to, path, paths);
}
else
{
int parent = this->edge(child, j);
// Copy path and add it to the list
QList<int>* pathCopy = new QList<int>(branch);
paths << pathCopy;
*pathCopy << parent;
this->findPathsRec(parent, to, pathCopy, paths);
}
}
}
void ctkDependencyGraph::ctkInternal::verticesWithIndegree(int indegree, QList<int>& list)
{
Q_ASSERT(indegree >= 0);
for (int i=1; i <= this->NVertices; i++)
{
if (this->InDegree[i] == indegree)
{
list << i;
}
}
}
//----------------------------------------------------------------------------
// ctkDependencyGraph methods
//----------------------------------------------------------------------------
ctkDependencyGraph::ctkDependencyGraph(int nvertices)
{
this->Internal = new ctkInternal(this);
this->Internal->NVertices = nvertices;
// Resize internal array
this->Internal->Processed.resize(nvertices + 1);
this->Internal->Discovered.resize(nvertices + 1);
this->Internal->Parent.resize(nvertices + 1);
this->Internal->Edges.resize(nvertices + 1);
this->Internal->OutDegree.resize(nvertices + 1);
this->Internal->InDegree.resize(nvertices + 1);
for (int i=1; i <= nvertices; i++)
{
this->Internal->OutDegree[i] = 0;
this->Internal->InDegree[i] = 0;
}
// initialize Edge adjacency list
for (int i=0; i <= nvertices; i++)
{
this->Internal->Edges[i] = new QVarLengthArray<int, MAXDEGREE>();
this->Internal->Edges[i]->resize(MAXDEGREE);
}
// initialize search
for (int i=1; i <= nvertices; i++)
{
this->Internal->Processed[i] = false;
this->Internal->Discovered[i] = false;
this->Internal->Parent[i] = -1;
}
}
//----------------------------------------------------------------------------
ctkDependencyGraph::~ctkDependencyGraph()
{
// Clean memory
for (int i=0; i <= this->Internal->NVertices; i++)
{
delete this->Internal->Edges[i];
}
delete this->Internal;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::printAdditionalInfo()
{
qDebug() << "ctkDependencyGraph (" << this << ")" << endl
<< " NVertices:" << this->numberOfVertices() << endl
<< " NEdges:" << this->numberOfEdges() << endl
<< " Abort:" << this->Internal->Abort;
qDebug() << " [Processed]";
for(int i=1; i < this->Internal->Processed.size(); i++)
{
qDebug() << i << "->" << this->Internal->Processed[i];
}
qDebug() << " [Discovered]";
for(int i=1; i < this->Internal->Discovered.size(); i++)
{
qDebug() << i << "->" << this->Internal->Discovered[i];
}
qDebug() << " [Parent]";
for(int i=1; i < this->Internal->Parent.size(); i++)
{
qDebug() << i << "->" << this->Internal->Parent[i];
}
qDebug() << " [Graph]";
this->printGraph();
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::printGraph()
{
for(int i=1; i <= this->Internal->NVertices; i++)
{
std::cout << i << ":";
for (int j=0; j < this->Internal->OutDegree[i]; j++)
{
std::cout << " " << this->Internal->edge(i, j);
}
std::cout << std::endl;
}
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::numberOfVertices()
{
return this->Internal->NVertices;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::numberOfEdges()
{
return this->Internal->NEdges;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::setVerbose(bool verbose)
{
this->Internal->Verbose = verbose;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::setEdgeListToExclude(const QList<int>& list)
{
this->Internal->ListOfEdgeToExclude = list;
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::shouldExcludeEdge(int edge)
{
return this->Internal->ListOfEdgeToExclude.contains(edge);
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::checkForCycle()
{
if (this->Internal->NEdges > 0)
{
// get a valid vertice Id
int verticeId = 1;
this->Internal->traverseUsingDFS(verticeId);
}
return this->cycleDetected();
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::cycleDetected()
{
return this->Internal->CycleDetected;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::cycleOrigin()
{
return this->Internal->CycleOrigin;
}
//----------------------------------------------------------------------------
int ctkDependencyGraph::cycleEnd()
{
return this->Internal->CycleEnd;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::insertEdge(int from, int to)
{
Q_ASSERT(from > 0 && from <= this->Internal->NVertices);
Q_ASSERT(to > 0 && to <= this->Internal->NVertices);
// resize if needed
int capacity = this->Internal->Edges[from]->capacity();
if (this->Internal->OutDegree[from] > capacity)
{
this->Internal->Edges[from]->resize(capacity + capacity * 0.3);
}
this->Internal->setEdge(from, this->Internal->OutDegree[from], to);
this->Internal->OutDegree[from]++;
this->Internal->InDegree[to]++;
this->Internal->NEdges++;
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::findPaths(int from, int to, QList<QList<int>* >& paths)
{
QList<int>* path = new QList<int>;
*path << from;
paths << path;
this->Internal->findPathsRec(from, to, path, paths);
QList<int> pathToRemove;
// Remove list no ending with the requested element
int i = 0;
while (!paths.isEmpty() && i < paths.size())
{
QList<int>* p = paths[i];
Q_ASSERT(p);
if (p->last() != to)
{
paths.removeAt(i);
delete p;
}
else
{
i++;
}
}
}
//----------------------------------------------------------------------------
void ctkDependencyGraph::findPath(int from, int to, QList<int>& path)
{
int child = from;
int parent = this->Internal->edge(child, 0);
path << child;
while (parent > 0)
{
path << parent;
if (parent == to)
{
break;
}
child = parent;
parent = this->Internal->edge(child, 0);
}
}
//----------------------------------------------------------------------------
bool ctkDependencyGraph::topologicalSort(QList<int>& sorted)
{
QVarLengthArray<int, MAXV> outdegree; // outdegree of each vertex
QQueue<int> zeroout; // vertices of outdegree 0
int x, y; // current and next vertex
outdegree.resize(this->Internal->NVertices + 1);
// resize if needed
if (this->Internal->NVertices > MAXV)
{
outdegree.resize(this->Internal->NVertices);
}
this->Internal->computeOutdegrees(outdegree);
for (int i=1; i <= this->Internal->NVertices; i++)
{
if (outdegree[i] == 0)
{
zeroout.enqueue(i);
}
}
int j=0;
while (zeroout.empty() == false)
{
j = j+1;
x = zeroout.dequeue();
sorted << x;
for (int i=0; i < this->Internal->OutDegree[x]; i++)
{
y = this->Internal->edge(x, i);
outdegree[y] --;
if (outdegree[y] == 0)
{
zeroout.enqueue(y);
}
}
}
if (j != this->Internal->NVertices)
{
return false;
}
return true;
}
void ctkDependencyGraph::sourceVertices(QList<int>& sources)
{
this->Internal->verticesWithIndegree(0, sources);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015-present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <hip/hip_runtime.h>
#define CHECK(cmd) \
{\
hipError_t error = cmd;\
if (error != hipSuccess) { \
fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), error,__FILE__, __LINE__); \
exit(EXIT_FAILURE);\
}\
}
/*
* Square each element in the array A and write to array C.
*/
template <typename T>
__global__ void
vector_square(T *C_d, T *A_d, size_t N)
{
size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
size_t stride = blockDim.x * gridDim.x ;
for (size_t i=offset; i<N; i+=stride) {
C_d[i] = A_d[i] * A_d[i];
}
}
int main(int argc, char *argv[])
{
float *A_d, *C_d;
float *A_h, *C_h;
size_t N = 1000000;
size_t Nbytes = N * sizeof(float);
hipDeviceProp_t props;
CHECK(hipGetDeviceProperties(&props, 0/*deviceID*/));
printf ("info: running on device %s\n", props.name);
printf ("info: allocate host mem (%6.2f MB)\n", 2*Nbytes/1024.0/1024.0);
A_h = (float*)malloc(Nbytes);
CHECK(A_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
C_h = (float*)malloc(Nbytes);
CHECK(C_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
// Fill with Phi + i
for (size_t i=0; i<N; i++)
{
A_h[i] = 1.618f + i;
}
printf ("info: allocate device mem (%6.2f MB)\n", 2*Nbytes/1024.0/1024.0);
CHECK(hipMalloc(&A_d, Nbytes));
CHECK(hipMalloc(&C_d, Nbytes));
printf ("info: copy Host2Device\n");
CHECK ( hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
const unsigned blocks = 512;
const unsigned threadsPerBlock = 256;
printf ("info: launch 'vector_square' kernel\n");
hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0, 0, C_d, A_d, N);
printf ("info: copy Device2Host\n");
CHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));
printf ("info: check result\n");
for (size_t i=0; i<N; i++) {
if (C_h[i] != A_h[i] * A_h[i]) {
CHECK(hipErrorUnknown);
}
}
printf ("PASSED!\n");
}
<commit_msg>remove unnecessary file<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <mutex>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
// TODO(all) implement
/**
const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
FLAGS_localization_topic};
rosbag::Bag bag;
try {
bag.open(filename, rosbag::bagmode::Read);
} catch (const rosbag::BagIOException& e) {
AERROR << "BagIOException when open bag: " << filename
<< " Exception: " << e.what();
bag.close();
return;
} catch (...) {
AERROR << "Failed to open bag: " << filename;
bag.close();
return;
}
rosbag::View view(bag, rosbag::TopicQuery(topics));
for (auto it = view.begin(); it != view.end(); ++it) {
if (it->getTopic() == FLAGS_localization_topic) {
OnLocalization(*(it->instantiate<LocalizationEstimate>()));
} else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
RunOnce(*(it->instantiate<PerceptionObstacles>()));
}
}
bag.close();
**/
}
bool PredictionComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
return true;
}
Status PredictionComponent::Start() { return Status::OK(); }
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
FeatureOutput::Close();
}
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(adc_trajectory_container);
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization,
const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_
> FLAGS_prediction_test_duration)) {
AINFO << "Prediction finished running in test mode";
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
double start_timestamp = Clock::NowInSeconds();
OnLocalization(*localization);
OnPlanning(*adc_trajectory);
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(*perception_obstacles);
ADEBUG << "Received a perception message ["
<< perception_obstacles->ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(*perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return true;
}
// Make predictions
PredictorManager::Instance()->Run(*perception_obstacles);
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(start_timestamp);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles->header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles->header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles->header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return false;
}
}
}
}
}
prediction_writer_->Write(prediction_obstacles);
return true;
}
Status PredictionComponent::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: initialize prediction writer to run loops<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <mutex>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
// TODO(all) implement
/**
const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
FLAGS_localization_topic};
rosbag::Bag bag;
try {
bag.open(filename, rosbag::bagmode::Read);
} catch (const rosbag::BagIOException& e) {
AERROR << "BagIOException when open bag: " << filename
<< " Exception: " << e.what();
bag.close();
return;
} catch (...) {
AERROR << "Failed to open bag: " << filename;
bag.close();
return;
}
rosbag::View view(bag, rosbag::TopicQuery(topics));
for (auto it = view.begin(); it != view.end(); ++it) {
if (it->getTopic() == FLAGS_localization_topic) {
OnLocalization(*(it->instantiate<LocalizationEstimate>()));
} else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
RunOnce(*(it->instantiate<PerceptionObstacles>()));
}
}
bag.close();
**/
}
bool PredictionComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
prediction_writer_ =
node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
return true;
}
Status PredictionComponent::Start() { return Status::OK(); }
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
FeatureOutput::Close();
}
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(adc_trajectory_container);
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization,
const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_
> FLAGS_prediction_test_duration)) {
ADEBUG << "Prediction finished running in test mode";
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
double start_timestamp = Clock::NowInSeconds();
OnLocalization(*localization);
OnPlanning(*adc_trajectory);
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(*perception_obstacles);
ADEBUG << "Received a perception message ["
<< perception_obstacles->ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(*perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return true;
}
// Make predictions
PredictorManager::Instance()->Run(*perception_obstacles);
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(start_timestamp);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles->header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles->header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles->header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return false;
}
}
}
}
}
prediction_writer_->Write(prediction_obstacles);
return true;
}
Status PredictionComponent::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"
namespace Halide {
using namespace Internal;
using std::string;
using std::vector;
RVar::operator Expr() const {
if (!min().defined() || !extent().defined()) {
user_error << "Use of undefined RDom dimension: " <<
(name().empty() ? "<unknown>" : name()) << "\n";
}
return Variable::make(Int(32), name(), domain());
}
Expr RVar::min() const {
if (_domain.defined()) {
return _var().min;
} else {
return undef<int>();
}
}
Expr RVar::extent() const {
if (_domain.defined()) {
return _var().extent;
} else {
return undef<int>();
}
}
const std::string &RVar::name() const {
if (_domain.defined()) {
return _var().var;
} else {
return _name;
}
}
template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
ReductionVariable *begin = &vars[0];
ReductionVariable *end = &vars[0];
for (int i = 0; i < N; i++) {
if (vars[i].min.defined()) {
end = &vars[i + 1];
}
}
vector<ReductionVariable> d(begin, end);
ReductionDomain dom(d);
return dom;
}
// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
static string var_names[] = { "x", "y", "z", "w" };
if (name == "") {
name = make_entity_name(this, "Halide::RDom", 'r');
}
const std::vector<ReductionVariable> &dom_vars = dom.domain();
RVar *vars[] = { &x, &y, &z, &w };
for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
if (i < dom_vars.size()) {
*(vars[i]) = RVar(dom, i);
} else {
*(vars[i]) = RVar(name + "." + var_names[i]);
}
}
}
RDom::RDom(ReductionDomain d) : dom(d) {
init_vars("");
}
// We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w.
RDom::RDom(Expr min, Expr extent, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min), cast<int>(extent) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
{ name + ".6$r", cast<int>(min6), cast<int>(extent6) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, Expr min7, Expr extent7,
string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
{ name + ".6$r", cast<int>(min6), cast<int>(extent6) },
{ name + ".7$r", cast<int>(min7), cast<int>(extent7) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Buffer b) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < b.dimensions(); i++) {
ReductionVariable var = {
b.name() + "." + var_names[i],
b.min(i),
b.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(b.name());
}
RDom::RDom(ImageParam p) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < p.dimensions(); i++) {
ReductionVariable var = {
p.name() + "." + var_names[i],
p.min(i),
p.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(p.name());
}
int RDom::dimensions() const {
return (int)dom.domain().size();
}
RVar RDom::operator[](int i) const {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
if (i < dimensions()) {
return RVar(dom, i);
}
user_error << "Reduction domain index out of bounds: " << i << "\n";
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to Expr.\n";
}
return Expr(x);
}
RDom::operator RVar() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to RVar.\n";
}
return x;
}
/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
return stream;
}
/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
stream << "RDom(\n";
for (int i = 0; i < dom.dimensions(); i++) {
stream << " " << dom[i] << "\n";
}
stream << ")\n";
return stream;
}
}
<commit_msg>Fixed indent mistake.<commit_after>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"
namespace Halide {
using namespace Internal;
using std::string;
using std::vector;
RVar::operator Expr() const {
if (!min().defined() || !extent().defined()) {
user_error << "Use of undefined RDom dimension: " <<
(name().empty() ? "<unknown>" : name()) << "\n";
}
return Variable::make(Int(32), name(), domain());
}
Expr RVar::min() const {
if (_domain.defined()) {
return _var().min;
} else {
return undef<int>();
}
}
Expr RVar::extent() const {
if (_domain.defined()) {
return _var().extent;
} else {
return undef<int>();
}
}
const std::string &RVar::name() const {
if (_domain.defined()) {
return _var().var;
} else {
return _name;
}
}
template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
ReductionVariable *begin = &vars[0];
ReductionVariable *end = &vars[0];
for (int i = 0; i < N; i++) {
if (vars[i].min.defined()) {
end = &vars[i + 1];
}
}
vector<ReductionVariable> d(begin, end);
ReductionDomain dom(d);
return dom;
}
// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
static string var_names[] = { "x", "y", "z", "w" };
if (name == "") {
name = make_entity_name(this, "Halide::RDom", 'r');
}
const std::vector<ReductionVariable> &dom_vars = dom.domain();
RVar *vars[] = { &x, &y, &z, &w };
for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
if (i < dom_vars.size()) {
*(vars[i]) = RVar(dom, i);
} else {
*(vars[i]) = RVar(name + "." + var_names[i]);
}
}
}
RDom::RDom(ReductionDomain d) : dom(d) {
init_vars("");
}
// We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w.
RDom::RDom(Expr min, Expr extent, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min), cast<int>(extent) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
{ name + ".6$r", cast<int>(min6), cast<int>(extent6) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3,
Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, Expr min7, Expr extent7,
string name) {
ReductionVariable vars[] = {
{ name + ".x$r", cast<int>(min0), cast<int>(extent0) },
{ name + ".y$r", cast<int>(min1), cast<int>(extent1) },
{ name + ".z$r", cast<int>(min2), cast<int>(extent2) },
{ name + ".w$r", cast<int>(min3), cast<int>(extent3) },
{ name + ".4$r", cast<int>(min4), cast<int>(extent4) },
{ name + ".5$r", cast<int>(min5), cast<int>(extent5) },
{ name + ".6$r", cast<int>(min6), cast<int>(extent6) },
{ name + ".7$r", cast<int>(min7), cast<int>(extent7) },
};
dom = build_domain(vars);
init_vars(name);
}
RDom::RDom(Buffer b) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < b.dimensions(); i++) {
ReductionVariable var = {
b.name() + "." + var_names[i],
b.min(i),
b.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(b.name());
}
RDom::RDom(ImageParam p) {
static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
std::vector<ReductionVariable> vars;
for (int i = 0; i < p.dimensions(); i++) {
ReductionVariable var = {
p.name() + "." + var_names[i],
p.min(i),
p.extent(i)
};
vars.push_back(var);
}
dom = ReductionDomain(vars);
init_vars(p.name());
}
int RDom::dimensions() const {
return (int)dom.domain().size();
}
RVar RDom::operator[](int i) const {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
if (i < dimensions()) {
return RVar(dom, i);
}
user_error << "Reduction domain index out of bounds: " << i << "\n";
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to Expr.\n";
}
return Expr(x);
}
RDom::operator RVar() const {
if (dimensions() != 1) {
user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
<< (*this) << "\n"
<< "Only single-dimensional RDoms can be cast to RVar.\n";
}
return x;
}
/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
return stream;
}
/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
stream << "RDom(\n";
for (int i = 0; i < dom.dimensions(); i++) {
stream << " " << dom[i] << "\n";
}
stream << ")\n";
return stream;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <Poco/Logger.h>
#include <Poco/Message.h>
#include <Poco/File.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/ServerApplication.h>
#include "server/MongooseServer.h"
#include "di/DependencyInjector.h"
#include "UIServerModule.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace BeeeOn;
#define DEFAULT_PORT 8000
#define SYSTEM_LOGGING_FILE "/etc/beeeon/ui-server/logging.ini"
#define SYSTEM_CONFIG_FILE "/etc/beeeon/ui-server/server.ini"
#define SYSTEM_SERVICES_FILE "/etc/beeeon/ui-server/services.xml"
static Option optConfig("config", "c",
"general configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optServices("services", "s",
"services configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogging("logging", "l",
"logging configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogLevel("log-level", "L",
"change startup log-level (trace, debug, [info],"
" notice, warn, error, fatal, trace)",
false,
"<level>",
true);
static Option optPort("port", "p",
"server port to listen on",
false,
"<port>",
true);
static Option optHelp("help", "h", "print help");
class Startup : public ServerApplication {
public:
Startup():
m_printHelp(false),
m_serverPort(DEFAULT_PORT)
{
}
protected:
/**
* Extend log-level parsing by shortcuts: info, warn, err, cirt.
*/
int parseLogLevel(const string &level)
{
if (icompare(level, "info") == 0)
return Message::PRIO_INFORMATION;
if (icompare(level, "warn") == 0)
return Message::PRIO_WARNING;
if (icompare(level, "err") == 0)
return Message::PRIO_ERROR;
if (icompare(level, "crit") == 0)
return Message::PRIO_CRITICAL;
return Logger::parseLevel(level);
}
void handleOption(const string &name, const string &value)
{
if (name == "services")
m_userServices = value;
if (name == "logging")
m_userLogging = value;
if (name == "config")
m_userConfig = value;
if (name == "help")
m_printHelp = true;
if (name == "log-level")
logger().setLevel(parseLogLevel(value));
if (name == "port")
m_serverPort = stoi(value);
if (m_printHelp)
stopOptionsProcessing();
Application::handleOption(name, value);
}
void loadAllConfiguration()
{
findAndLoadConfig();
findAndLoadLogging();
findAndLoadServices();
}
string parentPath(const File &file)
{
Path path(file.path());
return path.parent().toString();
}
bool readConfiguration(const File &file)
{
if (!file.exists()) {
logger().debug("configuration file "
+ file.path() + " not found");
return false;
}
loadConfiguration(file.path());
logger().notice("configuration file "
+ file.path() + " loaded");
return true;
}
void findAndLoadConfig()
{
File user(m_userConfig);
File system(SYSTEM_CONFIG_FILE);
config().setString("config.dir",
config().getString("application.dir"));
if (!m_userConfig.empty() && readConfiguration(user))
config().setString("config.dir", parentPath(user));
else if (readConfiguration(system))
config().setString("config.dir", parentPath(system));
else
logger().warning("no main configration found");
}
void findAndLoadLogging()
{
File user(m_userLogging);
File system(config().getString(
"ui.config.logging", SYSTEM_LOGGING_FILE));
if (!m_userLogging.empty() && readConfiguration(user))
return;
else if (!readConfiguration(system.path()))
logger().warning("no logging configuration found");
}
void findAndLoadServices()
{
File user(m_userServices);
File system(config().getString(
"ui.config.services", SYSTEM_SERVICES_FILE));
if (!m_userServices.empty() && readConfiguration(user))
return;
else if (!readConfiguration(system))
logger().warning("no services configuration found");
}
void initialize(Application &app)
{
if (m_printHelp)
return;
loadAllConfiguration();
Application::initialize(app);
}
void defineOptions(OptionSet &options)
{
options.addOption(optConfig);
options.addOption(optServices);
options.addOption(optLogging);
options.addOption(optLogLevel);
options.addOption(optPort);
options.addOption(optHelp);
Application::defineOptions(options);
}
int printHelp()
{
HelpFormatter help(options());
help.setCommand(config().getString("application.baseName"));
help.setUnixStyle(true);
help.setWidth(80);
help.setUsage("[-h] ...");
help.format(cout);
return EXIT_OK;
}
int main(const std::vector <std::string> &args)
{
if (m_printHelp)
return printHelp();
if (logger().debug())
ManifestSingleton::reportInfo(logger());
DependencyInjector injector(config().createView("services"));
UIServerModule *module = injector
.create<UIServerModule>("main");
module->createServer(m_serverPort);
module->server().start();
waitForTerminationRequest();
module->server().stop();
return EXIT_OK;
}
private:
bool m_printHelp;
unsigned int m_serverPort;
string m_userLogging;
string m_userConfig;
string m_userServices;
};
int main(int argc, char **argv)
{
Startup server;
server.setUnixOptions(true);
try {
return server.run(argc, argv);
} catch(Exception &e) {
cerr << e.displayText() << endl;
} catch(exception &e) {
cerr << e.what() << endl;
} catch(const char *s) {
cerr << s << endl;
}
}
<commit_msg>ui: convert signals to exception for error handling<commit_after>#include <iostream>
#include <Poco/Logger.h>
#include <Poco/Message.h>
#include <Poco/File.h>
#include <Poco/SignalHandler.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/ServerApplication.h>
#include "server/MongooseServer.h"
#include "di/DependencyInjector.h"
#include "UIServerModule.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace BeeeOn;
#define DEFAULT_PORT 8000
#define SYSTEM_LOGGING_FILE "/etc/beeeon/ui-server/logging.ini"
#define SYSTEM_CONFIG_FILE "/etc/beeeon/ui-server/server.ini"
#define SYSTEM_SERVICES_FILE "/etc/beeeon/ui-server/services.xml"
static Option optConfig("config", "c",
"general configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optServices("services", "s",
"services configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogging("logging", "l",
"logging configuration file to be used (xml, ini, properties)",
false,
"<file>",
true);
static Option optLogLevel("log-level", "L",
"change startup log-level (trace, debug, [info],"
" notice, warn, error, fatal, trace)",
false,
"<level>",
true);
static Option optPort("port", "p",
"server port to listen on",
false,
"<port>",
true);
static Option optHelp("help", "h", "print help");
class Startup : public ServerApplication {
public:
Startup():
m_printHelp(false),
m_serverPort(DEFAULT_PORT)
{
}
protected:
/**
* Extend log-level parsing by shortcuts: info, warn, err, cirt.
*/
int parseLogLevel(const string &level)
{
if (icompare(level, "info") == 0)
return Message::PRIO_INFORMATION;
if (icompare(level, "warn") == 0)
return Message::PRIO_WARNING;
if (icompare(level, "err") == 0)
return Message::PRIO_ERROR;
if (icompare(level, "crit") == 0)
return Message::PRIO_CRITICAL;
return Logger::parseLevel(level);
}
void handleOption(const string &name, const string &value)
{
if (name == "services")
m_userServices = value;
if (name == "logging")
m_userLogging = value;
if (name == "config")
m_userConfig = value;
if (name == "help")
m_printHelp = true;
if (name == "log-level")
logger().setLevel(parseLogLevel(value));
if (name == "port")
m_serverPort = stoi(value);
if (m_printHelp)
stopOptionsProcessing();
Application::handleOption(name, value);
}
void loadAllConfiguration()
{
findAndLoadConfig();
findAndLoadLogging();
findAndLoadServices();
}
string parentPath(const File &file)
{
Path path(file.path());
return path.parent().toString();
}
bool readConfiguration(const File &file)
{
if (!file.exists()) {
logger().debug("configuration file "
+ file.path() + " not found");
return false;
}
loadConfiguration(file.path());
logger().notice("configuration file "
+ file.path() + " loaded");
return true;
}
void findAndLoadConfig()
{
File user(m_userConfig);
File system(SYSTEM_CONFIG_FILE);
config().setString("config.dir",
config().getString("application.dir"));
if (!m_userConfig.empty() && readConfiguration(user))
config().setString("config.dir", parentPath(user));
else if (readConfiguration(system))
config().setString("config.dir", parentPath(system));
else
logger().warning("no main configration found");
}
void findAndLoadLogging()
{
File user(m_userLogging);
File system(config().getString(
"ui.config.logging", SYSTEM_LOGGING_FILE));
if (!m_userLogging.empty() && readConfiguration(user))
return;
else if (!readConfiguration(system.path()))
logger().warning("no logging configuration found");
}
void findAndLoadServices()
{
File user(m_userServices);
File system(config().getString(
"ui.config.services", SYSTEM_SERVICES_FILE));
if (!m_userServices.empty() && readConfiguration(user))
return;
else if (!readConfiguration(system))
logger().warning("no services configuration found");
}
void initialize(Application &app)
{
if (m_printHelp)
return;
loadAllConfiguration();
Application::initialize(app);
}
void defineOptions(OptionSet &options)
{
options.addOption(optConfig);
options.addOption(optServices);
options.addOption(optLogging);
options.addOption(optLogLevel);
options.addOption(optPort);
options.addOption(optHelp);
Application::defineOptions(options);
}
int printHelp()
{
HelpFormatter help(options());
help.setCommand(config().getString("application.baseName"));
help.setUnixStyle(true);
help.setWidth(80);
help.setUsage("[-h] ...");
help.format(cout);
return EXIT_OK;
}
int main(const std::vector <std::string> &args)
{
if (m_printHelp)
return printHelp();
if (logger().debug())
ManifestSingleton::reportInfo(logger());
DependencyInjector injector(config().createView("services"));
UIServerModule *module = injector
.create<UIServerModule>("main");
module->createServer(m_serverPort);
module->server().start();
waitForTerminationRequest();
module->server().stop();
return EXIT_OK;
}
private:
bool m_printHelp;
unsigned int m_serverPort;
string m_userLogging;
string m_userConfig;
string m_userServices;
};
int main(int argc, char **argv)
{
try {
poco_throw_on_signal;
Startup server;
server.setUnixOptions(true);
return server.run(argc, argv);
} catch(Exception &e) {
cerr << e.displayText() << endl;
} catch(exception &e) {
cerr << e.what() << endl;
} catch(const char *s) {
cerr << s << endl;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008 Kevin Krammer <kevin.krammer@gmx.at>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kresourceassistant.h"
#include <kresources/configwidget.h>
#include <kresources/factory.h>
#include <kresources/resource.h>
#include <kdebug.h>
#include <klineedit.h>
#include <kpagewidget.h>
#include <QCheckBox>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QStackedWidget>
class CompatibilityIntroductionLabel : public QWidget
{
public:
explicit CompatibilityIntroductionLabel( QWidget *parent )
: QWidget( parent )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
const QString introduction =
i18nc( "@info",
"<title>Introduction</title>"
"<para>This assistant will guide you through the necessary "
"steps to use a traditional KDE resource plugin to populate "
"a folder of your Akonadi personal information setup with data "
"otherwise not yet accesible through native Akonadi "
"resources.</para>"
"<para>The setup process consists of three steps:</para>"
"<para><list>"
"<item>Step 1: Selecting a plugin suitable for the kind of data "
"source you want to add</item>"
"<item>Step 2: Providing the selected plugin with information on "
"where to find and how to access the data</item>"
"<item>Step 3: Naming the resulting data source so you can easily "
"identify it in any application presenting you a choice of "
"which data to process</item></list></para>" );
QLabel *label = new QLabel( this );
label->setWordWrap( true );
label->setText( introduction );
mainLayout->addWidget( label );
mainLayout->addStretch();
}
};
class KResourceDescriptionLabel : public QWidget
{
public:
KResourceDescriptionLabel( const QString &type, const QString &desc, QWidget *parent)
: QWidget( parent ), mType( type )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
QLabel *label = new QLabel( desc, this );
label->setWordWrap( true );
mainLayout->addWidget( label );
mainLayout->addItem( new QSpacerItem( 0, 0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding ) );
}
public:
const QString mType;
};
class KResourceCreationWidget : public QWidget
{
public:
KResourceCreationWidget( const QString &familyName, KRES::Factory *factory, QWidget *parent )
: QWidget( parent ), mFamilyName( familyName ),
mFactory( factory ), mResource( 0 ), mPageWidget( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
mPageWidget = new KPageWidget( this );
mPageWidget->setFaceType( KPageView::Tree );
mainLayout->addWidget( mPageWidget );
mTypes = mFactory->typeNames();
int index = mTypes.indexOf( QLatin1String( "akonadi" ) );
if ( index != -1 )
mTypes.removeAt( index );
foreach ( const QString &type, mTypes ) {
QString description = mFactory->typeDescription( type );
if ( description.isEmpty() )
description = i18nc( "@info", "No description available" );
QWidget *label = new KResourceDescriptionLabel( type, description, mPageWidget );
mPageWidget->addPage( label, mFactory->typeName( type ) );
}
}
void createResource()
{
KResourceDescriptionLabel *label =
static_cast<KResourceDescriptionLabel*>( mPageWidget->currentPage()->widget() );
if ( mResource != 0 && mResource->type() == label->mType )
return;
delete mResource;
mResource = mFactory->resource( label->mType );
mResource->setResourceName( mFamilyName );
}
public:
QString mFamilyName;
QStringList mTypes;
KRES::Factory *mFactory;
KRES::Resource *mResource;
KPageWidget *mPageWidget;
};
class KResourcePluginConfigWidget : public QGroupBox
{
public:
KResourcePluginConfigWidget( const QString &type, KRES::Factory *factory, QWidget *parent)
: QGroupBox( parent ), mPluginWidget( 0 )
{
setTitle( i18nc( "@title:group", "%1 Plugin Settings", factory->typeName( type ) ) );
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mPluginWidget = factory->configWidget( type, this );
if ( mPluginWidget == 0 ) {
kError() << "No plugin configuration widget for resource type" << type;
QLabel *label = new QLabel( i18nc( "@info", "No plugin specific configuration available" ), this );
label->setAlignment( Qt::AlignHCenter );
mainLayout->addWidget( label );
} else
mainLayout->addWidget( mPluginWidget );
mainLayout->addStretch();
}
public:
KRES::ConfigWidget *mPluginWidget;
};
class KResourceConfigWidget : public QWidget
{
public:
KResourceConfigWidget( const QStringList &types, KRES::Factory *factory, QWidget *parent )
: QWidget( parent ), mStackWidget( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
mStackWidget = new QStackedWidget( this );
mainLayout->addWidget( mStackWidget );
foreach ( const QString &type, types ) {
KResourcePluginConfigWidget *configWidget =
new KResourcePluginConfigWidget( type, factory, mStackWidget );
mStackWidget->addWidget( configWidget );
mStackedWidgets.insert( type, configWidget );
connect( configWidget->mPluginWidget, SIGNAL( setReadOnly( bool ) ),
parent, SLOT( setReadOnly( bool ) ) );
}
}
void loadSettings( KRES::Resource *resource )
{
KResourcePluginConfigWidget *widget = mStackedWidgets[ resource->type() ];
Q_ASSERT( widget != 0 );
if ( widget->mPluginWidget != 0 )
widget->mPluginWidget->loadSettings( resource );
mStackWidget->setCurrentWidget( widget );
}
void saveSettings( KRES::Resource *resource )
{
KResourcePluginConfigWidget *widget = mStackedWidgets[ resource->type() ];
Q_ASSERT( widget != 0 );
if ( widget->mPluginWidget != 0 )
widget->mPluginWidget->saveSettings( resource );
}
public:
QStackedWidget *mStackWidget;
QMap<QString, KResourcePluginConfigWidget*> mStackedWidgets;
};
class KResourceFolderConfigWidget : public QWidget
{
public:
KResourceFolderConfigWidget( const QString &familyName, QWidget *parent )
: QWidget( parent ), mName( 0 ), mReadOnly( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
// TODO probably add Akonadi related options
const QString helpText =
i18nc( "@info",
"The settings on this page allow you to customize how the "
"data from the plugin will fit into your personal information "
"setup." );
QLabel *helpLabel = new QLabel( this );
helpLabel->setWordWrap( true );
helpLabel->setText( helpText );
mainLayout->addWidget( helpLabel );
QGroupBox *generalGroup = new QGroupBox( this );
QGridLayout *generalLayout = new QGridLayout( generalGroup );
generalLayout->setMargin( KDialog::marginHint() );
generalLayout->setSpacing( KDialog::spacingHint() );
generalGroup->setTitle( i18nc( "@title:group general resource settings",
"%1 Folder Settings",
familyName ) );
QLabel *nameLabel = new QLabel( i18nc( "@label resource name", "Name:" ),
generalGroup );
generalLayout->addWidget( nameLabel, 0, 0 );
mName = new KLineEdit( generalGroup );
generalLayout->addWidget( mName, 0, 1 );
mReadOnly = new QCheckBox( i18nc( "@option:check if resource is read-only",
"Read-only" ),
generalGroup );
generalLayout->addWidget( mReadOnly, 1, 0, 1, 2 );
mReadOnly->setChecked( false );
mainLayout->addWidget( generalGroup );
mainLayout->addStretch();
connect( mName, SIGNAL( textChanged( const QString& ) ),
parent, SLOT( slotNameChanged( const QString& ) ) );
}
public:
KLineEdit *mName;
QCheckBox *mReadOnly;
};
class KResourceAssistant::Private
{
public:
explicit Private( KResourceAssistant *parent )
: mParent( parent ), mFactory( 0 ), mCreationWidget( 0 ),
mConfigWidget( 0 ), mFolderWidget( 0 ),
mLastPage( 0 )
{
}
public:
KResourceAssistant *mParent;
KRES::Factory *mFactory;
KResourceCreationWidget *mCreationWidget;
KResourceConfigWidget *mConfigWidget;
KResourceFolderConfigWidget *mFolderWidget;
KPageWidgetItem *mLastPage;
public:
void setReadOnly( bool readOnly )
{
mFolderWidget->mReadOnly->setChecked( readOnly );
}
void slotNameChanged( const QString &text );
};
KResourceAssistant::KResourceAssistant( const QString& resourceFamily, QWidget *parent )
: KAssistantDialog( parent ), d( new Private( this ) )
{
// TODO they are most likely already defined somewhere
QMap<QString, QString> familyNames;
familyNames[ QLatin1String( "contact" ) ] =
i18nc( "@title user visible resource type", "Address Book" );
familyNames[ QLatin1String( "calendar" ) ] =
i18nc( "@title user visible resource type", "Calendar" );
const QString familyName = familyNames[ resourceFamily.toLower() ];
setModal( true );
setCaption( i18nc( "@title:window", "KDE Compatibility Assistant" ) );
QWidget *introPage = new CompatibilityIntroductionLabel( this );
addPage( introPage, QString() );
d->mFactory = KRES::Factory::self( resourceFamily.toLower() );
d->mCreationWidget = new KResourceCreationWidget( familyName, d->mFactory, this );
addPage( d->mCreationWidget, i18nc( "@title assistant dialog step",
"Step 1: Select a KDE resource plugin") );
d->mConfigWidget =
new KResourceConfigWidget( d->mCreationWidget->mTypes, d->mFactory, this );
addPage( d->mConfigWidget, i18nc( "@title assistant dialog step",
"Step 2: Configure the selected KDE resource plugin") );
d->mFolderWidget = new KResourceFolderConfigWidget( familyName, this );
d->mLastPage = addPage( d->mFolderWidget, i18nc( "@title assistant dialog step",
"Step 3: Choose target folder properties" ) );
}
KResourceAssistant::~KResourceAssistant()
{
delete d;
}
KRES::Resource *KResourceAssistant::resource()
{
return d->mCreationWidget->mResource;
}
void KResourceAssistant::back()
{
KPageWidgetItem *item = currentPage();
if ( item->widget() == d->mConfigWidget ) {
d->mConfigWidget->saveSettings( d->mCreationWidget->mResource );
}
KAssistantDialog::back();
}
void KResourceAssistant::next()
{
KPageWidgetItem *item = currentPage();
if ( item->widget() == d->mCreationWidget ) {
d->mCreationWidget->createResource();
d->mConfigWidget->loadSettings( d->mCreationWidget->mResource );
} else if ( item->widget() == d->mConfigWidget ) {
const QString resourceName = d->mCreationWidget->mResource->resourceName();
d->mFolderWidget->mName->setText( resourceName );
}
KAssistantDialog::next();
}
void KResourceAssistant::Private::slotNameChanged( const QString &text )
{
mParent->setValid( mLastPage, !text.isEmpty() );
mCreationWidget->mResource->setResourceName( text );
}
#include "kresourceassistant.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Do not attempt to connect signal when plugin does not have a config widget. Minor spelling fix on introduction page<commit_after>/*
Copyright (c) 2008 Kevin Krammer <kevin.krammer@gmx.at>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kresourceassistant.h"
#include <kresources/configwidget.h>
#include <kresources/factory.h>
#include <kresources/resource.h>
#include <kdebug.h>
#include <klineedit.h>
#include <kpagewidget.h>
#include <QCheckBox>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QStackedWidget>
class CompatibilityIntroductionLabel : public QWidget
{
public:
explicit CompatibilityIntroductionLabel( QWidget *parent )
: QWidget( parent )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
const QString introduction =
i18nc( "@info",
"<title>Introduction</title>"
"<para>This assistant will guide you through the necessary "
"steps to use a traditional KDE resource plugin to populate "
"a folder of your Akonadi personal information setup with data "
"otherwise not yet accessible through native Akonadi "
"resources.</para>"
"<para>The setup process consists of three steps:</para>"
"<para><list>"
"<item>Step 1: Selecting a plugin suitable for the kind of data "
"source you want to add</item>"
"<item>Step 2: Providing the selected plugin with information on "
"where to find and how to access the data</item>"
"<item>Step 3: Naming the resulting data source so you can easily "
"identify it in any application presenting you a choice of "
"which data to process</item></list></para>" );
QLabel *label = new QLabel( this );
label->setWordWrap( true );
label->setText( introduction );
mainLayout->addWidget( label );
mainLayout->addStretch();
}
};
class KResourceDescriptionLabel : public QWidget
{
public:
KResourceDescriptionLabel( const QString &type, const QString &desc, QWidget *parent)
: QWidget( parent ), mType( type )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
QLabel *label = new QLabel( desc, this );
label->setWordWrap( true );
mainLayout->addWidget( label );
mainLayout->addItem( new QSpacerItem( 0, 0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding ) );
}
public:
const QString mType;
};
class KResourceCreationWidget : public QWidget
{
public:
KResourceCreationWidget( const QString &familyName, KRES::Factory *factory, QWidget *parent )
: QWidget( parent ), mFamilyName( familyName ),
mFactory( factory ), mResource( 0 ), mPageWidget( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
mPageWidget = new KPageWidget( this );
mPageWidget->setFaceType( KPageView::Tree );
mainLayout->addWidget( mPageWidget );
mTypes = mFactory->typeNames();
int index = mTypes.indexOf( QLatin1String( "akonadi" ) );
if ( index != -1 )
mTypes.removeAt( index );
foreach ( const QString &type, mTypes ) {
QString description = mFactory->typeDescription( type );
if ( description.isEmpty() )
description = i18nc( "@info", "No description available" );
QWidget *label = new KResourceDescriptionLabel( type, description, mPageWidget );
mPageWidget->addPage( label, mFactory->typeName( type ) );
}
}
void createResource()
{
KResourceDescriptionLabel *label =
static_cast<KResourceDescriptionLabel*>( mPageWidget->currentPage()->widget() );
if ( mResource != 0 && mResource->type() == label->mType )
return;
delete mResource;
mResource = mFactory->resource( label->mType );
mResource->setResourceName( mFamilyName );
}
public:
QString mFamilyName;
QStringList mTypes;
KRES::Factory *mFactory;
KRES::Resource *mResource;
KPageWidget *mPageWidget;
};
class KResourcePluginConfigWidget : public QGroupBox
{
public:
KResourcePluginConfigWidget( const QString &type, KRES::Factory *factory, QWidget *parent)
: QGroupBox( parent ), mPluginWidget( 0 )
{
setTitle( i18nc( "@title:group", "%1 Plugin Settings", factory->typeName( type ) ) );
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mPluginWidget = factory->configWidget( type, this );
if ( mPluginWidget == 0 ) {
kError() << "No plugin configuration widget for resource type" << type;
QLabel *label = new QLabel( i18nc( "@info", "No plugin specific configuration available" ), this );
label->setAlignment( Qt::AlignHCenter );
mainLayout->addWidget( label );
} else
mainLayout->addWidget( mPluginWidget );
mainLayout->addStretch();
}
public:
KRES::ConfigWidget *mPluginWidget;
};
class KResourceConfigWidget : public QWidget
{
public:
KResourceConfigWidget( const QStringList &types, KRES::Factory *factory, QWidget *parent )
: QWidget( parent ), mStackWidget( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
mainLayout->setMargin( KDialog::marginHint() );
mStackWidget = new QStackedWidget( this );
mainLayout->addWidget( mStackWidget );
foreach ( const QString &type, types ) {
KResourcePluginConfigWidget *configWidget =
new KResourcePluginConfigWidget( type, factory, mStackWidget );
mStackWidget->addWidget( configWidget );
mStackedWidgets.insert( type, configWidget );
if ( configWidget->mPluginWidget != 0 ) {
connect( configWidget->mPluginWidget, SIGNAL( setReadOnly( bool ) ),
parent, SLOT( setReadOnly( bool ) ) );
}
}
}
void loadSettings( KRES::Resource *resource )
{
KResourcePluginConfigWidget *widget = mStackedWidgets[ resource->type() ];
Q_ASSERT( widget != 0 );
if ( widget->mPluginWidget != 0 )
widget->mPluginWidget->loadSettings( resource );
mStackWidget->setCurrentWidget( widget );
}
void saveSettings( KRES::Resource *resource )
{
KResourcePluginConfigWidget *widget = mStackedWidgets[ resource->type() ];
Q_ASSERT( widget != 0 );
if ( widget->mPluginWidget != 0 )
widget->mPluginWidget->saveSettings( resource );
}
public:
QStackedWidget *mStackWidget;
QMap<QString, KResourcePluginConfigWidget*> mStackedWidgets;
};
class KResourceFolderConfigWidget : public QWidget
{
public:
KResourceFolderConfigWidget( const QString &familyName, QWidget *parent )
: QWidget( parent ), mName( 0 ), mReadOnly( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this );
mainLayout->setSpacing( KDialog::spacingHint() );
// TODO probably add Akonadi related options
const QString helpText =
i18nc( "@info",
"The settings on this page allow you to customize how the "
"data from the plugin will fit into your personal information "
"setup." );
QLabel *helpLabel = new QLabel( this );
helpLabel->setWordWrap( true );
helpLabel->setText( helpText );
mainLayout->addWidget( helpLabel );
QGroupBox *generalGroup = new QGroupBox( this );
QGridLayout *generalLayout = new QGridLayout( generalGroup );
generalLayout->setMargin( KDialog::marginHint() );
generalLayout->setSpacing( KDialog::spacingHint() );
generalGroup->setTitle( i18nc( "@title:group general resource settings",
"%1 Folder Settings",
familyName ) );
QLabel *nameLabel = new QLabel( i18nc( "@label resource name", "Name:" ),
generalGroup );
generalLayout->addWidget( nameLabel, 0, 0 );
mName = new KLineEdit( generalGroup );
generalLayout->addWidget( mName, 0, 1 );
mReadOnly = new QCheckBox( i18nc( "@option:check if resource is read-only",
"Read-only" ),
generalGroup );
generalLayout->addWidget( mReadOnly, 1, 0, 1, 2 );
mReadOnly->setChecked( false );
mainLayout->addWidget( generalGroup );
mainLayout->addStretch();
connect( mName, SIGNAL( textChanged( const QString& ) ),
parent, SLOT( slotNameChanged( const QString& ) ) );
}
public:
KLineEdit *mName;
QCheckBox *mReadOnly;
};
class KResourceAssistant::Private
{
public:
explicit Private( KResourceAssistant *parent )
: mParent( parent ), mFactory( 0 ), mCreationWidget( 0 ),
mConfigWidget( 0 ), mFolderWidget( 0 ),
mLastPage( 0 )
{
}
public:
KResourceAssistant *mParent;
KRES::Factory *mFactory;
KResourceCreationWidget *mCreationWidget;
KResourceConfigWidget *mConfigWidget;
KResourceFolderConfigWidget *mFolderWidget;
KPageWidgetItem *mLastPage;
public:
void setReadOnly( bool readOnly )
{
mFolderWidget->mReadOnly->setChecked( readOnly );
}
void slotNameChanged( const QString &text );
};
KResourceAssistant::KResourceAssistant( const QString& resourceFamily, QWidget *parent )
: KAssistantDialog( parent ), d( new Private( this ) )
{
// TODO they are most likely already defined somewhere
QMap<QString, QString> familyNames;
familyNames[ QLatin1String( "contact" ) ] =
i18nc( "@title user visible resource type", "Address Book" );
familyNames[ QLatin1String( "calendar" ) ] =
i18nc( "@title user visible resource type", "Calendar" );
const QString familyName = familyNames[ resourceFamily.toLower() ];
setModal( true );
setCaption( i18nc( "@title:window", "KDE Compatibility Assistant" ) );
QWidget *introPage = new CompatibilityIntroductionLabel( this );
addPage( introPage, QString() );
d->mFactory = KRES::Factory::self( resourceFamily.toLower() );
d->mCreationWidget = new KResourceCreationWidget( familyName, d->mFactory, this );
addPage( d->mCreationWidget, i18nc( "@title assistant dialog step",
"Step 1: Select a KDE resource plugin") );
d->mConfigWidget =
new KResourceConfigWidget( d->mCreationWidget->mTypes, d->mFactory, this );
addPage( d->mConfigWidget, i18nc( "@title assistant dialog step",
"Step 2: Configure the selected KDE resource plugin") );
d->mFolderWidget = new KResourceFolderConfigWidget( familyName, this );
d->mLastPage = addPage( d->mFolderWidget, i18nc( "@title assistant dialog step",
"Step 3: Choose target folder properties" ) );
}
KResourceAssistant::~KResourceAssistant()
{
delete d;
}
KRES::Resource *KResourceAssistant::resource()
{
return d->mCreationWidget->mResource;
}
void KResourceAssistant::back()
{
KPageWidgetItem *item = currentPage();
if ( item->widget() == d->mConfigWidget ) {
d->mConfigWidget->saveSettings( d->mCreationWidget->mResource );
}
KAssistantDialog::back();
}
void KResourceAssistant::next()
{
KPageWidgetItem *item = currentPage();
if ( item->widget() == d->mCreationWidget ) {
d->mCreationWidget->createResource();
d->mConfigWidget->loadSettings( d->mCreationWidget->mResource );
} else if ( item->widget() == d->mConfigWidget ) {
const QString resourceName = d->mCreationWidget->mResource->resourceName();
d->mFolderWidget->mName->setText( resourceName );
}
KAssistantDialog::next();
}
void KResourceAssistant::Private::slotNameChanged( const QString &text )
{
mParent->setValid( mLastPage, !text.isEmpty() );
mCreationWidget->mResource->setResourceName( text );
}
#include "kresourceassistant.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////
// //
// AddCaloHFEpp //
// Author: T. Suzuki Univ. of Tsukuba //
// //
///////////////////////////////////////////////////////////////////
class AliAnalysisDataContainer;
AliAnalysisTaskCaloHFEpp* AddTaskCaloHFEpp(TString name = "name",
TString dataname = "dataname",
Bool_t flagEG1,
Bool_t flagEG2,
Bool_t SetFlagClsTypeEMC,
Bool_t SetFlagClsTypeDCAL)
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":CaloHFEpp"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskCaloHFEpp* task = new AliAnalysisTaskCaloHFEpp(name.Data());
task -> SetEG1(flagEG1);
task -> SetEG2(flagEG2);
task -> SetfFlagClsTypeEMC(SetFlagClsTypeEMC);
task -> SetfFlagClsTypeDCAL(SetFlagClsTypeDCAL);
if(!task) return 0x0;
// add your task to the manager
mgr->AddTask(task);
TString containerName = mgr->GetCommonFileName();
containerName += ":PWGHF_hfeCalpp";
TString SubcontainerName = Form("hfeCalpp");
SubcontainerName += name;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(SubcontainerName, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput1);
return task;
}
<commit_msg>add default parameter<commit_after>///////////////////////////////////////////////////////////////////
// //
// AddCaloHFEpp //
// Author: T. Suzuki Univ. of Tsukuba //
// //
///////////////////////////////////////////////////////////////////
class AliAnalysisDataContainer;
AliAnalysisTaskCaloHFEpp* AddTaskCaloHFEpp(TString name = "name",
TString dataname = "dataname",
Bool_t flagEG1 = kFALSE,
Bool_t flagEG2 = kFALSE,
Bool_t SetFlagClsTypeEMC = kFALSE,
Bool_t SetFlagClsTypeDCAL = kFALSE)
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":CaloHFEpp"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskCaloHFEpp* task = new AliAnalysisTaskCaloHFEpp(name.Data());
task -> SetEG1(flagEG1);
task -> SetEG2(flagEG2);
task -> SetfFlagClsTypeEMC(SetFlagClsTypeEMC);
task -> SetfFlagClsTypeDCAL(SetFlagClsTypeDCAL);
if(!task) return 0x0;
// add your task to the manager
mgr->AddTask(task);
TString containerName = mgr->GetCommonFileName();
containerName += ":PWGHF_hfeCalpp";
TString SubcontainerName = Form("hfeCalpp");
SubcontainerName += name;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(SubcontainerName, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput1);
return task;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>
//
// 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.
#ifndef BYOM_DYNAMIC_VIEW_HPP
#define BYOM_DYNAMIC_VIEW_HPP
#include <string>
#include <memory>
#include <functional>
#include <type_traits>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
namespace byom {
class dynamic_view;
using visit_function =
std::function<void(dynamic_view const&, dynamic_view const&)>;
template <typename T, typename Enable = void>
struct ext;
class dynamic_view
{
template <typename T>
using no_copy_ctor = typename std::enable_if<!std::is_same<
typename std::remove_reference<T>::type, dynamic_view>::value>::type;
public:
template <typename T, typename Enable = no_copy_ctor<T>>
dynamic_view(T&& t)
: dynamic_view(std::forward<T>(t), std::is_lvalue_reference<T>())
{
}
template <typename T>
dynamic_view(T* t)
{
new (storage()) local_model_t<T*>(t);
}
template <typename T>
dynamic_view(T const* t)
{
new (storage()) local_model_t<T const*>(t);
}
dynamic_view(dynamic_view const& x)
{
x.object().clone(storage());
}
dynamic_view(dynamic_view&& x)
{
x.object().move_clone(storage());
}
~dynamic_view()
{
object().~concept_t();
}
dynamic_view& operator=(dynamic_view&& x) = delete;
dynamic_view& operator=(dynamic_view const& x) = delete;
public:
bool empty() const
{
return object().empty();
}
dynamic_view at(std::string const& n) const &
{
return object().at(n);
}
dynamic_view at(std::string const& n) const &&
{
auto member = object().at(n);
if (object().owned() && !member.object().owned()) {
throw std::invalid_argument{ "dangling reference" };
}
return member;
}
void for_each(visit_function const& v) const
{
object().for_each(v);
}
friend std::ostream& operator<<(std::ostream& os, dynamic_view const& self)
{
self.object().print(os);
return os;
}
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual void clone(void* storage) const = 0;
virtual void move_clone(void* storage) = 0;
virtual bool owned() const = 0;
virtual bool empty() const = 0;
virtual dynamic_view at(std::string const& n) const = 0;
virtual void for_each(visit_function const& v) const = 0;
virtual void print(std::ostream& os) const = 0;
};
template <template <typename> class Derived, typename T>
struct model_base_t : concept_t
{
bool empty() const override
{
return ext<T>::empty_impl(get());
}
dynamic_view at(std::string const& n) const override
{
return ext<T>::at_impl(get(), n);
}
void for_each(visit_function const& v) const override
{
ext<T>::for_each_impl(get(), v);
}
void print(std::ostream& os) const override
{
ext<T>::print_impl(os, get());
}
T const& get() const
{
return static_cast<Derived<T> const*>(this)->get();
}
};
template <typename T>
struct cref_model_t : model_base_t<cref_model_t, T>
{
cref_model_t(T const& x)
: object(x)
{
}
void clone(void* storage) const override
{
new (storage) cref_model_t(object);
}
void move_clone(void* storage) override
{
clone(storage);
}
bool owned() const override
{
return false;
}
T const& get() const
{
return object;
}
T const& object;
};
template <typename T>
struct local_model_t : model_base_t<local_model_t, T>
{
local_model_t(T x)
: object(std::move(x))
{
}
void clone(void* storage) const override
{
new (storage) local_model_t(object);
}
bool owned() const override
{
return true;
}
void move_clone(void* storage) override
{
new (storage) local_model_t(std::move(object));
}
T const& get() const
{
return object;
}
T object;
};
template <typename T>
struct remote_model_t : model_base_t<remote_model_t, T>
{
remote_model_t(T x)
: object(std::make_unique<T const>(std::move(x)))
{
}
void clone(void* storage) const override
{
new (storage) remote_model_t(get());
}
void move_clone(void* storage) override
{
new (storage) remote_model_t(std::move(*this));
}
bool owned() const override
{
return true;
}
T const& get() const
{
return *object;
}
std::unique_ptr<T const> object;
};
private:
template <typename T>
dynamic_view(T&& t, std::true_type)
{
using model = cref_model_t<typename std::decay<T>::type>;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(t);
}
template <typename T>
dynamic_view(T&& t, std::false_type)
{
using local_type = local_model_t<typename std::decay<T>::type>;
using remote_type = remote_model_t<typename std::decay<T>::type>;
using use_local_type =
boost::mpl::bool_<(sizeof(local_type) <= sizeof(data)) &&
(std::is_nothrow_copy_constructible<T>::value ||
std::is_nothrow_move_constructible<T>::value)>;
using model =
typename boost::mpl::if_<use_local_type, local_type, remote_type>::type;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(std::move(t));
}
private:
concept_t& object()
{
return *static_cast<concept_t*>(storage());
}
concept_t const& object() const
{
return *static_cast<concept_t const*>(storage());
}
void* storage()
{
return &data;
}
void const* storage() const
{
return &data;
}
double data[2];
};
} // namespace byom
#endif /* BYOM_DYNAMIC_VIEW_HPP */
<commit_msg>add get function<commit_after>// Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>
//
// 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.
#ifndef BYOM_DYNAMIC_VIEW_HPP
#define BYOM_DYNAMIC_VIEW_HPP
#include <string>
#include <memory>
#include <functional>
#include <type_traits>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
namespace byom {
class dynamic_view;
using visit_function =
std::function<void(dynamic_view const&, dynamic_view const&)>;
template <typename T, typename Enable = void>
struct ext;
class dynamic_view
{
template <typename T>
using no_copy_ctor = typename std::enable_if<!std::is_same<
typename std::remove_reference<T>::type, dynamic_view>::value>::type;
public:
template <typename T, typename Enable = no_copy_ctor<T>>
dynamic_view(T&& t)
: dynamic_view(std::forward<T>(t), std::is_lvalue_reference<T>())
{
}
template <typename T>
dynamic_view(T* t)
{
new (storage()) local_model_t<T*>(t);
}
template <typename T>
dynamic_view(T const* t)
{
new (storage()) local_model_t<T const*>(t);
}
dynamic_view(dynamic_view const& x)
{
x.object().clone(storage());
}
dynamic_view(dynamic_view&& x)
{
x.object().move_clone(storage());
}
~dynamic_view()
{
object().~concept_t();
}
dynamic_view& operator=(dynamic_view&& x) = delete;
dynamic_view& operator=(dynamic_view const& x) = delete;
public:
bool empty() const
{
return object().empty();
}
dynamic_view at(std::string const& n) const &
{
return object().at(n);
}
dynamic_view at(std::string const& n) const &&
{
auto member = object().at(n);
if (object().owned() && !member.object().owned()) {
throw std::invalid_argument{ "dangling reference" };
}
return member;
}
void for_each(visit_function const& v) const
{
object().for_each(v);
}
template <typename T>
T get() const
{
if (object().type() != typeid(T)) {
throw std::bad_cast{ "bad cast" };
}
return *reinterpret_cast<T const*>(object().data());
}
friend std::ostream& operator<<(std::ostream& os, dynamic_view const& self)
{
self.object().print(os);
return os;
}
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual void clone(void* storage) const = 0;
virtual void move_clone(void* storage) = 0;
virtual bool owned() const = 0;
virtual const std::type_info& type() const = 0;
virtual void const* data() const = 0;
virtual bool empty() const = 0;
virtual dynamic_view at(std::string const& n) const = 0;
virtual void for_each(visit_function const& v) const = 0;
virtual void print(std::ostream& os) const = 0;
};
template <template <typename> class Derived, typename T>
struct model_base_t : concept_t
{
const std::type_info& type() const override
{
return typeid(T);
}
void const* data() const override
{
return &get();
}
bool empty() const override
{
return ext<T>::empty_impl(get());
}
dynamic_view at(std::string const& n) const override
{
return ext<T>::at_impl(get(), n);
}
void for_each(visit_function const& v) const override
{
ext<T>::for_each_impl(get(), v);
}
void print(std::ostream& os) const override
{
ext<T>::print_impl(os, get());
}
T const& get() const
{
return static_cast<Derived<T> const*>(this)->get();
}
};
template <typename T>
struct cref_model_t : model_base_t<cref_model_t, T>
{
cref_model_t(T const& x)
: object(x)
{
}
void clone(void* storage) const override
{
new (storage) cref_model_t(object);
}
void move_clone(void* storage) override
{
clone(storage);
}
bool owned() const override
{
return false;
}
T const& get() const
{
return object;
}
T const& object;
};
template <typename T>
struct local_model_t : model_base_t<local_model_t, T>
{
local_model_t(T x)
: object(std::move(x))
{
}
void clone(void* storage) const override
{
new (storage) local_model_t(object);
}
bool owned() const override
{
return true;
}
void move_clone(void* storage) override
{
new (storage) local_model_t(std::move(object));
}
T const& get() const
{
return object;
}
T object;
};
template <typename T>
struct remote_model_t : model_base_t<remote_model_t, T>
{
remote_model_t(T x)
: object(std::make_unique<T const>(std::move(x)))
{
}
void clone(void* storage) const override
{
new (storage) remote_model_t(get());
}
void move_clone(void* storage) override
{
new (storage) remote_model_t(std::move(*this));
}
bool owned() const override
{
return true;
}
T const& get() const
{
return *object;
}
std::unique_ptr<T const> object;
};
private:
template <typename T>
dynamic_view(T&& t, std::true_type)
{
using model = cref_model_t<typename std::decay<T>::type>;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(t);
}
template <typename T>
dynamic_view(T&& t, std::false_type)
{
using local_type = local_model_t<typename std::decay<T>::type>;
using remote_type = remote_model_t<typename std::decay<T>::type>;
using use_local_type =
boost::mpl::bool_<(sizeof(local_type) <= sizeof(data)) &&
(std::is_nothrow_copy_constructible<T>::value ||
std::is_nothrow_move_constructible<T>::value)>;
using model =
typename boost::mpl::if_<use_local_type, local_type, remote_type>::type;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(std::move(t));
}
private:
concept_t& object()
{
return *static_cast<concept_t*>(storage());
}
concept_t const& object() const
{
return *static_cast<concept_t const*>(storage());
}
void* storage()
{
return &data;
}
void const* storage() const
{
return &data;
}
double data[2];
};
} // namespace byom
#endif /* BYOM_DYNAMIC_VIEW_HPP */
<|endoftext|> |
<commit_before>#include <gflags/gflags.h>
#include <rans.hpp>
#include <iostream>
#include <fstream>
#include <string>
DEFINE_bool(dump_dfa, false, "dump DFA as dot language.");
DEFINE_bool(dump_matrix, false, "dump Matrix.");
DEFINE_bool(dump_exmatrix, false, "dump Extended Matrix.");
DEFINE_bool(dump_scc, false, "dump Strongly-connected-components of DFA.");
DEFINE_string(f, "", "obtain pattern from FILE.");
DEFINE_bool(i, false, "ignore case distinctions in both the REGEX and the input files..");
DEFINE_string(text, "", "print the value of given text on ANS.");
DEFINE_string(textf, "", "obtain text from FILE.");
DEFINE_string(quick_check, "", "check wheter given text is acceptable or not.");
DEFINE_string(value, "", "print the text of given value on ANS.");
DEFINE_bool(verbose, false, "report additional informations.");
DEFINE_bool(syntax, false, "print RANS regular expression syntax.");
DEFINE_bool(utf8, false, "use utf8 as internal encoding.");
DEFINE_string(convert_from, "", "convert the given value base from the given expression.");
DEFINE_string(convert_to, "", "convert the given value base to the given expression.");
DEFINE_string(compress, "", "compress the given file (create '.rans' file, by default).");
DEFINE_string(decompress, "", "decompress the given file");
DEFINE_string(out, "", "output file name.");
DEFINE_bool(size, false, "print the size of the DFA.");
DEFINE_bool(repl, false, "start REPL.");
DEFINE_bool(amount, false, "print number of acceptable strings that has less than '--value' characters in length.");
DEFINE_int64(count, -1, "print number of acceptable strings that just has specified characters in length.");
DEFINE_bool(compression_ratio, false, "print asymptotic compression ratio [%].");
DEFINE_bool(frobenius_root, false, "print frobenius root of adjacency matrix.");
DEFINE_bool(frobenius_root2, false, "print frobenius root of adjacency matrix without linear algebraic optimization.");
DEFINE_bool(factorial, false, "make langauge as a factorial");
void dispatch(const RANS&);
void set_filename(const std::string&, std::string&);
int main(int argc, char* argv[])
{
google::SetUsageMessage(
"RANS command line tool.\n"
"Usage: rans REGEX [Flags ...] \n"
"You can check RANS extended regular expression syntax via '--syntax' option."
);
google::SetVersionString(std::string("build rev: ")+std::string(GIT_REV));
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_syntax) {
std::cout << rans::SYNTAX;
return 0;
}
std::string regex;
if (!FLAGS_f.empty()) {
std::ifstream ifs(FLAGS_f.data());
ifs >> regex;
} else if (argc > 1) {
regex = argv[1];
} else if (FLAGS_convert_from.empty() || FLAGS_convert_to.empty()) {
std::cout << google::ProgramUsage() << std::endl;
return 0;
}
if (FLAGS_text.empty() && !FLAGS_textf.empty()) {
std::ifstream ifs(FLAGS_textf.data());
if (ifs.fail()) {
std::cout << FLAGS_textf + " does not exists." << std::endl;
exit(0);
}
ifs >> FLAGS_text;
}
RANS::Encoding enc = FLAGS_utf8 ? RANS::UTF8 : RANS::ASCII;
if (!FLAGS_convert_from.empty() && !FLAGS_convert_to.empty()) {
RANS from(FLAGS_convert_from, enc, FLAGS_factorial, FLAGS_i),
to(FLAGS_convert_to, enc, FLAGS_factorial, FLAGS_i);
if (!from.ok() || !to.ok()) {
std::cout << from.error() << std::endl << to.error() << std::endl;
exit(0);
}
if (FLAGS_compression_ratio) {
std::cout << from.compression_ratio(FLAGS_count, to) << std::endl;
} else if (!FLAGS_text.empty()) {
try {
std::cout << to(from(FLAGS_text)) << std::endl;
} catch (RANS::Exception& e) {
std::cout << e.what() << std::endl;
}
}
return 0;
}
RANS r(regex, enc, FLAGS_factorial, FLAGS_i);
if (!r.ok()) {
std::cout << r.error() << std::endl;
exit(0);
}
if (FLAGS_dump_dfa) std::cout << r.dfa();
if (FLAGS_dump_matrix) std::cout << r.adjacency_matrix();
if (FLAGS_dump_exmatrix) std::cout << r.extended_adjacency_matrix();
if (FLAGS_dump_scc) {
for (std::size_t i = 0; i < r.scc().size(); i++) {
for (std::set<std::size_t>::iterator iter = r.scc()[i].begin();
iter != r.scc()[i].end(); ++iter) {
std::cout << *iter << ", ";
}
std::cout << std::endl;
}
}
try {
dispatch(r);
} catch (RANS::Exception& e) {
std::cout << e.what() << std::endl;
exit(0);
}
return 0;
}
void dispatch(const RANS& r) {
if (FLAGS_frobenius_root) {
std::cout << r.spectrum().root << std::endl;
} else if (FLAGS_frobenius_root2) {
std::cout << r.adjacency_matrix().frobenius_root() << std::endl;
} else if (FLAGS_compression_ratio) {
std::cout << r.compression_ratio(FLAGS_count) << std::endl;
} else if (FLAGS_amount) {
if (FLAGS_count < 0) {
if (r.finite()) {
std::cout << r.amount() << std::endl;
} else {
std::cout << "there exists infinite acceptable strings." << std::endl;
}
} else {
std::cout << r.amount(FLAGS_count) << std::endl;
}
} else if (FLAGS_count >= 0) {
std::cout << r.count(FLAGS_count) << std::endl;
} else if (!FLAGS_quick_check.empty()) {
if (r.dfa().accept(FLAGS_quick_check)) {
std::cout << "text is acceptable." << std::endl;
} else {
std::cout << "text is not acceptable." << std::endl;
}
} else if (!FLAGS_compress.empty()) {
std::string text;
std::ifstream ifs(FLAGS_compress.data(), std::ios::in | std::ios::binary);
if (ifs.fail()) {
std::cout << FLAGS_decompress + " does not exists." << std::endl;
exit(0);
}
ifs >> text;
if (FLAGS_out.empty()) {
FLAGS_out = FLAGS_compress;
FLAGS_out += ".rans";
}
std::ofstream ofs(FLAGS_out.data(), std::ios::out | std::ios::binary);
try {
std::string dst;
ofs << r.compress(text, dst);
} catch (const RANS::Exception &e) {
std::cout << e.what() << std::endl;
}
} else if (!FLAGS_decompress.empty()) {
std::ifstream ifs(FLAGS_decompress.data(), std::ios::in | std::ios::binary);
if (ifs.fail()) {
std::cout << FLAGS_decompress + " does not exists." << std::endl;
exit(0);
}
std::istreambuf_iterator<char> first(ifs);
std::istreambuf_iterator<char> last;
std::string text(first, last);
set_filename(FLAGS_decompress, FLAGS_out);
if (FLAGS_out.empty()) exit(0);
std::ofstream ofs(FLAGS_out.data(), std::ios::out | std::ios::binary);
try {
std::string dst;
ofs << r.decompress(text, dst);
} catch (const RANS::Exception &e) {
std::cout << e.what() << std::endl;
}
} else if (FLAGS_size) {
std::cout << "size of DFA: " << r.dfa().size() << std::endl;
} else if (!FLAGS_value.empty()) {
std::cout << r(RANS::Value(FLAGS_value)) << std::endl;
} else if (!FLAGS_text.empty()) {
std::cout << r(FLAGS_text) << std::endl;
} else if (FLAGS_repl) {
std::string text;
RANS::Value value;
while (std::cin >> text) {
try {
std::cout << r(text, value) << std::endl;
std::cout << r(value, text) << std::endl;
} catch(const RANS::Exception& e) {
std::cout << e.what() << std::endl;
}
}
}
}
void set_filename(const std::string& src, std::string& dst)
{
if (!dst.empty()) return;
static const std::string suffix = ".rans";
if (src.length() > suffix.length() &&
src.substr(src.length() - suffix.length(), std::string::npos) == suffix) {
dst = src.substr(0, src.length() - suffix.length());
} else {
std::string input = "dummy";
do {
switch (input[0]) {
case 'y': case 'A': dst = src; return;
case 'n': case 'N': return;
case 'r':
std::cout << "new name: ";
std::cin >> dst;
return;
default:
std::cout << "replace " << src << "? [y]es, [n]o, [A]ll, [N]one, [r]ename: ";
}
} while (std::cin >> input);
}
}
<commit_msg>modify cui behavior for easy to enumerate.<commit_after>#include <gflags/gflags.h>
#include <rans.hpp>
#include <iostream>
#include <fstream>
#include <string>
DEFINE_bool(dfa, false, "dump DFA as dot language.");
DEFINE_bool(matrix, false, "dump Matrix.");
DEFINE_bool(exmatrix, false, "dump Extended Matrix.");
DEFINE_bool(scc, false, "dump Strongly-connected-components of DFA.");
DEFINE_string(f, "", "obtain pattern from FILE.");
DEFINE_bool(i, false, "ignore case distinctions in both the REGEX and the input files..");
DEFINE_string(text, "", "print the value of given text on ANS.");
DEFINE_string(textf, "", "obtain text from FILE.");
DEFINE_string(quick_check, "", "check wheter given text is acceptable or not.");
DEFINE_string(value, "", "print the text of given value on ANS.");
DEFINE_bool(verbose, false, "report additional informations.");
DEFINE_bool(syntax, false, "print RANS regular expression syntax.");
DEFINE_bool(utf8, false, "use utf8 as internal encoding.");
DEFINE_string(convert_from, "", "convert the given value base from the given expression.");
DEFINE_string(convert_to, "", "convert the given value base to the given expression.");
DEFINE_string(compress, "", "compress the given file (create '.rans' file, by default).");
DEFINE_string(decompress, "", "decompress the given file");
DEFINE_string(out, "", "output file name.");
DEFINE_bool(size, false, "print the size of the DFA.");
DEFINE_bool(amount, false, "print number of acceptable strings that has less than '--value' characters in length.");
DEFINE_int64(count, -1, "print number of acceptable strings that just has specified characters in length.");
DEFINE_bool(compression_ratio, false, "print asymptotic compression ratio [%].");
DEFINE_bool(frobenius_root, false, "print frobenius root of adjacency matrix.");
DEFINE_bool(frobenius_root2, false, "print frobenius root of adjacency matrix without linear algebraic optimization.");
DEFINE_bool(factorial, false, "make langauge as a factorial");
DEFINE_bool(tovalue, false, "convert the given text into the correspondence value");
void dispatch(const RANS&);
void set_filename(const std::string&, std::string&);
int main(int argc, char* argv[])
{
google::SetUsageMessage(
"RANS command line tool.\n"
"Usage: rans REGEX [Flags ...] \n"
"You can check RANS extended regular expression syntax via '--syntax' option."
);
google::SetVersionString(std::string("build rev: ")+std::string(GIT_REV));
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_syntax) {
std::cout << rans::SYNTAX;
return 0;
}
std::string regex;
if (!FLAGS_f.empty()) {
std::ifstream ifs(FLAGS_f.data());
ifs >> regex;
} else if (argc > 1) {
regex = argv[1];
} else if (FLAGS_convert_from.empty() || FLAGS_convert_to.empty()) {
std::cout << google::ProgramUsage() << std::endl;
return 0;
}
if (FLAGS_text.empty() && !FLAGS_textf.empty()) {
std::ifstream ifs(FLAGS_textf.data());
if (ifs.fail()) {
std::cout << FLAGS_textf + " does not exists." << std::endl;
exit(0);
}
ifs >> FLAGS_text;
}
RANS::Encoding enc = FLAGS_utf8 ? RANS::UTF8 : RANS::ASCII;
if (!FLAGS_convert_from.empty() && !FLAGS_convert_to.empty()) {
RANS from(FLAGS_convert_from, enc, FLAGS_factorial, FLAGS_i),
to(FLAGS_convert_to, enc, FLAGS_factorial, FLAGS_i);
if (!from.ok() || !to.ok()) {
std::cout << from.error() << std::endl << to.error() << std::endl;
exit(0);
}
if (FLAGS_compression_ratio) {
std::cout << from.compression_ratio(FLAGS_count, to) << std::endl;
} else if (!FLAGS_text.empty()) {
try {
std::cout << to(from(FLAGS_text)) << std::endl;
} catch (RANS::Exception& e) {
std::cout << e.what() << std::endl;
}
}
return 0;
}
RANS r(regex, enc, FLAGS_factorial, FLAGS_i);
if (!r.ok()) {
std::cout << r.error() << std::endl;
exit(0);
}
if (FLAGS_dfa) std::cout << r.dfa();
if (FLAGS_matrix) std::cout << r.adjacency_matrix();
if (FLAGS_exmatrix) std::cout << r.extended_adjacency_matrix();
if (FLAGS_scc) {
for (std::size_t i = 0; i < r.scc().size(); i++) {
for (std::set<std::size_t>::iterator iter = r.scc()[i].begin();
iter != r.scc()[i].end(); ++iter) {
std::cout << *iter << ", ";
}
std::cout << std::endl;
}
}
if (!(FLAGS_dfa || FLAGS_matrix || FLAGS_exmatrix || FLAGS_scc)) {
try {
dispatch(r);
} catch (RANS::Exception& e) {
std::cout << e.what() << std::endl;
exit(0);
}
}
return 0;
}
void dispatch(const RANS& r) {
if (FLAGS_frobenius_root) {
std::cout << r.spectrum().root << std::endl;
} else if (FLAGS_frobenius_root2) {
std::cout << r.adjacency_matrix().frobenius_root() << std::endl;
} else if (FLAGS_compression_ratio) {
std::cout << r.compression_ratio(FLAGS_count) << std::endl;
} else if (FLAGS_amount) {
if (FLAGS_count < 0) {
if (r.finite()) {
std::cout << r.amount() << std::endl;
} else {
std::cout << "there exists infinite acceptable strings." << std::endl;
}
} else {
std::cout << r.amount(FLAGS_count) << std::endl;
}
} else if (FLAGS_count >= 0) {
std::cout << r.count(FLAGS_count) << std::endl;
} else if (!FLAGS_quick_check.empty()) {
if (r.dfa().accept(FLAGS_quick_check)) {
std::cout << "text is acceptable." << std::endl;
} else {
std::cout << "text is not acceptable." << std::endl;
}
} else if (!FLAGS_compress.empty()) {
std::string text;
std::ifstream ifs(FLAGS_compress.data(), std::ios::in | std::ios::binary);
if (ifs.fail()) {
std::cout << FLAGS_decompress + " does not exists." << std::endl;
exit(0);
}
ifs >> text;
if (FLAGS_out.empty()) {
FLAGS_out = FLAGS_compress;
FLAGS_out += ".rans";
}
std::ofstream ofs(FLAGS_out.data(), std::ios::out | std::ios::binary);
try {
std::string dst;
ofs << r.compress(text, dst);
} catch (const RANS::Exception &e) {
std::cout << e.what() << std::endl;
}
} else if (!FLAGS_decompress.empty()) {
std::ifstream ifs(FLAGS_decompress.data(), std::ios::in | std::ios::binary);
if (ifs.fail()) {
std::cout << FLAGS_decompress + " does not exists." << std::endl;
exit(0);
}
std::istreambuf_iterator<char> first(ifs);
std::istreambuf_iterator<char> last;
std::string text(first, last);
set_filename(FLAGS_decompress, FLAGS_out);
if (FLAGS_out.empty()) exit(0);
std::ofstream ofs(FLAGS_out.data(), std::ios::out | std::ios::binary);
try {
std::string dst;
ofs << r.decompress(text, dst);
} catch (const RANS::Exception &e) {
std::cout << e.what() << std::endl;
}
} else if (FLAGS_size) {
std::cout << "size of DFA: " << r.dfa().size() << std::endl;
} else if (!FLAGS_value.empty()) {
std::cout << r(RANS::Value(FLAGS_value)) << std::endl;
} else if (!FLAGS_text.empty()) {
std::cout << r(FLAGS_text) << std::endl;
} else {
std::string input;
while (std::cin >> input) {
try {
if (FLAGS_tovalue) {
std::cout << r(input) << std::endl;
} else {
std::cout << r(RANS::Value(input)) << std::endl;
}
} catch(const RANS::Exception& e) {
std::cout << e.what() << std::endl;
}
}
}
}
void set_filename(const std::string& src, std::string& dst)
{
if (!dst.empty()) return;
static const std::string suffix = ".rans";
if (src.length() > suffix.length() &&
src.substr(src.length() - suffix.length(), std::string::npos) == suffix) {
dst = src.substr(0, src.length() - suffix.length());
} else {
std::string input = "dummy";
do {
switch (input[0]) {
case 'y': case 'A': dst = src; return;
case 'n': case 'N': return;
case 'r':
std::cout << "new name: ";
std::cin >> dst;
return;
default:
std::cout << "replace " << src << "? [y]es, [n]o, [A]ll, [N]one, [r]ename: ";
}
} while (std::cin >> input);
}
}
<|endoftext|> |
<commit_before>/*
* httpstream.cpp - HTTP stream parser
* Copyright (C) 2013 Il'inykh Sergey (rion)
*
* 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 "httpstream.h"
#include "bsocket.h"
#include "../xmpp/zlib/zlibdecompressor.h"
//------------------------------------------------------------------------------
// LayerStream
//------------------------------------------------------------------------------
// implemented here just in case. usually should be reimplemented or not used
void LayerStream::writeIncoming(const QByteArray &data)
{
handleOutData(data); // no processing in base class so move data out
}
void LayerStream::handleOutData(const QByteArray &data)
{
if (_dataOutLayer) {
_dataOutLayer->writeIncoming(data);
} else {
appendRead(data);
emit readyRead();
}
}
//--------------------------------------------
// GzipStream
//--------------------------------------------
class GzipStream : public LayerStream
{
Q_OBJECT
ZLibDecompressor *zDec;
QBuffer uncompressed;
public:
GzipStream(QObject *parent) :
LayerStream(parent)
{
uncompressed.setBuffer(&readBuf());
zDec = new ZLibDecompressor(&uncompressed);
connect(&uncompressed, SIGNAL(bytesWritten(qint64)), SLOT(decompressedWritten(qint64)));
}
void writeIncoming(const QByteArray &data)
{
zDec->write(data);
}
private slots:
void decompressedWritten(qint64 size)
{
if (size) {
if (_dataOutLayer) {
_dataOutLayer->writeIncoming(uncompressed.buffer());
uncompressed.buffer().clear();
uncompressed.seek(0);
} else {
emit readyRead();
}
}
}
};
//--------------------------------------------
// ChunkedStream
//--------------------------------------------
class ChunkedStream : public LayerStream
{
Q_OBJECT
enum State
{
Header,
Body,
BodyEnd,
Trailer
};
bool sizeParsed;
State _state;
quint64 chunkSize;
quint64 chunkBytesLeft; // bytes left to read for current chunk
static const quint8 tmpBufSize = 12;
QByteArray tmpBuffer;
public:
ChunkedStream(QObject *parent) :
LayerStream(parent),
sizeParsed(false),
_state(Header)
{
tmpBuffer.reserve(tmpBufSize);
}
void writeIncoming(const QByteArray &data)
{
int index;
QByteArray tail = QByteArray::fromRawData(data.constData(), data.size());
while (tail.size()) {
switch (_state) {
case Header:
{
quint8 lastHeaderSize = (quint8)tmpBuffer.size();
quint8 bufFree = tmpBufSize - lastHeaderSize;
tmpBuffer += ((int)bufFree > tail.size() ? tail : QByteArray::fromRawData(
tail.constData(), bufFree));
if ((index = tmpBuffer.indexOf("\r\n")) == -1) {
if (!bufFree) {
setError(ErrRead, "String for chunk header is too long");
}
return;
}
tmpBuffer.resize(index);
int unparsedOffset = tmpBuffer.size() + 2 - lastHeaderSize;
tail = QByteArray::fromRawData(tail.constData() + unparsedOffset,
tail.size() - unparsedOffset);
chunkSize = tmpBuffer.toInt(&sizeParsed, 16);
if (!sizeParsed) {
setError(ErrRead, "chunk size parse failed");
return;
}
chunkBytesLeft = chunkSize;
tmpBuffer.clear(); // should be clean to make BodyEnd working
_state = chunkSize? Body : Trailer; // 0 means the end of response
break;
}
case Body:
{
QByteArray r = readTail(tail, chunkBytesLeft);
chunkBytesLeft -= r.size();
handleOutData(r);
if (chunkBytesLeft) {
break; // no enough data to finish chunk read
}
_state = BodyEnd;
}
case BodyEnd:
tmpBuffer.append(readTail(tail, 2 - tmpBuffer.size()));
if (tmpBuffer.size() == 2) {
if (tmpBuffer[0] != '\r' || tmpBuffer[1] != '\n') {
setError(ErrRead, "no \r\n at chunk end");
return;
}
_state = Header;
}
break;
case Trailer:
// TODO
break;
}
}
}
private:
QByteArray readTail(QByteArray &tail, int bytes) const
{
int rb = qMin<int>(bytes, tail.size());
QByteArray ret = QByteArray::fromRawData(tail.constData(), rb);
tail = QByteArray::fromRawData(tail.constData() + rb, tail.size() - rb);
return ret;
}
};
//--------------------------------------------
// HttpStream
//
// This layer assumes it receives raw data right from tcp or decoded ssl
// and on out it has some http unrelated data (html for example or contents
// of some file.). Layer internally creates another layers pipeline to handle
// http compression and chunked data (maybe other encodings in the future)
//--------------------------------------------
void HttpStream::writeIncoming(const QByteArray &data)
{
if (!data.size()) {
return;
}
QByteArray realData;
if (!headersReady) {
int parsePos = qMax<int>(headersBuffer.size() - 3, 0);
headersBuffer += data;
if (headersBuffer.indexOf("\r\n\r\n", parsePos) == -1) {
return;
}
if (parseHeaders(headersBuffer, parsePos)) {
parsePos += 2;
realData = QByteArray::fromRawData(headersBuffer.constData() + parsePos,
headersBuffer.size() - parsePos);
headersReady = true;
QByteArray header = headers.value("Content-Encoding").toLower();
if (!header.isEmpty()) {
QList<QByteArray> tes = header.split(',');
while (tes.size()) {
QByteArray lv = tes.takeLast().trimmed().toLower();
if (lv == "gzip" || lv == "x-gzip" || lv == "deflate") {
pipeLine.append(new GzipStream(this));
}
}
}
header = headers.value("Transfer-Encoding");
if (!header.isEmpty()) {
QList<QByteArray> tes = header.split(',');
while (tes.size()) {
QByteArray lv = tes.takeLast().trimmed().toLower();
if (lv == "chunked") {
pipeLine.append(new ChunkedStream(this));
}
if (lv == "gzip" || lv == "x-gzip" || lv == "deflate") {
pipeLine.append(new GzipStream(this));
}
}
headers.remove("Content-Length"); // by rfc2616 we have to ignore this header
}
if (pipeLine.count()) { // connect pipes
for (int i = 0; i < pipeLine.count() - 1; i++) {
pipeLine[i]->setDataOutLayer(pipeLine[i+1]);
}
connect(pipeLine.last(), SIGNAL(readyRead()), SLOT(pipeLine_readyReady()));
}
emit metaDataChanged();
} else {
qDebug("Invalid header: %s", headersBuffer.mid(
parsePos, headersBuffer.indexOf("\r\n", parsePos)).data());
setError(QNetworkReply::ProtocolFailure, "Invalid headers");
}
} else {
realData = data;
}
if (realData.size()) {
if (pipeLine.count()) {
pipeLine[0]->writeIncoming(realData);
} else {
handleOutData(realData);
}
}
}
void HttpStream::pipeLine_readyReady()
{
LayerStream *s = static_cast<LayerStream *>(sender());
handleOutData(s->readAll());
}
bool HttpStream::parseHeaders(const QByteArray &buffer, int &pos)
{
bool valid = true;
bool statusRead = false;
pos = 0;
int endPos = 0;
QByteArray lastKey;
while ((endPos = buffer.indexOf("\r\n", pos)) != -1 && endPos != pos) {
if (!statusRead) {
QRegExp statusRE("^HTTP/(1.[01]) (\\d{3})( .*)?$");
if (!statusRE.exactMatch(QString::fromLatin1(
buffer.constData() + pos, endPos - pos)))
{
valid = false;
break;
}
httpVersion = statusRE.cap(1);
statusCode = statusRE.cap(2).toInt();
statusText = statusRE.cap(3).trimmed();
statusRead = true;
} else {
QHash<QByteArray, QByteArray>::iterator it;
if (buffer[pos] == ' ' || buffer[pos] == '\t') { // multiline value
if (lastKey.isEmpty() || (it = headers.find(lastKey)) == headers.end()) {
valid = false;
break;
}
*it += ' ';
*it += buffer.mid(pos, endPos - pos).trimmed();
} else { // normal header line
int sPos = buffer.indexOf(':', pos);
if (sPos == -1 || sPos == pos || sPos > endPos) {
valid = false;
break;
}
QByteArray newKey = buffer.mid(pos, sPos - pos);
QByteArray newValue = buffer.mid(sPos + 1, endPos - sPos - 1);
if ((it = headers.find(newKey)) != headers.end()) { // by rfc we can combine so-named keys
*it += ',';
*it += newValue;
} else {
headers.insert(newKey, newValue);
lastKey == newKey;
}
}
}
pos = endPos + 2;
}
return valid;
}
<commit_msg>Add missing moc include to a cpp file containing Q_OBJECT macro<commit_after>/*
* httpstream.cpp - HTTP stream parser
* Copyright (C) 2013 Il'inykh Sergey (rion)
*
* 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 "httpstream.h"
#include "bsocket.h"
#include "../xmpp/zlib/zlibdecompressor.h"
//------------------------------------------------------------------------------
// LayerStream
//------------------------------------------------------------------------------
// implemented here just in case. usually should be reimplemented or not used
void LayerStream::writeIncoming(const QByteArray &data)
{
handleOutData(data); // no processing in base class so move data out
}
void LayerStream::handleOutData(const QByteArray &data)
{
if (_dataOutLayer) {
_dataOutLayer->writeIncoming(data);
} else {
appendRead(data);
emit readyRead();
}
}
//--------------------------------------------
// GzipStream
//--------------------------------------------
class GzipStream : public LayerStream
{
Q_OBJECT
ZLibDecompressor *zDec;
QBuffer uncompressed;
public:
GzipStream(QObject *parent) :
LayerStream(parent)
{
uncompressed.setBuffer(&readBuf());
zDec = new ZLibDecompressor(&uncompressed);
connect(&uncompressed, SIGNAL(bytesWritten(qint64)), SLOT(decompressedWritten(qint64)));
}
void writeIncoming(const QByteArray &data)
{
zDec->write(data);
}
private slots:
void decompressedWritten(qint64 size)
{
if (size) {
if (_dataOutLayer) {
_dataOutLayer->writeIncoming(uncompressed.buffer());
uncompressed.buffer().clear();
uncompressed.seek(0);
} else {
emit readyRead();
}
}
}
};
//--------------------------------------------
// ChunkedStream
//--------------------------------------------
class ChunkedStream : public LayerStream
{
Q_OBJECT
enum State
{
Header,
Body,
BodyEnd,
Trailer
};
bool sizeParsed;
State _state;
quint64 chunkSize;
quint64 chunkBytesLeft; // bytes left to read for current chunk
static const quint8 tmpBufSize = 12;
QByteArray tmpBuffer;
public:
ChunkedStream(QObject *parent) :
LayerStream(parent),
sizeParsed(false),
_state(Header)
{
tmpBuffer.reserve(tmpBufSize);
}
void writeIncoming(const QByteArray &data)
{
int index;
QByteArray tail = QByteArray::fromRawData(data.constData(), data.size());
while (tail.size()) {
switch (_state) {
case Header:
{
quint8 lastHeaderSize = (quint8)tmpBuffer.size();
quint8 bufFree = tmpBufSize - lastHeaderSize;
tmpBuffer += ((int)bufFree > tail.size() ? tail : QByteArray::fromRawData(
tail.constData(), bufFree));
if ((index = tmpBuffer.indexOf("\r\n")) == -1) {
if (!bufFree) {
setError(ErrRead, "String for chunk header is too long");
}
return;
}
tmpBuffer.resize(index);
int unparsedOffset = tmpBuffer.size() + 2 - lastHeaderSize;
tail = QByteArray::fromRawData(tail.constData() + unparsedOffset,
tail.size() - unparsedOffset);
chunkSize = tmpBuffer.toInt(&sizeParsed, 16);
if (!sizeParsed) {
setError(ErrRead, "chunk size parse failed");
return;
}
chunkBytesLeft = chunkSize;
tmpBuffer.clear(); // should be clean to make BodyEnd working
_state = chunkSize? Body : Trailer; // 0 means the end of response
break;
}
case Body:
{
QByteArray r = readTail(tail, chunkBytesLeft);
chunkBytesLeft -= r.size();
handleOutData(r);
if (chunkBytesLeft) {
break; // no enough data to finish chunk read
}
_state = BodyEnd;
}
case BodyEnd:
tmpBuffer.append(readTail(tail, 2 - tmpBuffer.size()));
if (tmpBuffer.size() == 2) {
if (tmpBuffer[0] != '\r' || tmpBuffer[1] != '\n') {
setError(ErrRead, "no \r\n at chunk end");
return;
}
_state = Header;
}
break;
case Trailer:
// TODO
break;
}
}
}
private:
QByteArray readTail(QByteArray &tail, int bytes) const
{
int rb = qMin<int>(bytes, tail.size());
QByteArray ret = QByteArray::fromRawData(tail.constData(), rb);
tail = QByteArray::fromRawData(tail.constData() + rb, tail.size() - rb);
return ret;
}
};
//--------------------------------------------
// HttpStream
//
// This layer assumes it receives raw data right from tcp or decoded ssl
// and on out it has some http unrelated data (html for example or contents
// of some file.). Layer internally creates another layers pipeline to handle
// http compression and chunked data (maybe other encodings in the future)
//--------------------------------------------
void HttpStream::writeIncoming(const QByteArray &data)
{
if (!data.size()) {
return;
}
QByteArray realData;
if (!headersReady) {
int parsePos = qMax<int>(headersBuffer.size() - 3, 0);
headersBuffer += data;
if (headersBuffer.indexOf("\r\n\r\n", parsePos) == -1) {
return;
}
if (parseHeaders(headersBuffer, parsePos)) {
parsePos += 2;
realData = QByteArray::fromRawData(headersBuffer.constData() + parsePos,
headersBuffer.size() - parsePos);
headersReady = true;
QByteArray header = headers.value("Content-Encoding").toLower();
if (!header.isEmpty()) {
QList<QByteArray> tes = header.split(',');
while (tes.size()) {
QByteArray lv = tes.takeLast().trimmed().toLower();
if (lv == "gzip" || lv == "x-gzip" || lv == "deflate") {
pipeLine.append(new GzipStream(this));
}
}
}
header = headers.value("Transfer-Encoding");
if (!header.isEmpty()) {
QList<QByteArray> tes = header.split(',');
while (tes.size()) {
QByteArray lv = tes.takeLast().trimmed().toLower();
if (lv == "chunked") {
pipeLine.append(new ChunkedStream(this));
}
if (lv == "gzip" || lv == "x-gzip" || lv == "deflate") {
pipeLine.append(new GzipStream(this));
}
}
headers.remove("Content-Length"); // by rfc2616 we have to ignore this header
}
if (pipeLine.count()) { // connect pipes
for (int i = 0; i < pipeLine.count() - 1; i++) {
pipeLine[i]->setDataOutLayer(pipeLine[i+1]);
}
connect(pipeLine.last(), SIGNAL(readyRead()), SLOT(pipeLine_readyReady()));
}
emit metaDataChanged();
} else {
qDebug("Invalid header: %s", headersBuffer.mid(
parsePos, headersBuffer.indexOf("\r\n", parsePos)).data());
setError(QNetworkReply::ProtocolFailure, "Invalid headers");
}
} else {
realData = data;
}
if (realData.size()) {
if (pipeLine.count()) {
pipeLine[0]->writeIncoming(realData);
} else {
handleOutData(realData);
}
}
}
void HttpStream::pipeLine_readyReady()
{
LayerStream *s = static_cast<LayerStream *>(sender());
handleOutData(s->readAll());
}
bool HttpStream::parseHeaders(const QByteArray &buffer, int &pos)
{
bool valid = true;
bool statusRead = false;
pos = 0;
int endPos = 0;
QByteArray lastKey;
while ((endPos = buffer.indexOf("\r\n", pos)) != -1 && endPos != pos) {
if (!statusRead) {
QRegExp statusRE("^HTTP/(1.[01]) (\\d{3})( .*)?$");
if (!statusRE.exactMatch(QString::fromLatin1(
buffer.constData() + pos, endPos - pos)))
{
valid = false;
break;
}
httpVersion = statusRE.cap(1);
statusCode = statusRE.cap(2).toInt();
statusText = statusRE.cap(3).trimmed();
statusRead = true;
} else {
QHash<QByteArray, QByteArray>::iterator it;
if (buffer[pos] == ' ' || buffer[pos] == '\t') { // multiline value
if (lastKey.isEmpty() || (it = headers.find(lastKey)) == headers.end()) {
valid = false;
break;
}
*it += ' ';
*it += buffer.mid(pos, endPos - pos).trimmed();
} else { // normal header line
int sPos = buffer.indexOf(':', pos);
if (sPos == -1 || sPos == pos || sPos > endPos) {
valid = false;
break;
}
QByteArray newKey = buffer.mid(pos, sPos - pos);
QByteArray newValue = buffer.mid(sPos + 1, endPos - sPos - 1);
if ((it = headers.find(newKey)) != headers.end()) { // by rfc we can combine so-named keys
*it += ',';
*it += newValue;
} else {
headers.insert(newKey, newValue);
lastKey == newKey;
}
}
}
pos = endPos + 2;
}
return valid;
}
#include "httpstream.moc"
<|endoftext|> |
<commit_before>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <cstdio>
#include <nix.hpp>
#include <nix/NDArray.hpp>
#include <queue>
#include <random>
#include <type_traits>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdexcept>
/* ************************************ */
class Stopwatch {
public:
typedef std::chrono::high_resolution_clock::time_point time_point_t;
typedef std::chrono::high_resolution_clock clock_t;
Stopwatch() : t_start(clock_t::now()) { };
ssize_t ms() {
time_point_t t_end = clock_t::now();
ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
return count;
}
private:
time_point_t t_start;
};
/* ************************************ */
class RndGenBase {
public:
RndGenBase() : rd(), rd_gen(rd()) { };
protected:
std::random_device rd;
std::mt19937 rd_gen;
};
template<typename T, typename Enable = void>
class RndGen { };
template<typename T>
class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase {
public:
RndGen() : dis(-1024.0, +1024.0) { };
T operator()(void) {
return dis(rd_gen);
};
private:
std::uniform_real_distribution<T> dis;
};
template<typename T>
class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase {
public:
RndGen() : dis(-1024, +1024) { };
T operator()(void) {
return dis(rd_gen);
};
private:
std::uniform_real_distribution<T> dis;
};
/* ************************************ */
template<typename T>
class BlockGenerator {
public:
BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };
std::vector<T> make_block() {
std::vector<T> block(blocksize);
std::generate(block.begin(), block.end(), std::ref(rnd_gen));
return block;
}
std::vector<T> next_block() {
std::unique_lock<std::mutex> lock(mtx);
if (queue.empty()) {
cnd.wait(lock, [this]{ return !queue.empty(); });
}
std::vector<T> x(std::move(queue.front()));
queue.pop();
cnd.notify_all();
return x;
}
void worker_thread() {
while (do_run) {
std::unique_lock<std::mutex> lock(mtx);
std::vector<T> block = make_block();
if (queue.size() > bufsize) {
//wait until there is room
cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});
if (!do_run) {
return;
}
}
queue.push(std::move(block));
cnd.notify_all();
}
}
void start_worker() {
workers.emplace_back(&BlockGenerator::worker_thread, this);
}
~BlockGenerator() {
do_run = false;
cnd.notify_all();
for (auto &w : workers) {
w.join();
}
}
double speed_test() {
Stopwatch sw;
size_t N = 100;
size_t iterations = 0;
do {
Stopwatch inner;
for (size_t i = 0; i < N; i++) {
std::vector<double> block = next_block();
iterations++;
}
if (inner.ms() < 100) {
N *= 2;
}
} while (sw.ms() < 1000);
ssize_t count = sw.ms();
return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0);
}
private:
bool do_run = true;
size_t blocksize;
size_t bufsize;
RndGen<T> rnd_gen;
std::mutex mtx;
std::condition_variable cnd;
std::queue<std::vector<T>> queue;
std::vector<std::thread> workers;
};
class Config {
public:
Config(nix::DataType data_type, const nix::NDSize &blocksize)
: data_type(data_type), block_size(blocksize) {
sdim = find_single_dim();
shape = blocksize;
shape[sdim] = 0;
make_name();
};
size_t find_single_dim() {
size_t sdim;
bool have_rdim = false;
for (size_t i = 0; i < block_size.size(); i ++) {
if (block_size[i] == 1) {
sdim = i;
have_rdim = true;
}
}
if (!have_rdim) {
throw std::runtime_error("Could not find singelton dimension");
}
return sdim;
}
nix::DataType dtype() const { return data_type; }
const nix::NDSize& size() const { return block_size; }
const nix::NDSize& extend() const { return shape; }
size_t singleton_dimension() const { return sdim; }
const std::string & name() const { return my_name; };
private:
void make_name() {
std::stringstream s;
s << data_type << "@{ ";
for (auto x : block_size) {
s << x << " ";
}
s << "}";
my_name = s.str();
}
private:
const nix::DataType data_type;
const nix::NDSize block_size;
size_t sdim;
nix::NDSize shape;
std::string my_name;
};
class Benchmark {
public:
Benchmark(const Config &cfg) : config(cfg) { }
const Config & cfg() const { return config; }
nix::DataArray openDataArray(nix::Block block) const {
const std::string &cfg_name = config.name();
std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name));
if (v.empty()) {
return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend());
} else {
return v[0];
}
}
virtual ~Benchmark() { }
double virtual speed_in_mbs() {
return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) *
(1000.0/millis) / (1024 * 1024);
}
template<typename F>
ssize_t time_it(F func) {
Stopwatch watch;
func();
return watch.ms();
}
virtual void run(nix::Block block) = 0;
virtual void report() = 0;
protected:
double calc_speed_mbs(ssize_t ms, size_t iterations) {
return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) /
(1024.0*1024.0);
}
protected:
const Config config;
size_t count;
double millis;
};
class GeneratorBenchmark : public Benchmark {
public:
GeneratorBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void run(nix::Block block) override {
switch (config.dtype()) {
case nix::DataType::Double:
test_speed<double>();
break;
default:
throw std::runtime_error("Unsupported DataType!");
}
}
template<typename T>
void test_speed() {
size_t nelms = config.size().nelms();
BlockGenerator<T> generator(nelms, 10);
generator.start_worker();
speed = generator.speed_test();
}
double speed_in_mbs() override {
return speed;
}
void report() override {
std::cout << config.name() << ": "
<< "G: " << speed << " MB/s, " << std::endl;
}
private:
double speed;
};
class WriteBenchmark : public Benchmark {
public:
WriteBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void test_write_io(nix::Block block) {
nix::DataArray da = openDataArray(block);
switch (config.dtype()) {
case nix::DataType::Double:
do_write_test<double>(da);
break;
default:
throw std::runtime_error("Unsupported DataType!");
}
}
void report() override {
std::cout << config.name() << ": "
<< "W: " << speed_write << " MB/s, " << std::endl;
}
void run(nix::Block block) override {
test_write_io(block);
}
private:
template<typename T>
void do_write_test(nix::DataArray da) {
size_t nelms = config.size().nelms();
BlockGenerator<T> generator(nelms, 10);
generator.start_worker();
size_t N = 100;
size_t iterations = 0;
nix::NDSize pos = {0, 0};
Stopwatch sw;
ssize_t ms = 0;
do {
Stopwatch inner;
for (size_t i = 0; i < N; i++) {
std::vector<T> block = generator.next_block();
da.dataExtent(config.size() + pos);
da.setData(config.dtype(), block.data(), config.size(), pos);
pos[config.singleton_dimension()] += 1;
iterations++;
}
if (inner.ms() < 100) {
N *= 2;
}
} while ((ms = sw.ms()) < 3*1000);
speed_write = calc_speed_mbs(ms, iterations);
}
private:
double speed_write;
};
class ReadBenchmark : public Benchmark {
public:
ReadBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void test_read_io(nix::Block block) {
nix::DataArray da = openDataArray(block);
speed_read = test_read_io(da);
}
double test_read_io(nix::DataArray da) {
nix::NDArray array(config.dtype(), config.size());
nix::NDSize extend = da.dataExtent();
size_t N = extend[config.singleton_dimension()];
nix::NDSize pos = {0, 0};
ssize_t ms = time_it([this, &da, &N, &pos, &array] {
for(size_t i = 0; i < N; i++) {
da.getData(config.dtype(), array.data(), config.size(), pos);
pos[config.singleton_dimension()] += 1;
}
});
return calc_speed_mbs(ms, N);
}
void report() override {
std::cout << config.name() << ": "
<< "R: " << speed_read << " MB/s, " << std::endl;
}
void run(nix::Block block) override {
test_read_io(block);
}
private:
double speed_read;
};
class ReadPolyBenchmark : public ReadBenchmark {
public:
ReadPolyBenchmark(const Config &cfg)
: ReadBenchmark(cfg) {
};
void test_read_io_polynom(nix::Block block) {
nix::DataArray da = openDataArray(block);
da.polynomCoefficients({3, 4, 5, 6});
speed_read_poly = test_read_io(da);
}
void report() override {
std::cout << config.name() << ": "
<< "P: " << speed_read_poly << " MB/s, " << std::endl;
}
void run(nix::Block block) override {
test_read_io_polynom(block);
}
private:
double speed_read_poly;
};
/* ************************************ */
static std::vector<Config> make_configs() {
std::vector<Config> configs;
configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1});
configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048});
return configs;
}
int main(int argc, char **argv)
{
nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite);
nix::Block block = fd.createBlock("speed", "nix.test");
std::vector<Config> configs = make_configs();
std::vector<Benchmark *> marks;
std::cout << "Performing generators tests..." << std::endl;
for (const Config &cfg : configs) {
GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing write tests..." << std::endl;
for (const Config &cfg : configs) {
WriteBenchmark *benchmark = new WriteBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing read tests..." << std::endl;
for (const Config &cfg : configs) {
ReadBenchmark *benchmark = new ReadBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing read (poly) tests..." << std::endl;
for (const Config &cfg : configs) {
ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << " === Reports ===" << std::endl;
for (Benchmark *mark : marks) {
mark->report();
delete mark;
}
return 0;
}
<commit_msg>[test] Benchmark: move report logic to main()<commit_after>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <cstdio>
#include <nix.hpp>
#include <nix/NDArray.hpp>
#include <queue>
#include <random>
#include <type_traits>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdexcept>
/* ************************************ */
class Stopwatch {
public:
typedef std::chrono::high_resolution_clock::time_point time_point_t;
typedef std::chrono::high_resolution_clock clock_t;
Stopwatch() : t_start(clock_t::now()) { };
ssize_t ms() {
time_point_t t_end = clock_t::now();
ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
return count;
}
private:
time_point_t t_start;
};
/* ************************************ */
class RndGenBase {
public:
RndGenBase() : rd(), rd_gen(rd()) { };
protected:
std::random_device rd;
std::mt19937 rd_gen;
};
template<typename T, typename Enable = void>
class RndGen { };
template<typename T>
class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase {
public:
RndGen() : dis(-1024.0, +1024.0) { };
T operator()(void) {
return dis(rd_gen);
};
private:
std::uniform_real_distribution<T> dis;
};
template<typename T>
class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase {
public:
RndGen() : dis(-1024, +1024) { };
T operator()(void) {
return dis(rd_gen);
};
private:
std::uniform_real_distribution<T> dis;
};
/* ************************************ */
template<typename T>
class BlockGenerator {
public:
BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };
std::vector<T> make_block() {
std::vector<T> block(blocksize);
std::generate(block.begin(), block.end(), std::ref(rnd_gen));
return block;
}
std::vector<T> next_block() {
std::unique_lock<std::mutex> lock(mtx);
if (queue.empty()) {
cnd.wait(lock, [this]{ return !queue.empty(); });
}
std::vector<T> x(std::move(queue.front()));
queue.pop();
cnd.notify_all();
return x;
}
void worker_thread() {
while (do_run) {
std::unique_lock<std::mutex> lock(mtx);
std::vector<T> block = make_block();
if (queue.size() > bufsize) {
//wait until there is room
cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});
if (!do_run) {
return;
}
}
queue.push(std::move(block));
cnd.notify_all();
}
}
void start_worker() {
workers.emplace_back(&BlockGenerator::worker_thread, this);
}
~BlockGenerator() {
do_run = false;
cnd.notify_all();
for (auto &w : workers) {
w.join();
}
}
double speed_test() {
Stopwatch sw;
size_t N = 100;
size_t iterations = 0;
do {
Stopwatch inner;
for (size_t i = 0; i < N; i++) {
std::vector<double> block = next_block();
iterations++;
}
if (inner.ms() < 100) {
N *= 2;
}
} while (sw.ms() < 1000);
ssize_t count = sw.ms();
return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0);
}
private:
bool do_run = true;
size_t blocksize;
size_t bufsize;
RndGen<T> rnd_gen;
std::mutex mtx;
std::condition_variable cnd;
std::queue<std::vector<T>> queue;
std::vector<std::thread> workers;
};
class Config {
public:
Config(nix::DataType data_type, const nix::NDSize &blocksize)
: data_type(data_type), block_size(blocksize) {
sdim = find_single_dim();
shape = blocksize;
shape[sdim] = 0;
make_name();
};
size_t find_single_dim() {
size_t sdim;
bool have_rdim = false;
for (size_t i = 0; i < block_size.size(); i ++) {
if (block_size[i] == 1) {
sdim = i;
have_rdim = true;
}
}
if (!have_rdim) {
throw std::runtime_error("Could not find singelton dimension");
}
return sdim;
}
nix::DataType dtype() const { return data_type; }
const nix::NDSize& size() const { return block_size; }
const nix::NDSize& extend() const { return shape; }
size_t singleton_dimension() const { return sdim; }
const std::string & name() const { return my_name; };
private:
void make_name() {
std::stringstream s;
s << data_type << "@{ ";
for (auto x : block_size) {
s << x << " ";
}
s << "}";
my_name = s.str();
}
private:
const nix::DataType data_type;
const nix::NDSize block_size;
size_t sdim;
nix::NDSize shape;
std::string my_name;
};
class Benchmark {
public:
Benchmark(const Config &cfg) : config(cfg) { }
const Config & cfg() const { return config; }
nix::DataArray openDataArray(nix::Block block) const {
const std::string &cfg_name = config.name();
std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name));
if (v.empty()) {
return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend());
} else {
return v[0];
}
}
virtual ~Benchmark() { }
virtual double speed_in_mbs() {
return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) *
(1000.0/millis) / (1024 * 1024);
}
template<typename F>
ssize_t time_it(F func) {
Stopwatch watch;
func();
return watch.ms();
}
virtual void run(nix::Block block) = 0;
virtual std::string id() = 0;
protected:
double calc_speed_mbs(ssize_t ms, size_t iterations) {
return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) /
(1024.0*1024.0);
}
protected:
const Config config;
size_t count;
double millis;
};
class GeneratorBenchmark : public Benchmark {
public:
GeneratorBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void run(nix::Block block) override {
switch (config.dtype()) {
case nix::DataType::Double:
test_speed<double>();
break;
default:
throw std::runtime_error("Unsupported DataType!");
}
}
template<typename T>
void test_speed() {
size_t nelms = config.size().nelms();
BlockGenerator<T> generator(nelms, 10);
generator.start_worker();
speed = generator.speed_test();
}
double speed_in_mbs() override {
return speed;
}
std::string id() override {
return "P";
}
private:
double speed;
};
class WriteBenchmark : public Benchmark {
public:
WriteBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void test_write_io(nix::Block block) {
nix::DataArray da = openDataArray(block);
switch (config.dtype()) {
case nix::DataType::Double:
do_write_test<double>(da);
break;
default:
throw std::runtime_error("Unsupported DataType!");
}
}
void run(nix::Block block) override {
test_write_io(block);
}
double speed_in_mbs() override {
return speed_write;
}
std::string id() override {
return "W";
}
private:
template<typename T>
void do_write_test(nix::DataArray da) {
size_t nelms = config.size().nelms();
BlockGenerator<T> generator(nelms, 10);
generator.start_worker();
size_t N = 100;
size_t iterations = 0;
nix::NDSize pos = {0, 0};
Stopwatch sw;
ssize_t ms = 0;
do {
Stopwatch inner;
for (size_t i = 0; i < N; i++) {
std::vector<T> block = generator.next_block();
da.dataExtent(config.size() + pos);
da.setData(config.dtype(), block.data(), config.size(), pos);
pos[config.singleton_dimension()] += 1;
iterations++;
}
if (inner.ms() < 100) {
N *= 2;
}
} while ((ms = sw.ms()) < 3*1000);
speed_write = calc_speed_mbs(ms, iterations);
}
private:
double speed_write;
};
class ReadBenchmark : public Benchmark {
public:
ReadBenchmark(const Config &cfg)
: Benchmark(cfg) {
};
void test_read_io(nix::Block block) {
nix::DataArray da = openDataArray(block);
speed_read = test_read_io(da);
}
double test_read_io(nix::DataArray da) {
nix::NDArray array(config.dtype(), config.size());
nix::NDSize extend = da.dataExtent();
size_t N = extend[config.singleton_dimension()];
nix::NDSize pos = {0, 0};
ssize_t ms = time_it([this, &da, &N, &pos, &array] {
for(size_t i = 0; i < N; i++) {
da.getData(config.dtype(), array.data(), config.size(), pos);
pos[config.singleton_dimension()] += 1;
}
});
return calc_speed_mbs(ms, N);
}
void run(nix::Block block) override {
test_read_io(block);
}
double speed_in_mbs() override {
return speed_read;
}
std::string id() override {
return "R";
}
private:
double speed_read;
};
class ReadPolyBenchmark : public ReadBenchmark {
public:
ReadPolyBenchmark(const Config &cfg)
: ReadBenchmark(cfg) {
};
void test_read_io_polynom(nix::Block block) {
nix::DataArray da = openDataArray(block);
da.polynomCoefficients({3, 4, 5, 6});
speed_read_poly = test_read_io(da);
}
void run(nix::Block block) override {
test_read_io_polynom(block);
}
double speed_in_mbs() override {
return speed_read_poly;
}
std::string id() override {
return "P";
}
private:
double speed_read_poly;
};
/* ************************************ */
static std::vector<Config> make_configs() {
std::vector<Config> configs;
configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1});
configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048});
return configs;
}
int main(int argc, char **argv)
{
nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite);
nix::Block block = fd.createBlock("speed", "nix.test");
std::vector<Config> configs = make_configs();
std::vector<Benchmark *> marks;
std::cout << "Performing generators tests..." << std::endl;
for (const Config &cfg : configs) {
GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing write tests..." << std::endl;
for (const Config &cfg : configs) {
WriteBenchmark *benchmark = new WriteBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing read tests..." << std::endl;
for (const Config &cfg : configs) {
ReadBenchmark *benchmark = new ReadBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << "Performing read (poly) tests..." << std::endl;
for (const Config &cfg : configs) {
ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg);
benchmark->run(block);
marks.push_back(benchmark);
}
std::cout << " === Reports ===" << std::endl;
for (Benchmark *mark : marks) {
std::cout << mark->cfg().name() << ", " << mark->id() << ", "
<< mark->speed_in_mbs() << " MB/s" << std::endl;
delete mark;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_
#include <string>
#include <vector>
#include "clustering/administration/issues/issue.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
class local_issue_aggregator_t;
class local_issues_t;
class local_issue_t : public issue_t {
public:
local_issue_t();
local_issue_t(const issue_id_t &id);
virtual ~local_issue_t();
void add_server(const machine_id_t &server);
std::vector<machine_id_t> affected_server_ids;
};
class local_issue_tracker_t {
public:
explicit local_issue_tracker_t(local_issue_aggregator_t *_parent);
protected:
// This is a little wonky, but enforces the interface we want.
// The update_fn argument takes a pointer to the existing local_issues
// and should modify it appropriately
void update_issues(std::function<bool(local_issues_t*)> update_fn);
private:
local_issue_aggregator_t *parent;
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_ */
<commit_msg>fixing style<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_
#include <string>
#include <vector>
#include "clustering/administration/issues/issue.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
class local_issue_aggregator_t;
class local_issues_t;
class local_issue_t : public issue_t {
public:
local_issue_t();
explicit local_issue_t(const issue_id_t &id);
virtual ~local_issue_t();
void add_server(const machine_id_t &server);
std::vector<machine_id_t> affected_server_ids;
};
class local_issue_tracker_t {
public:
explicit local_issue_tracker_t(local_issue_aggregator_t *_parent);
protected:
// This is a little wonky, but enforces the interface we want.
// The update_fn argument takes a pointer to the existing local_issues
// and should modify it appropriately
void update_issues(std::function<bool(local_issues_t*)> update_fn);
private:
local_issue_aggregator_t *parent;
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_HPP_ */
<|endoftext|> |
<commit_before>/*****************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: RooFitTools
* File: $Id: RooGaussian.cc,v 1.11 2001/10/03 16:17:56 verkerke Exp $
* Authors:
* DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu
* History:
* 05-Jan-2000 DK Created initial version from RooGaussianProb
* 02-May-2001 WV Port to RooFitModels/RooFitCore
*
* Copyright (C) 1999 Stanford University
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
#include "BaBar/BaBar.hh"
#include <iostream.h>
#include <math.h>
#include "RooFitModels/RooGaussian.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRandom.hh"
ClassImp(RooGaussian)
RooGaussian::RooGaussian(const char *name, const char *title,
RooAbsReal& _x, RooAbsReal& _mean,
RooAbsReal& _sigma) :
RooAbsPdf(name,title),
x("x","Dependent",this,_x),
mean("mean","Mean",this,_mean),
sigma("sigma","Width",this,_sigma)
{
}
RooGaussian::RooGaussian(const RooGaussian& other, const char* name) :
RooAbsPdf(other,name), x("x",this,other.x), mean("mean",this,other.mean),
sigma("sigma",this,other.sigma)
{
}
Double_t RooGaussian::evaluate() const
{
Double_t arg= x - mean;
return exp(-0.5*arg*arg/(sigma*sigma)) ;
}
Int_t RooGaussian::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
if (matchArgs(allVars,analVars,x)) return 1 ;
return 0 ;
}
Double_t RooGaussian::analyticalIntegral(Int_t code) const
{
assert(code==1) ;
static Double_t root2 = sqrt(2) ;
static Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)/2.0);
Double_t xscale = root2*sigma;
return rootPiBy2*sigma*(erf((x.max()-mean)/xscale)-erf((x.min()-mean)/xscale));
}
Int_t RooGaussian::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars) const
{
//if (matchArgs(directVars,generateVars,x)) return 1 ;
return 0 ;
}
void RooGaussian::generateEvent(Int_t code)
{
assert(code==1) ;
Double_t xgen ;
while(1) {
xgen = RooRandom::randomGenerator()->Gaus(mean,sigma);
if (xgen<x.max() && xgen>x.min()) {
x = xgen ;
return ;
}
}
}
<commit_msg>RooGaussian:<commit_after>/*****************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: RooFitTools
* File: $Id: RooGaussian.cc,v 1.12 2001/10/08 05:21:19 verkerke Exp $
* Authors:
* DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu
* History:
* 05-Jan-2000 DK Created initial version from RooGaussianProb
* 02-May-2001 WV Port to RooFitModels/RooFitCore
*
* Copyright (C) 1999 Stanford University
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
#include "BaBar/BaBar.hh"
#include <iostream.h>
#include <math.h>
#include "RooFitModels/RooGaussian.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRandom.hh"
ClassImp(RooGaussian)
RooGaussian::RooGaussian(const char *name, const char *title,
RooAbsReal& _x, RooAbsReal& _mean,
RooAbsReal& _sigma) :
RooAbsPdf(name,title),
x("x","Dependent",this,_x),
mean("mean","Mean",this,_mean),
sigma("sigma","Width",this,_sigma)
{
}
RooGaussian::RooGaussian(const RooGaussian& other, const char* name) :
RooAbsPdf(other,name), x("x",this,other.x), mean("mean",this,other.mean),
sigma("sigma",this,other.sigma)
{
}
Double_t RooGaussian::evaluate() const
{
Double_t arg= x - mean;
return exp(-0.5*arg*arg/(sigma*sigma)) ;
}
Int_t RooGaussian::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
if (matchArgs(allVars,analVars,x)) return 1 ;
return 0 ;
}
Double_t RooGaussian::analyticalIntegral(Int_t code) const
{
assert(code==1) ;
static const Double_t root2 = sqrt(2) ;
static const Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)/2.0);
Double_t xscale = root2*sigma;
return rootPiBy2*sigma*(erf((x.max()-mean)/xscale)-erf((x.min()-mean)/xscale));
}
Int_t RooGaussian::getGenerator(const RooArgSet& directVars, RooArgSet &generateVars) const
{
return (matchArgs(directVars,generateVars,x)) ? 1 : 0;
}
void RooGaussian::generateEvent(Int_t code)
{
assert(code==1) ;
Double_t xgen ;
while(1) {
xgen = RooRandom::randomGenerator()->Gaus(mean,sigma);
if (xgen<x.max() && xgen>x.min()) {
x = xgen ;
break;
}
}
return;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories
// for implementing this test.
#include "vtkDoubleArray.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkDescriptiveStatistics.h"
//=============================================================================
int TestDescriptiveStatistics( int, char *[] )
{
int testStatus = 0;
double mingledData[] =
{
46,
45,
47,
49,
46,
47,
46,
46,
47,
46,
47,
49,
49,
49,
47,
45,
50,
50,
46,
46,
51,
50,
48,
48,
52,
54,
48,
47,
52,
52,
49,
49,
53,
54,
50,
50,
53,
54,
50,
52,
53,
53,
50,
51,
54,
54,
49,
49,
52,
52,
50,
51,
52,
52,
49,
47,
48,
48,
48,
50,
46,
48,
47,
47,
};
int nVals = 32;
vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Metric 0" );
vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Metric 1" );
vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Metric 2" );
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 1;
dataset1Arr->InsertNextValue( mingledData[ti] );
dataset2Arr->InsertNextValue( mingledData[ti + 1] );
dataset3Arr->InsertNextValue( -1. );
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
int nMetrics = 3;
vtkStdString columns[] = { "Metric 1", "Metric 2", "Metric 0" };
double means[] = { 49.5, -1., 49.2188 };
double stdevs[] = { sqrt( 7.54839 ), 0., sqrt( 5.98286 ) };
vtkDescriptiveStatistics* haruspex = vtkDescriptiveStatistics::New();
haruspex->SetInput( 0, datasetTable );
vtkTable* outputData = haruspex->GetOutput( 0 );
vtkTable* outputMeta = haruspex->GetOutput( 1 );
datasetTable->Delete();
// -- Select Columns of Interest --
haruspex->AddColumn( "Metric 3" ); // Include invalid Metric 3
haruspex->AddColumn( "Metric 4" ); // Include invalid Metric 4
for ( int i = 0; i< nMetrics; ++ i )
{ // Try to add all valid indices once more
haruspex->AddColumn( columns[i] );
}
haruspex->RemoveColumn( "Metric 3" ); // Remove invalid Metric 3 (but keep 4)
// -- Test Learn and Assess Modes --
haruspex->SetLearn( true );
haruspex->SetDerive( true );
haruspex->SetAssess( true );
haruspex->SignedDeviationsOff();
haruspex->Update();
vtkIdType n = haruspex->GetSampleSize();
cout << "## Calculated the following statistics ( "
<< n
<< " entries per column ):\n";
for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
{
cout << " ";
for ( int i = 0; i < outputMeta->GetNumberOfColumns(); ++ i )
{
cout << outputMeta->GetColumnName( i )
<< "="
<< outputMeta->GetValue( r, i ).ToString()
<< " ";
}
if ( fabs ( outputMeta->GetValueByName( r, "Mean" ).ToDouble() - means[r] ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect mean");
testStatus = 1;
}
if ( fabs ( outputMeta->GetValueByName( r, "Standard Deviation" ).ToDouble() - stdevs[r] ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect standard deviation");
testStatus = 1;
}
cout << "\n";
}
cout << "## Searching for outliers:\n";
int m0outliers = 0;
int m1outliers = 0;
cout << "Outliers:\n";
vtkDoubleArray* m0reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 0)" ) );
vtkDoubleArray* m1reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 1)" ) );
vtkDoubleArray* m0vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 0" ) );
vtkDoubleArray* m1vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 1" ) );
if ( ! m0reld || ! m1reld || ! m0vals || ! m1vals )
{
vtkGenericWarningMacro("Empty output column(s).\n");
testStatus = 1;
return testStatus;
}
double dev;
double maxdev = 1.5;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m0reld->GetValue( r );
if ( dev > maxdev )
{
++ m0outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m0reld->GetName()
<< " = "
<< dev
<< " > "
<< maxdev
<< " (value: "
<< m0vals->GetValue( r )
<< ")\n";
}
}
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m1reld->GetValue( r );
if ( dev > maxdev )
{
++ m1outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m1reld->GetName()
<< " = "
<< dev
<< " > "
<< maxdev
<< " (value: "
<< m1vals->GetValue( r )
<< ")\n";
}
}
cout
<< "Found " << m0outliers << " outliers for Metric 0"
<< " and " << m1outliers << " outliers for Metric 1.\n";
if ( m0outliers != 4 || m1outliers != 6 )
{
vtkGenericWarningMacro("Expected 4 outliers for Metric 0 and 6 outliers for Metric 1.");
testStatus = 1;
}
// -- Used modified output 1 as input 1 to test 0-deviation --
cout << "Re-running with mean 50 and deviation 0 for metric 1:\n";
vtkTable* paramsTable = vtkTable::New();
paramsTable->ShallowCopy( outputMeta );
paramsTable->SetValueByName( 1, "Standard Deviation", 0. );
paramsTable->SetValueByName( 1, "Mean", 50. );
haruspex->SetInput( 1, paramsTable );
haruspex->SetLearn( false );
haruspex->SetDerive( false ); // Do not recalculate nor rederive a model
haruspex->SetAssess( true );
haruspex->Update();
m1vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 1" ) );
m1reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 1)" ) );
if ( ! m1reld || ! m1vals )
{
vtkGenericWarningMacro("Empty output column(s).\n");
testStatus = 1;
return testStatus;
}
m1outliers = 0;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m1reld->GetValue( r );
if ( dev )
{
++ m1outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m1reld->GetName()
<< " = "
<< dev
<< " (value: "
<< m1vals->GetValue( r )
<< ")\n";
}
}
if ( m1outliers != 28 )
{
vtkGenericWarningMacro("Expected 28 outliers for Metric 1, found " << m1outliers << ".");
testStatus = 1;
}
paramsTable->Delete();
haruspex->Delete();
return testStatus;
}
<commit_msg>ENH: added a test for comparison vs. R baseline<commit_after>/*
* Copyright 2008 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories
// for implementing this test.
#include "vtkDoubleArray.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkDescriptiveStatistics.h"
//=============================================================================
int TestDescriptiveStatistics( int, char *[] )
{
int testStatus = 0;
// ************** More complex example comprising three columns **************
double mingledData[] =
{
46,
45,
47,
49,
46,
47,
46,
46,
47,
46,
47,
49,
49,
49,
47,
45,
50,
50,
46,
46,
51,
50,
48,
48,
52,
54,
48,
47,
52,
52,
49,
49,
53,
54,
50,
50,
53,
54,
50,
52,
53,
53,
50,
51,
54,
54,
49,
49,
52,
52,
50,
51,
52,
52,
49,
47,
48,
48,
48,
50,
46,
48,
47,
47,
};
int nVals = 32;
vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Metric 0" );
vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Metric 1" );
vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Metric 2" );
cout << "## Input data set:\n";
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 1;
dataset1Arr->InsertNextValue( mingledData[ti] );
dataset2Arr->InsertNextValue( mingledData[ti + 1] );
dataset3Arr->InsertNextValue( -1. );
cout << " "
<< mingledData[ti]
<< "\t"
<< mingledData[ti + 1]
<< "\t"
<< -1.
<< "\n";
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
int nMetrics = 3;
vtkStdString columns[] = { "Metric 1", "Metric 2", "Metric 0" };
double means[] = { 49.5, -1., 49.2188 };
double stdevs[] = { sqrt( 7.54839 ), 0., sqrt( 5.98286 ) };
vtkDescriptiveStatistics* haruspex = vtkDescriptiveStatistics::New();
haruspex->SetInput( 0, datasetTable );
vtkTable* outputData = haruspex->GetOutput( 0 );
vtkTable* outputMeta = haruspex->GetOutput( 1 );
datasetTable->Delete();
// -- Select Columns of Interest --
haruspex->AddColumn( "Metric 3" ); // Include invalid Metric 3
haruspex->AddColumn( "Metric 4" ); // Include invalid Metric 4
for ( int i = 0; i< nMetrics; ++ i )
{ // Try to add all valid indices once more
haruspex->AddColumn( columns[i] );
}
haruspex->RemoveColumn( "Metric 3" ); // Remove invalid Metric 3 (but keep 4)
// -- Test Learn and Assess Modes --
haruspex->SetLearn( true );
haruspex->SetDerive( true );
haruspex->SetAssess( true );
haruspex->SignedDeviationsOff();
haruspex->Update();
vtkIdType n = haruspex->GetSampleSize();
cout << "## Calculated the following statistics ( "
<< n
<< " entries per column ):\n";
for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
{
cout << " ";
for ( int i = 0; i < outputMeta->GetNumberOfColumns(); ++ i )
{
cout << outputMeta->GetColumnName( i )
<< "="
<< outputMeta->GetValue( r, i ).ToString()
<< " ";
}
if ( fabs ( outputMeta->GetValueByName( r, "Mean" ).ToDouble() - means[r] ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect mean");
testStatus = 1;
}
if ( fabs ( outputMeta->GetValueByName( r, "Standard Deviation" ).ToDouble() - stdevs[r] ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect standard deviation");
testStatus = 1;
}
cout << "\n";
}
cout << "## Searching for outliers:\n";
int m0outliers = 0;
int m1outliers = 0;
cout << "Outliers:\n";
vtkDoubleArray* m0reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 0)" ) );
vtkDoubleArray* m1reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 1)" ) );
vtkDoubleArray* m0vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 0" ) );
vtkDoubleArray* m1vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 1" ) );
if ( ! m0reld || ! m1reld || ! m0vals || ! m1vals )
{
vtkGenericWarningMacro("Empty output column(s).\n");
testStatus = 1;
return testStatus;
}
double dev;
double maxdev = 1.5;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m0reld->GetValue( r );
if ( dev > maxdev )
{
++ m0outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m0reld->GetName()
<< " = "
<< dev
<< " > "
<< maxdev
<< " (value: "
<< m0vals->GetValue( r )
<< ")\n";
}
}
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m1reld->GetValue( r );
if ( dev > maxdev )
{
++ m1outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m1reld->GetName()
<< " = "
<< dev
<< " > "
<< maxdev
<< " (value: "
<< m1vals->GetValue( r )
<< ")\n";
}
}
cout
<< "Found " << m0outliers << " outliers for Metric 0"
<< " and " << m1outliers << " outliers for Metric 1.\n";
if ( m0outliers != 4 || m1outliers != 6 )
{
vtkGenericWarningMacro("Expected 4 outliers for Metric 0 and 6 outliers for Metric 1.");
testStatus = 1;
}
// -- Used modified output 1 as input 1 to test 0-deviation --
cout << "Re-running with mean 50 and deviation 0 for metric 1:\n";
vtkTable* paramsTable = vtkTable::New();
paramsTable->ShallowCopy( outputMeta );
paramsTable->SetValueByName( 1, "Standard Deviation", 0. );
paramsTable->SetValueByName( 1, "Mean", 50. );
haruspex->SetInput( 1, paramsTable );
haruspex->SetLearn( false );
haruspex->SetDerive( false ); // Do not recalculate nor rederive a model
haruspex->SetAssess( true );
haruspex->Update();
m1vals = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "Metric 1" ) );
m1reld = vtkDoubleArray::SafeDownCast(
outputData->GetColumnByName( "d(Metric 1)" ) );
if ( ! m1reld || ! m1vals )
{
vtkGenericWarningMacro("Empty output column(s).\n");
testStatus = 1;
return testStatus;
}
m1outliers = 0;
for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
{
dev = m1reld->GetValue( r );
if ( dev )
{
++ m1outliers;
cout << " "
<< " row "
<< r
<< ", "
<< m1reld->GetName()
<< " = "
<< dev
<< " (value: "
<< m1vals->GetValue( r )
<< ")\n";
}
}
if ( m1outliers != 28 )
{
vtkGenericWarningMacro("Expected 28 outliers for Metric 1, found " << m1outliers << ".");
testStatus = 1;
}
paramsTable->Delete();
haruspex->Delete();
// ************** Very simple example, for baseline comparison vs. R *********
double simpleData[] =
{
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
int nSimpleVals = 10;
vtkDoubleArray* datasetArr = vtkDoubleArray::New();
datasetArr->SetNumberOfComponents( 1 );
datasetArr->SetName( "Metric" );
cout << "## Input data set:\n";
for ( int i = 0; i < nSimpleVals; ++ i )
{
datasetArr->InsertNextValue( simpleData[i] );
cout << " "
<< simpleData[i]
<< "\n";
}
vtkTable* simpleTable = vtkTable::New();
simpleTable->AddColumn( datasetArr );
datasetArr->Delete();
double mean = 4.5;
double variance = 9.16666666666667;
double g1 = 0.;
double g2 = -1.56163636363636;
vtkDescriptiveStatistics* ds = vtkDescriptiveStatistics::New();
ds->SetInput( 0, simpleTable );
vtkTable* outputSimpleMeta = ds->GetOutput( 1 );
simpleTable->Delete();
// -- Select Column of Interest --
ds->AddColumn( "Metric" );
// -- Test Learn and Derive only --
ds->SetLearn( true );
ds->SetDerive( true );
ds->SetAssess( false );
ds->Update();
cout << "## Calculated the following statistics ( "
<< ds->GetSampleSize()
<< " entries in a single column ):\n"
<< " ";
for ( int i = 0; i < outputSimpleMeta->GetNumberOfColumns(); ++ i )
{
cout << outputSimpleMeta->GetColumnName( i )
<< "="
<< outputSimpleMeta->GetValue( 0, i ).ToString()
<< " ";
}
if ( fabs ( outputSimpleMeta->GetValueByName( r, "Mean" ).ToDouble() - mean ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect mean");
testStatus = 1;
}
if ( fabs ( outputSimpleMeta->GetValueByName( r, "Variance" ).ToDouble() - variance ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect variance");
testStatus = 1;
}
cout << "\n";
if ( fabs ( outputSimpleMeta->GetValueByName( r, "G1 Skewness" ).ToDouble() - g1 ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect G1 skewness");
testStatus = 1;
}
cout << "\n";
if ( fabs ( outputSimpleMeta->GetValueByName( r, "G2 Kurtosis" ).ToDouble() - g2 ) > 1.e6 )
{
vtkGenericWarningMacro("Incorrect G2 kurtosis");
testStatus = 1;
}
cout << "\n";
ds->Delete();
return testStatus;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "cyber/cyber.h"
#include "cyber/record/record_reader.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/util/message_util.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
using cyber::record::RecordMessage;
using cyber::record::RecordReader;
PredictionComponent::~PredictionComponent() { Stop(); }
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
RecordReader reader(filename);
RecordMessage message;
while (reader.ReadMessage(&message)) {
if (message.channel_name == FLAGS_perception_obstacle_topic) {
PerceptionObstacles perception_obstacles;
if (perception_obstacles.ParseFromString(message.content)) {
OnPerception(perception_obstacles);
}
} else if (message.channel_name == FLAGS_localization_topic) {
LocalizationEstimate localization;
if (localization.ParseFromString(message.content)) {
OnLocalization(localization);
}
} else if (message.channel_name == FLAGS_planning_trajectory_topic) {
ADCTrajectory adc_trajectory;
if (adc_trajectory.ParseFromString(message.content)) {
OnPlanning(adc_trajectory);
}
}
}
}
bool PredictionComponent::Init() {
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
planning_reader_ = node_->CreateReader<ADCTrajectory>(
FLAGS_planning_trajectory_topic, nullptr);
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
prediction_writer_ =
node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::Split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
}
return true;
}
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
AINFO << "write when stop";
FeatureOutput::Close();
}
apollo::cyber::Shutdown();
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
if (!pose_container) {
return;
}
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
if (!adc_trajectory_container) {
return;
}
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message ["
<< adc_trajectory.ShortDebugString() << "].";
}
void PredictionComponent::OnPerception(
const PerceptionObstacles& perception_obstacles) {
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
if (!obstacles_container) {
return;
}
obstacles_container->Insert(perception_obstacles);
const auto& adc_trajectory_msg = planning_reader_->GetLatestObserved();
if (adc_trajectory_msg != nullptr) {
OnPlanning(*adc_trajectory_msg);
}
// Scenario analysis
// ScenarioManager::Instance()->Run();
const Scenario& scenario = ScenarioManager::Instance()->scenario();
if (scenario.type() == Scenario::JUNCTION && scenario.has_junction_id()) {
JunctionAnalyzer::Init(scenario.junction_id());
obstacles_container->BuildJunctionFeature();
}
// TODO(kechxu) refactor logic of build lane graph and build junction feature
// Set up obstacle cluster
obstacles_container->BuildLaneGraph();
ADEBUG << "Received a perception message ["
<< perception_obstacles.ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
if (!pose_container || !adc_container) {
return;
}
const PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return;
}
// Make predictions
PredictorManager::Instance()->Run(perception_obstacles);
// Get predicted obstacles
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(frame_start_time_);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles.header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles.header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles.header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return;
}
}
}
}
}
// Publish output
common::util::FillHeader(node_->Name(), &prediction_obstacles);
prediction_writer_->Write(
std::make_shared<PredictionObstacles>(prediction_obstacles));
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_ >
FLAGS_prediction_test_duration)) {
ADEBUG << "Prediction finished running in test mode";
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
frame_start_time_ = Clock::NowInSeconds();
OnLocalization(*localization);
OnPerception(*perception_obstacles);
return true;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: recover scenario manager<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "cyber/cyber.h"
#include "cyber/record/record_reader.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/util/message_util.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
using cyber::record::RecordMessage;
using cyber::record::RecordReader;
PredictionComponent::~PredictionComponent() { Stop(); }
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
RecordReader reader(filename);
RecordMessage message;
while (reader.ReadMessage(&message)) {
if (message.channel_name == FLAGS_perception_obstacle_topic) {
PerceptionObstacles perception_obstacles;
if (perception_obstacles.ParseFromString(message.content)) {
OnPerception(perception_obstacles);
}
} else if (message.channel_name == FLAGS_localization_topic) {
LocalizationEstimate localization;
if (localization.ParseFromString(message.content)) {
OnLocalization(localization);
}
} else if (message.channel_name == FLAGS_planning_trajectory_topic) {
ADCTrajectory adc_trajectory;
if (adc_trajectory.ParseFromString(message.content)) {
OnPlanning(adc_trajectory);
}
}
}
}
bool PredictionComponent::Init() {
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
planning_reader_ = node_->CreateReader<ADCTrajectory>(
FLAGS_planning_trajectory_topic, nullptr);
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
prediction_writer_ =
node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::Split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
}
return true;
}
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
AINFO << "write when stop";
FeatureOutput::Close();
}
apollo::cyber::Shutdown();
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
if (!pose_container) {
return;
}
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
if (!adc_trajectory_container) {
return;
}
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message ["
<< adc_trajectory.ShortDebugString() << "].";
}
void PredictionComponent::OnPerception(
const PerceptionObstacles& perception_obstacles) {
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
if (!obstacles_container) {
return;
}
obstacles_container->Insert(perception_obstacles);
const auto& adc_trajectory_msg = planning_reader_->GetLatestObserved();
if (adc_trajectory_msg != nullptr) {
OnPlanning(*adc_trajectory_msg);
}
// Scenario analysis
ScenarioManager::Instance()->Run();
const Scenario& scenario = ScenarioManager::Instance()->scenario();
if (scenario.type() == Scenario::JUNCTION && scenario.has_junction_id()) {
JunctionAnalyzer::Init(scenario.junction_id());
obstacles_container->BuildJunctionFeature();
}
// TODO(kechxu) refactor logic of build lane graph and build junction feature
// Set up obstacle cluster
obstacles_container->BuildLaneGraph();
ADEBUG << "Received a perception message ["
<< perception_obstacles.ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
if (!pose_container || !adc_container) {
return;
}
const PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return;
}
// Make predictions
PredictorManager::Instance()->Run(perception_obstacles);
// Get predicted obstacles
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(frame_start_time_);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles.header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles.header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles.header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return;
}
}
}
}
}
// Publish output
common::util::FillHeader(node_->Name(), &prediction_obstacles);
prediction_writer_->Write(
std::make_shared<PredictionObstacles>(prediction_obstacles));
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_ >
FLAGS_prediction_test_duration)) {
ADEBUG << "Prediction finished running in test mode";
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
frame_start_time_ = Clock::NowInSeconds();
OnLocalization(*localization);
OnPerception(*perception_obstacles);
return true;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface to a pass that merges duplicate global
// constants together into a single constant that is shared. This is useful
// because some passes (ie TraceValues) insert a lot of string constants into
// the program, regardless of whether or not an existing string is available.
//
// Algorithm: ConstantMerge is designed to build up a map of available constants
// and eliminate duplicates when it is initialized.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/ConstantMerge.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Transforms/IPO.h"
#include <algorithm>
#include <cassert>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "constmerge"
STATISTIC(NumMerged, "Number of global constants merged");
/// Find values that are marked as llvm.used.
static void FindUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
if (!LLVMUsed) return;
ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
GlobalValue *GV = cast<GlobalValue>(Operand);
UsedValues.insert(GV);
}
}
// True if A is better than B.
static bool IsBetterCanonical(const GlobalVariable &A,
const GlobalVariable &B) {
if (!A.hasLocalLinkage() && B.hasLocalLinkage())
return true;
if (A.hasLocalLinkage() && !B.hasLocalLinkage())
return false;
return A.hasGlobalUnnamedAddr();
}
static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV) {
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
GV->getAllMetadata(MDs);
for (const auto &V : MDs)
if (V.first != LLVMContext::MD_dbg)
return true;
return false;
}
static void copyDebugLocMetadata(const GlobalVariable *From,
GlobalVariable *To) {
SmallVector<DIGlobalVariableExpression *, 1> MDs;
From->getDebugInfo(MDs);
for (auto MD : MDs)
To->addDebugInfo(MD);
}
static unsigned getAlignment(GlobalVariable *GV) {
unsigned Align = GV->getAlignment();
if (Align)
return Align;
return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
}
static bool mergeConstants(Module &M) {
// Find all the globals that are marked "used". These cannot be merged.
SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
// Map unique constants to globals.
DenseMap<Constant *, GlobalVariable *> CMap;
// Replacements - This vector contains a list of replacements to perform.
SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
bool MadeChange = false;
// Iterate constant merging while we are still making progress. Merging two
// constants together may allow us to merge other constants together if the
// second level constants have initializers which point to the globals that
// were just merged.
while (true) {
// First: Find the canonical constants others will be merged with.
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = &*GVI++;
// If this GV is dead, remove it.
GV->removeDeadConstantUsers();
if (GV->use_empty() && GV->hasLocalLinkage()) {
GV->eraseFromParent();
continue;
}
// Only process constants with initializers in the default address space.
if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
// Don't touch values marked with attribute(used).
UsedGlobals.count(GV))
continue;
// This transformation is legal for weak ODR globals in the sense it
// doesn't change semantics, but we really don't want to perform it
// anyway; it's likely to pessimize code generation, and some tools
// (like the Darwin linker in cases involving CFString) don't expect it.
if (GV->isWeakForLinker())
continue;
// Don't touch globals with metadata other then !dbg.
if (hasMetadataOtherThanDebugLoc(GV))
continue;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known.
GlobalVariable *&Slot = CMap[Init];
// If this is the first constant we find or if the old one is local,
// replace with the current one. If the current is externally visible
// it cannot be replace, but can be the canonical constant we merge with.
if (!Slot || IsBetterCanonical(*GV, *Slot))
Slot = GV;
}
// Second: identify all globals that can be merged together, filling in
// the Replacements vector. We cannot do the replacement in this pass
// because doing so may cause initializers of other globals to be rewritten,
// invalidating the Constant* pointers in CMap.
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = &*GVI++;
// Only process constants with initializers in the default address space.
if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
// Don't touch values marked with attribute(used).
UsedGlobals.count(GV))
continue;
// We can only replace constant with local linkage.
if (!GV->hasLocalLinkage())
continue;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known.
auto Found = CMap.find(Init);
if (Found == CMap.end())
continue;
GlobalVariable *Slot = Found->second;
if (Slot == GV)
continue;
if (!Slot->hasGlobalUnnamedAddr() && !GV->hasGlobalUnnamedAddr())
continue;
if (hasMetadataOtherThanDebugLoc(GV))
continue;
if (!GV->hasGlobalUnnamedAddr())
Slot->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
// Make all uses of the duplicate constant use the canonical version.
Replacements.push_back(std::make_pair(GV, Slot));
}
if (Replacements.empty())
return MadeChange;
CMap.clear();
// Now that we have figured out which replacements must be made, do them all
// now. This avoid invalidating the pointers in CMap, which are unneeded
// now.
for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
// Bump the alignment if necessary.
if (Replacements[i].first->getAlignment() ||
Replacements[i].second->getAlignment()) {
Replacements[i].second->setAlignment(
std::max(getAlignment(Replacements[i].first),
getAlignment(Replacements[i].second)));
}
copyDebugLocMetadata(Replacements[i].first, Replacements[i].second);
// Eliminate any uses of the dead global.
Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
// Delete the global value from the module.
assert(Replacements[i].first->hasLocalLinkage() &&
"Refusing to delete an externally visible global variable.");
Replacements[i].first->eraseFromParent();
MadeChange = true;
}
NumMerged += Replacements.size();
Replacements.clear();
}
}
PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {
if (!mergeConstants(M))
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}
namespace {
struct ConstantMergeLegacyPass : public ModulePass {
static char ID; // Pass identification, replacement for typeid
ConstantMergeLegacyPass() : ModulePass(ID) {
initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
}
// For this pass, process all of the globals in the module, eliminating
// duplicate constants.
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
return mergeConstants(M);
}
};
} // end anonymous namespace
char ConstantMergeLegacyPass::ID = 0;
INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
"Merge Duplicate Global Constants", false, false)
ModulePass *llvm::createConstantMergePass() {
return new ConstantMergeLegacyPass();
}
<commit_msg>ConstantMerge: factor out some functions<commit_after>//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface to a pass that merges duplicate global
// constants together into a single constant that is shared. This is useful
// because some passes (ie TraceValues) insert a lot of string constants into
// the program, regardless of whether or not an existing string is available.
//
// Algorithm: ConstantMerge is designed to build up a map of available constants
// and eliminate duplicates when it is initialized.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/ConstantMerge.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Transforms/IPO.h"
#include <algorithm>
#include <cassert>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "constmerge"
STATISTIC(NumMerged, "Number of global constants merged");
/// Find values that are marked as llvm.used.
static void FindUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
if (!LLVMUsed) return;
ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
GlobalValue *GV = cast<GlobalValue>(Operand);
UsedValues.insert(GV);
}
}
// True if A is better than B.
static bool IsBetterCanonical(const GlobalVariable &A,
const GlobalVariable &B) {
if (!A.hasLocalLinkage() && B.hasLocalLinkage())
return true;
if (A.hasLocalLinkage() && !B.hasLocalLinkage())
return false;
return A.hasGlobalUnnamedAddr();
}
static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV) {
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
GV->getAllMetadata(MDs);
for (const auto &V : MDs)
if (V.first != LLVMContext::MD_dbg)
return true;
return false;
}
static void copyDebugLocMetadata(const GlobalVariable *From,
GlobalVariable *To) {
SmallVector<DIGlobalVariableExpression *, 1> MDs;
From->getDebugInfo(MDs);
for (auto MD : MDs)
To->addDebugInfo(MD);
}
static unsigned getAlignment(GlobalVariable *GV) {
unsigned Align = GV->getAlignment();
if (Align)
return Align;
return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
}
enum class CanMerge { No, Yes };
static CanMerge makeMergeable(GlobalVariable *Old, GlobalVariable *New) {
if (!Old->hasGlobalUnnamedAddr() && !New->hasGlobalUnnamedAddr())
return CanMerge::No;
if (hasMetadataOtherThanDebugLoc(Old))
return CanMerge::No;
assert(!hasMetadataOtherThanDebugLoc(New));
if (!Old->hasGlobalUnnamedAddr())
New->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
return CanMerge::Yes;
}
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New) {
Constant *NewConstant = New;
LLVM_DEBUG(dbgs() << "Replacing global: @" << Old->getName() << " -> @"
<< New->getName() << "\n");
// Bump the alignment if necessary.
if (Old->getAlignment() || New->getAlignment())
New->setAlignment(std::max(getAlignment(Old), getAlignment(New)));
copyDebugLocMetadata(Old, New);
Old->replaceAllUsesWith(NewConstant);
// Delete the global value from the module.
assert(Old->hasLocalLinkage() &&
"Refusing to delete an externally visible global variable.");
Old->eraseFromParent();
}
static bool mergeConstants(Module &M) {
// Find all the globals that are marked "used". These cannot be merged.
SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
// Map unique constants to globals.
DenseMap<Constant *, GlobalVariable *> CMap;
// Replacements - This vector contains a list of replacements to perform.
SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
bool MadeChange = false;
// Iterate constant merging while we are still making progress. Merging two
// constants together may allow us to merge other constants together if the
// second level constants have initializers which point to the globals that
// were just merged.
while (true) {
// First: Find the canonical constants others will be merged with.
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = &*GVI++;
// If this GV is dead, remove it.
GV->removeDeadConstantUsers();
if (GV->use_empty() && GV->hasLocalLinkage()) {
GV->eraseFromParent();
continue;
}
// Only process constants with initializers in the default address space.
if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
// Don't touch values marked with attribute(used).
UsedGlobals.count(GV))
continue;
// This transformation is legal for weak ODR globals in the sense it
// doesn't change semantics, but we really don't want to perform it
// anyway; it's likely to pessimize code generation, and some tools
// (like the Darwin linker in cases involving CFString) don't expect it.
if (GV->isWeakForLinker())
continue;
// Don't touch globals with metadata other then !dbg.
if (hasMetadataOtherThanDebugLoc(GV))
continue;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known.
GlobalVariable *&Slot = CMap[Init];
// If this is the first constant we find or if the old one is local,
// replace with the current one. If the current is externally visible
// it cannot be replace, but can be the canonical constant we merge with.
bool FirstConstantFound = !Slot;
if (FirstConstantFound || IsBetterCanonical(*GV, *Slot)) {
Slot = GV;
LLVM_DEBUG(dbgs() << "Cmap[" << *Init << "] = " << GV->getName()
<< (FirstConstantFound ? "\n" : " (updated)\n"));
}
}
// Second: identify all globals that can be merged together, filling in
// the Replacements vector. We cannot do the replacement in this pass
// because doing so may cause initializers of other globals to be rewritten,
// invalidating the Constant* pointers in CMap.
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = &*GVI++;
// Only process constants with initializers in the default address space.
if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
// Don't touch values marked with attribute(used).
UsedGlobals.count(GV))
continue;
// We can only replace constant with local linkage.
if (!GV->hasLocalLinkage())
continue;
Constant *Init = GV->getInitializer();
// Check to see if the initializer is already known.
auto Found = CMap.find(Init);
if (Found == CMap.end())
continue;
GlobalVariable *Slot = Found->second;
if (Slot == GV)
continue;
if (makeMergeable(GV, Slot) == CanMerge::No)
continue;
// Make all uses of the duplicate constant use the canonical version.
LLVM_DEBUG(dbgs() << "Will replace: @" << GV->getName() << " -> @"
<< Slot->getName() << "\n");
Replacements.push_back(std::make_pair(GV, Slot));
}
if (Replacements.empty())
return MadeChange;
CMap.clear();
// Now that we have figured out which replacements must be made, do them all
// now. This avoid invalidating the pointers in CMap, which are unneeded
// now.
for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
GlobalVariable *Old = Replacements[i].first;
GlobalVariable *New = Replacements[i].second;
replace(M, Old, New);
MadeChange = true;
}
NumMerged += Replacements.size();
Replacements.clear();
}
}
PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {
if (!mergeConstants(M))
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}
namespace {
struct ConstantMergeLegacyPass : public ModulePass {
static char ID; // Pass identification, replacement for typeid
ConstantMergeLegacyPass() : ModulePass(ID) {
initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
}
// For this pass, process all of the globals in the module, eliminating
// duplicate constants.
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
return mergeConstants(M);
}
};
} // end anonymous namespace
char ConstantMergeLegacyPass::ID = 0;
INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
"Merge Duplicate Global Constants", false, false)
ModulePass *llvm::createConstantMergePass() {
return new ConstantMergeLegacyPass();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SalGtkFilePicker.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: ihi $ $Date: 2007-11-19 16:25:22 $
*
* 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 _SALGTKFILEPICKER_HXX_
#define _SALGTKFILEPICKER_HXX_
//_______________________________________________________________________________________________________________________
// includes of other projects
//_______________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_COMPBASE10_HXX_
#include <cppuhelper/compbase10.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_
#include <com/sun/star/beans/StringPair.hpp>
#endif
#ifndef _SALGTKPICKER_HXX_
#include "SalGtkPicker.hxx"
#endif
#include <memory>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.hxx>
#endif
#include <list>
//----------------------------------------------------------
// Implementation class for the XFilePicker Interface
//----------------------------------------------------------
//----------------------------------------------------------
// forward declarations
//----------------------------------------------------------
using namespace rtl;
struct FilterEntry;
struct ElementEntry_Impl;
typedef ::std::list < FilterEntry > FilterList;
typedef ::std::list < ElementEntry_Impl > ElementList;
typedef ::com::sun::star::beans::StringPair UnoFilterEntry;
typedef ::com::sun::star::uno::Sequence< UnoFilterEntry > UnoFilterList; // can be transported more effectively
//----------------------------------------------------------
// class declaration
//----------------------------------------------------------
class SalGtkFilePicker :
public SalGtkPicker,
public cppu::WeakComponentImplHelper10<
::com::sun::star::ui::dialogs::XFilterManager,
::com::sun::star::ui::dialogs::XFilterGroupManager,
::com::sun::star::ui::dialogs::XFilePickerControlAccess,
::com::sun::star::ui::dialogs::XFilePickerNotifier,
::com::sun::star::ui::dialogs::XFilePreview,
::com::sun::star::ui::dialogs::XFilePicker2,
::com::sun::star::lang::XInitialization,
::com::sun::star::util::XCancellable,
::com::sun::star::lang::XEventListener,
::com::sun::star::lang::XServiceInfo >
{
public:
// constructor
SalGtkFilePicker( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceMgr );
//------------------------------------------------------------------------------------
// XFilePickerNotifier
//------------------------------------------------------------------------------------
virtual void SAL_CALL addFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XExecutableDialog functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle )
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int16 SAL_CALL execute( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilePicker functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setMultiSelectionMode( sal_Bool bMode )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
throw( com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getDisplayDirectory( )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilePicker2 functions
//------------------------------------------------------------------------------------
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSelectedFiles()
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// XFilterManager functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getCurrentFilter( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilterGroupManager functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// XFilePickerControlAccess functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setValue( sal_Int16 nControlId, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& aValue )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL enableControl( sal_Int16 nControlId, sal_Bool bEnable )
throw(::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setLabel( sal_Int16 nControlId, const ::rtl::OUString& aLabel )
throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 nControlId )
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XFilePreview
//------------------------------------------------
virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTargetColorDepth( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableWidth( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableHeight( )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getShowState( )
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XInitialization
//------------------------------------------------
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XCancellable
//------------------------------------------------
virtual void SAL_CALL cancel( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------
// XEventListener
//------------------------------------------------
using cppu::WeakComponentImplHelperBase::disposing;
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XServiceInfo
//------------------------------------------------
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// FilePicker Event functions
//------------------------------------------------------------------------------------
void SAL_CALL fileSelectionChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
void SAL_CALL directoryChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
rtl::OUString SAL_CALL helpRequested( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ) const;
void SAL_CALL controlStateChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
void SAL_CALL dialogSizeChanged( );
private:
// prevent copy and assignment
SalGtkFilePicker( const SalGtkFilePicker& );
SalGtkFilePicker& operator=( const SalGtkFilePicker& );
sal_Bool FilterNameExists( const ::rtl::OUString& rTitle );
sal_Bool FilterNameExists( const UnoFilterList& _rGroupedFilters );
void ensureFilterList( const ::rtl::OUString& _rInitialCurrentFilter );
// to instanciate own services
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceMgr;
private:
::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >
m_xListener;
FilterList *m_pFilterList;
GtkWidget *m_pVBox;
GtkWidget *m_pFilterExpander;
GtkWidget *m_pFilterView;
GtkListStore *m_pFilterStore;
enum {
AUTOEXTENSION,
PASSWORD,
FILTEROPTIONS,
READONLY,
LINK,
PREVIEW,
SELECTION,
TOGGLE_LAST
};
GtkWidget *m_pToggles[ TOGGLE_LAST ];
bool mbToggleVisibility[TOGGLE_LAST];
bool mbToggleChecked[TOGGLE_LAST];
static const rtl::OString m_ToggleLabels[TOGGLE_LAST];
enum {
PLAY,
BUTTON_LAST };
GtkWidget *m_pButtons[ BUTTON_LAST ];
enum {
VERSION,
TEMPLATE,
IMAGE_TEMPLATE,
LIST_LAST
};
GtkWidget *m_pHBoxs[ LIST_LAST ];
GtkWidget *m_pAligns[ LIST_LAST ];
GtkWidget *m_pLists[ LIST_LAST ];
GtkWidget *m_pListLabels[ LIST_LAST ];
bool mbListVisibility[ LIST_LAST ];
gulong mnHID_FolderChange;
gulong mnHID_SelectionChange;
::rtl::OUString m_aCurrentFilter;
bool bVersionWidthUnset;
sal_Bool mbPreviewState;
gulong mHID_Preview;
GtkWidget* m_pPreview;
sal_Int32 m_PreviewImageWidth;
sal_Int32 m_PreviewImageHeight;
GtkWidget *getWidget( sal_Int16 nControlId, GType *pType = NULL);
void SetCurFilter( const OUString& rFilter );
void SetFilters();
void UpdateFilterfromUI();
void implChangeType( GtkTreeSelection *selection );
int implAddFilter( const OUString& rFilter, const OUString& rType);
int implAddFilterGroup( const OUString& rFilter,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair>& _rFilters );
void updateCurrentFilterFromName(const gchar* filtername);
void unselect_type();
void InitialMapping();
void HandleSetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction,
const ::com::sun::star::uno::Any& rValue);
::com::sun::star::uno::Any HandleGetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction) const;
static void expander_changed_cb( GtkExpander *expander, SalGtkFilePicker *pobjFP );
static void preview_toggled_cb (GtkObject *cb, SalGtkFilePicker *pobjFP);
static void filter_changed_cb (GtkFileChooser *file_chooser, GParamSpec *pspec, SalGtkFilePicker *pobjFP);
static void type_changed_cb( GtkTreeSelection *selection, SalGtkFilePicker *pobjFP );
static void folder_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void selection_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void update_preview_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void dialog_mapped_cb(GtkWidget *widget, SalGtkFilePicker *pobjFP);
public:
virtual ~SalGtkFilePicker();
};
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
#endif // _SALGTKFILEPICKER_HXX_
<commit_msg>INTEGRATION: CWS unifysound01_DEV300 (1.10.110); FILE MERGED 2007/12/03 10:02:57 cmc 1.10.110.3: RESYNC: (1.10-1.11); FILE MERGED 2007/08/13 09:58:19 cmc 1.10.110.2: #i80567# provide non-stock play and stop buttons for older gtk releases 2007/08/10 11:03:44 cmc 1.10.110.1: #i80567# Add a play button the gtk fpicker<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SalGtkFilePicker.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2008-03-07 16:13: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 _SALGTKFILEPICKER_HXX_
#define _SALGTKFILEPICKER_HXX_
//_______________________________________________________________________________________________________________________
// includes of other projects
//_______________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_COMPBASE10_HXX_
#include <cppuhelper/compbase10.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_
#include <com/sun/star/beans/StringPair.hpp>
#endif
#ifndef _SALGTKPICKER_HXX_
#include "SalGtkPicker.hxx"
#endif
#include <memory>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.hxx>
#endif
#include <list>
//----------------------------------------------------------
// Implementation class for the XFilePicker Interface
//----------------------------------------------------------
//----------------------------------------------------------
// forward declarations
//----------------------------------------------------------
using namespace rtl;
struct FilterEntry;
struct ElementEntry_Impl;
typedef ::std::list < FilterEntry > FilterList;
typedef ::std::list < ElementEntry_Impl > ElementList;
typedef ::com::sun::star::beans::StringPair UnoFilterEntry;
typedef ::com::sun::star::uno::Sequence< UnoFilterEntry > UnoFilterList; // can be transported more effectively
//----------------------------------------------------------
// class declaration
//----------------------------------------------------------
class SalGtkFilePicker :
public SalGtkPicker,
public cppu::WeakComponentImplHelper10<
::com::sun::star::ui::dialogs::XFilterManager,
::com::sun::star::ui::dialogs::XFilterGroupManager,
::com::sun::star::ui::dialogs::XFilePickerControlAccess,
::com::sun::star::ui::dialogs::XFilePickerNotifier,
::com::sun::star::ui::dialogs::XFilePreview,
::com::sun::star::ui::dialogs::XFilePicker2,
::com::sun::star::lang::XInitialization,
::com::sun::star::util::XCancellable,
::com::sun::star::lang::XEventListener,
::com::sun::star::lang::XServiceInfo >
{
public:
// constructor
SalGtkFilePicker( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceMgr );
//------------------------------------------------------------------------------------
// XFilePickerNotifier
//------------------------------------------------------------------------------------
virtual void SAL_CALL addFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XExecutableDialog functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle )
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int16 SAL_CALL execute( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilePicker functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setMultiSelectionMode( sal_Bool bMode )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
throw( com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getDisplayDirectory( )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilePicker2 functions
//------------------------------------------------------------------------------------
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSelectedFiles()
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// XFilterManager functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getCurrentFilter( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------------------------------------------
// XFilterGroupManager functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// XFilePickerControlAccess functions
//------------------------------------------------------------------------------------
virtual void SAL_CALL setValue( sal_Int16 nControlId, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& aValue )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL enableControl( sal_Int16 nControlId, sal_Bool bEnable )
throw(::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setLabel( sal_Int16 nControlId, const ::rtl::OUString& aLabel )
throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 nControlId )
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XFilePreview
//------------------------------------------------
virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTargetColorDepth( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableWidth( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableHeight( )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getShowState( )
throw (::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XInitialization
//------------------------------------------------
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XCancellable
//------------------------------------------------
virtual void SAL_CALL cancel( )
throw( ::com::sun::star::uno::RuntimeException );
//------------------------------------------------
// XEventListener
//------------------------------------------------
using cppu::WeakComponentImplHelperBase::disposing;
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::uno::RuntimeException);
//------------------------------------------------
// XServiceInfo
//------------------------------------------------
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException);
//------------------------------------------------------------------------------------
// FilePicker Event functions
//------------------------------------------------------------------------------------
void SAL_CALL fileSelectionChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
void SAL_CALL directoryChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
rtl::OUString SAL_CALL helpRequested( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ) const;
void SAL_CALL controlStateChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent );
void SAL_CALL dialogSizeChanged( );
private:
// prevent copy and assignment
SalGtkFilePicker( const SalGtkFilePicker& );
SalGtkFilePicker& operator=( const SalGtkFilePicker& );
sal_Bool FilterNameExists( const ::rtl::OUString& rTitle );
sal_Bool FilterNameExists( const UnoFilterList& _rGroupedFilters );
void ensureFilterList( const ::rtl::OUString& _rInitialCurrentFilter );
// to instanciate own services
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceMgr;
private:
::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >
m_xListener;
::rtl::OUString msPlayLabel;
FilterList *m_pFilterList;
GtkWidget *m_pVBox;
GtkWidget *m_pFilterExpander;
GtkWidget *m_pFilterView;
GtkListStore *m_pFilterStore;
enum {
AUTOEXTENSION,
PASSWORD,
FILTEROPTIONS,
READONLY,
LINK,
PREVIEW,
SELECTION,
TOGGLE_LAST
};
GtkWidget *m_pToggles[ TOGGLE_LAST ];
bool mbToggleVisibility[TOGGLE_LAST];
bool mbToggleChecked[TOGGLE_LAST];
static const rtl::OString m_ToggleLabels[TOGGLE_LAST];
enum {
PLAY,
BUTTON_LAST };
GtkWidget *m_pButtons[ BUTTON_LAST ];
enum {
VERSION,
TEMPLATE,
IMAGE_TEMPLATE,
LIST_LAST
};
GtkWidget *m_pHBoxs[ LIST_LAST ];
GtkWidget *m_pAligns[ LIST_LAST ];
GtkWidget *m_pLists[ LIST_LAST ];
GtkWidget *m_pListLabels[ LIST_LAST ];
bool mbListVisibility[ LIST_LAST ];
bool mbButtonVisibility[ BUTTON_LAST ];
gulong mnHID_FolderChange;
gulong mnHID_SelectionChange;
::rtl::OUString m_aCurrentFilter;
bool bVersionWidthUnset;
sal_Bool mbPreviewState;
gulong mHID_Preview;
GtkWidget* m_pPreview;
sal_Int32 m_PreviewImageWidth;
sal_Int32 m_PreviewImageHeight;
GtkWidget *getWidget( sal_Int16 nControlId, GType *pType = NULL);
void SetCurFilter( const OUString& rFilter );
void SetFilters();
void UpdateFilterfromUI();
void implChangeType( GtkTreeSelection *selection );
int implAddFilter( const OUString& rFilter, const OUString& rType);
int implAddFilterGroup( const OUString& rFilter,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair>& _rFilters );
void updateCurrentFilterFromName(const gchar* filtername);
void unselect_type();
void InitialMapping();
void HandleSetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction,
const ::com::sun::star::uno::Any& rValue);
::com::sun::star::uno::Any HandleGetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction) const;
static void expander_changed_cb( GtkExpander *expander, SalGtkFilePicker *pobjFP );
static void preview_toggled_cb (GtkObject *cb, SalGtkFilePicker *pobjFP);
static void filter_changed_cb (GtkFileChooser *file_chooser, GParamSpec *pspec, SalGtkFilePicker *pobjFP);
static void type_changed_cb( GtkTreeSelection *selection, SalGtkFilePicker *pobjFP );
static void folder_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void selection_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void update_preview_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP);
static void dialog_mapped_cb(GtkWidget *widget, SalGtkFilePicker *pobjFP);
public:
virtual ~SalGtkFilePicker();
};
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
#endif // _SALGTKFILEPICKER_HXX_
<|endoftext|> |
<commit_before>#pragma once
#include "CSingleton.hpp"
#include "types.hpp"
#include <string>
#include <atomic>
#include <json.hpp>
using json = nlohmann::json;
class Role
{
public:
Role(RoleId_t pawn_id, json &data);
~Role() = default;
private:
const RoleId_t m_PawnId;
Snowflake_t m_Id;
std::string m_Name;
int m_Color;
bool m_Hoist;
int m_Permissions;
bool m_Mentionable;
public:
inline RoleId_t GetPawnId() const
{
return m_PawnId;
}
inline Snowflake_t const &GetId() const
{
return m_Id;
}
inline std::string const &GetName() const
{
return m_Name;
}
inline int GetColor() const
{
return m_Color;
}
inline bool IsHoist() const
{
return m_Hoist;
}
inline int GetPermissions() const
{
return m_Permissions;
}
inline bool IsMentionable() const
{
return m_Mentionable;
}
};
class RoleManager : public CSingleton<RoleManager>
{
friend class CSingleton<RoleManager>;
private:
RoleManager() = default;
~RoleManager() = default;
private:
const unsigned int m_InitValue = 1;
std::atomic<unsigned int> m_Initialized{ 0 };
std::map<RoleId_t, Role_t> m_Roles; //PAWN role-id to actual channel map
public:
Role_t const &AddRole(json &data);
Role_t const &FindRole(RoleId_t id);
Role_t const &FindRoleById(Snowflake_t const &sfid);
};
<commit_msg>fix spacing<commit_after>#pragma once
#include "CSingleton.hpp"
#include "types.hpp"
#include <string>
#include <atomic>
#include <json.hpp>
using json = nlohmann::json;
class Role
{
public:
Role(RoleId_t pawn_id, json &data);
~Role() = default;
private:
const RoleId_t m_PawnId;
Snowflake_t m_Id;
std::string m_Name;
int m_Color;
bool m_Hoist;
int m_Permissions;
bool m_Mentionable;
public:
inline RoleId_t GetPawnId() const
{
return m_PawnId;
}
inline Snowflake_t const &GetId() const
{
return m_Id;
}
inline std::string const &GetName() const
{
return m_Name;
}
inline int GetColor() const
{
return m_Color;
}
inline bool IsHoist() const
{
return m_Hoist;
}
inline int GetPermissions() const
{
return m_Permissions;
}
inline bool IsMentionable() const
{
return m_Mentionable;
}
};
class RoleManager : public CSingleton<RoleManager>
{
friend class CSingleton<RoleManager>;
private:
RoleManager() = default;
~RoleManager() = default;
private:
const unsigned int m_InitValue = 1;
std::atomic<unsigned int> m_Initialized{ 0 };
std::map<RoleId_t, Role_t> m_Roles; //PAWN role-id to actual channel map
public:
Role_t const &AddRole(json &data);
Role_t const &FindRole(RoleId_t id);
Role_t const &FindRoleById(Snowflake_t const &sfid);
};
<|endoftext|> |
<commit_before>#ifndef __CALCULATE_WRAPPER_HPP__
#define __CALCULATE_WRAPPER_HPP__
#include <memory>
#include <type_traits>
#include <tuple>
#include <vector>
#include <utility>
#include "exception.hpp"
namespace calculate {
namespace detail {
template<typename Function, typename... Args>
struct NoExcept {
static constexpr bool value =
noexcept(std::declval<Function>()(std::declval<Args>()...));
};
template<typename Type, typename = void>
struct Traits : Traits<decltype(&Type::operator())> {};
template<typename Result, typename... Args>
struct Traits<std::function<Result(Args...)>, void> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...),
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const,
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Function>
using Result = typename Traits<Function>::result;
template<typename Function>
using Arguments = typename Traits<Function>::arguments;
template<typename Function>
struct Argc {
static constexpr std::size_t value =
std::tuple_size<typename Traits<Function>::arguments>::value;
};
template<typename Function>
struct IsConst {
static constexpr bool value = Traits<Function>::constant;
};
template<typename Type, typename Target>
struct NotSame {
static constexpr bool value =
!std::is_same<std::decay_t<Type>, Target>::value &&
!std::is_base_of<Target, std::decay_t<Type>>::value;
};
template<typename Type, std::size_t>
using ExtractType = Type;
template<typename, std::size_t n, typename = std::make_index_sequence<n>>
struct Repeat {};
template<typename Type, std::size_t n, std::size_t... indices>
struct Repeat<Type, n, std::index_sequence<indices...>> {
using type = std::tuple<ExtractType<Type, indices>...>;
};
template<typename Type, std::size_t n>
using Repeated = typename Repeat<Type, n>::type;
}
template<typename Type, typename Source>
struct WrapperConcept {
virtual std::shared_ptr<WrapperConcept> copy() const noexcept = 0;
virtual std::size_t argc() const noexcept = 0;
virtual bool is_const() const noexcept = 0;
virtual Type evaluate(const std::vector<Source>&) const = 0;
virtual Type evaluate(const std::vector<Source>&) = 0;
virtual ~WrapperConcept() {}
};
template<typename Type, typename Source = Type>
class Wrapper {
friend struct std::hash<Wrapper>;
using WrapperConcept = calculate::WrapperConcept<Type, Source>;
template<typename Callable>
struct Inspect {
static constexpr bool not_me =
detail::NotSame<Callable, Wrapper>::value;
static constexpr bool is_model =
std::is_base_of<WrapperConcept, Callable>::value;
};
template<typename Callable, typename Adapter, std::size_t n, bool constant>
class WrapperModel final : public WrapperConcept {
Callable _callable;
Adapter _adapter;
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, true>::type,
const std::vector<Source>& args
) const {
return const_cast<WrapperModel*>(this)
->_evaluate(args, std::make_index_sequence<n>{});
}
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, false>::type,
const std::vector<Source>&
) const { throw AccessViolation{}; }
template<std::size_t... indices>
Type _evaluate(
const std::vector<Source>& args,
std::index_sequence<indices...>
) {
if (args.size() != n)
throw ArgumentsMismatch{n, args.size()};
return _callable(_adapter(args[indices])...);
}
public:
WrapperModel(Callable callable, Adapter adapter) :
_callable{callable},
_adapter{adapter}
{}
std::shared_ptr<WrapperConcept> copy() const noexcept override {
return std::make_shared<WrapperModel>(*this);
}
std::size_t argc() const noexcept override { return n; }
bool is_const() const noexcept override { return constant; }
Type evaluate(const std::vector<Source>& args) const override {
return _evaluate(std::integral_constant<bool, constant>{}, args);
}
Type evaluate(const std::vector<Source>& args) override {
return _evaluate(args, std::make_index_sequence<n>{});
}
};
template<typename Callable, typename Adapter>
using ModelType = WrapperModel<
Callable,
Adapter,
detail::Argc<Callable>::value,
detail::IsConst<Callable>::value
>;
std::shared_ptr<WrapperConcept> _callable;
Wrapper(std::shared_ptr<WrapperConcept>&& callable) :
_callable{std::move(callable)}
{}
public:
template<typename Callable, typename Adapter>
Wrapper(Callable&& callable, Adapter&& adapter) :
_callable{
std::make_shared<ModelType<Callable, Adapter>>(
std::forward<Callable>(callable),
std::forward<Adapter>(adapter)
)
}
{
static_assert(
std::is_copy_constructible<Callable>::value,
"Non copy-constructible callable"
);
static_assert(
std::is_copy_constructible<Adapter>::value,
"Non copy-constructible adapter"
);
static_assert(
std::is_same<
detail::Arguments<Callable>,
detail::Repeated<Type, detail::Argc<Callable>::value>
>::value,
"Wrong arguments types"
);
static_assert(
std::is_same<detail::Result<Callable>, Type>::value,
"Wrong return type"
);
static_assert(
std::is_same<
detail::Arguments<Adapter>,
detail::Repeated<Source, 1>
>::value,
"Wrong adapter arguments types"
);
static_assert(
std::is_same<detail::Result<Adapter>, Type>::value,
"Wrong adapter return type"
);
static_assert(
detail::IsConst<Adapter>::value,
"Non constant adapter function"
);
}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::not_me>* = nullptr,
std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable=[]() { return Type(); }) :
Wrapper{
std::forward<Callable>(callable),
[](const Source& x) { return Type{x}; }
}
{}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable) :
_callable{
std::make_shared<Callable>(
std::forward<Callable>(callable)
)
}
{}
Type operator()(const std::vector<Source>& args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(args);
}
Type operator()(const std::vector<Source>& args) {
return _callable->evaluate(args);
}
template<typename... Args>
Type operator()(Args&&... args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
template<typename... Args>
Type operator()(Args&&... args) {
return _callable
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
bool operator==(const Wrapper& other) const noexcept {
return _callable == other._callable;
}
Wrapper copy() const noexcept { return Wrapper{_callable->copy()}; }
std::size_t argc() const noexcept { return _callable->argc(); }
bool is_const() const noexcept { return _callable->is_const(); }
};
}
namespace std {
template<typename Type, typename Source>
struct hash<calculate::Wrapper<Type, Source>> {
size_t operator()(const calculate::Wrapper<Type, Source>& wrapper) const {
return hash<std::shared_ptr<calculate::WrapperConcept<Type, Source>>>{}(
wrapper._callable
);
}
};
}
#endif
<commit_msg>Bring 'feature/call' from develop into 'feature/symbols'<commit_after>#ifndef __CALCULATE_WRAPPER_HPP__
#define __CALCULATE_WRAPPER_HPP__
#include <memory>
#include <type_traits>
#include <tuple>
#include <vector>
#include <utility>
#include "exception.hpp"
namespace calculate {
namespace detail {
template<typename Function, typename... Args>
struct NoExcept {
static constexpr bool value =
noexcept(std::declval<Function>()(std::declval<Args>()...));
};
template<typename Type, typename = void>
struct Traits : Traits<decltype(&Type::operator())> {};
template<typename Result, typename... Args>
struct Traits<std::function<Result(Args...)>, void> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...),
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const,
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Function>
using Result = typename Traits<Function>::result;
template<typename Function>
using Arguments = typename Traits<Function>::arguments;
template<typename Function>
struct Argc {
static constexpr std::size_t value =
std::tuple_size<typename Traits<Function>::arguments>::value;
};
template<typename Function>
struct IsConst {
static constexpr bool value = Traits<Function>::constant;
};
template<typename Type, typename Target>
struct NotSame {
static constexpr bool value =
!std::is_same<std::decay_t<Type>, Target>::value &&
!std::is_base_of<Target, std::decay_t<Type>>::value;
};
template<typename Type, std::size_t>
using ExtractType = Type;
template<typename, std::size_t n, typename = std::make_index_sequence<n>>
struct Repeat {};
template<typename Type, std::size_t n, std::size_t... indices>
struct Repeat<Type, n, std::index_sequence<indices...>> {
using type = std::tuple<ExtractType<Type, indices>...>;
};
template<typename Type, std::size_t n>
using Repeated = typename Repeat<Type, n>::type;
}
template<typename Type, typename Source>
struct WrapperConcept {
virtual std::shared_ptr<WrapperConcept> copy() const noexcept = 0;
virtual std::size_t argc() const noexcept = 0;
virtual bool is_const() const noexcept = 0;
virtual Type call(const std::vector<Type>&) const = 0;
virtual Type call(const std::vector<Type>&) = 0;
virtual Type eval(const std::vector<Source>&) const = 0;
virtual Type eval(const std::vector<Source>&) = 0;
virtual ~WrapperConcept() {}
};
template<typename Type, typename Source = Type>
class Wrapper {
friend struct std::hash<Wrapper>;
using WrapperConcept = calculate::WrapperConcept<Type, Source>;
template<typename Callable>
struct Inspect {
static constexpr bool not_me =
detail::NotSame<Callable, Wrapper>::value;
static constexpr bool is_model =
std::is_base_of<WrapperConcept, Callable>::value;
};
template<typename Callable, typename Adapter, std::size_t n, bool constant>
class WrapperModel final : public WrapperConcept {
template<bool c> using Constant = std::integral_constant<bool, c>;
using False = std::integral_constant<bool, false>::type;
using True = std::integral_constant<bool, true>::type;
Callable _callable;
Adapter _adapter;
template<typename Vector, typename Adapt, std::size_t... indices>
Type _invoke(const Vector&, const Adapt&, False) const {
throw AccessViolation{};
}
template<typename Vector, typename Adapt, std::size_t... indices>
Type _invoke(const Vector& args, const Adapt& adapt, True) const {
return const_cast<WrapperModel*>(this)
->_invoke(args, adapt, std::make_index_sequence<n>{});
}
template<std::size_t... indices>
Type _invoke(
const std::vector<Type>& args,
False,
std::index_sequence<indices...>
) {
if (args.size() != n)
throw ArgumentsMismatch{n, args.size()};
return _callable(args[indices]...);
}
template<std::size_t... indices>
Type _invoke(
const std::vector<Source>& args,
True,
std::index_sequence<indices...>
) {
if (args.size() != n)
throw ArgumentsMismatch{n, args.size()};
return _callable(_adapter(args[indices])...);
}
public:
WrapperModel(Callable callable, Adapter adapter) :
_callable{callable},
_adapter{adapter}
{}
std::shared_ptr<WrapperConcept> copy() const noexcept override {
return std::make_shared<WrapperModel>(*this);
}
std::size_t argc() const noexcept override { return n; }
bool is_const() const noexcept override { return constant; }
Type call(const std::vector<Type>& args) const override {
return _invoke(args, False{}, Constant<constant>{});
}
Type call(const std::vector<Type>& args) override {
return _invoke(args, False{}, std::make_index_sequence<n>{});
}
Type eval(const std::vector<Source>& args) const override {
return _invoke(args, True{}, Constant<constant>{});
}
Type eval(const std::vector<Source>& args) override {
return _invoke(args, True{}, std::make_index_sequence<n>{});
}
};
template<typename Callable, typename Adapter>
using ModelType = WrapperModel<
Callable,
Adapter,
detail::Argc<Callable>::value,
detail::IsConst<Callable>::value
>;
std::shared_ptr<WrapperConcept> _callable;
Wrapper(std::shared_ptr<WrapperConcept>&& callable) :
_callable{std::move(callable)}
{}
public:
template<typename Callable, typename Adapter>
Wrapper(Callable&& callable, Adapter&& adapter) :
_callable{
std::make_shared<ModelType<Callable, Adapter>>(
std::forward<Callable>(callable),
std::forward<Adapter>(adapter)
)
}
{
static_assert(
std::is_copy_constructible<Callable>::value,
"Non copy-constructible callable"
);
static_assert(
std::is_copy_constructible<Adapter>::value,
"Non copy-constructible adapter"
);
static_assert(
std::is_same<
detail::Arguments<Callable>,
detail::Repeated<Type, detail::Argc<Callable>::value>
>::value,
"Wrong arguments types"
);
static_assert(
std::is_same<detail::Result<Callable>, Type>::value,
"Wrong return type"
);
static_assert(
std::is_same<
detail::Arguments<Adapter>,
detail::Repeated<Source, 1>
>::value,
"Wrong adapter arguments types"
);
static_assert(
std::is_same<detail::Result<Adapter>, Type>::value,
"Wrong adapter return type"
);
static_assert(
detail::IsConst<Adapter>::value,
"Non constant adapter function"
);
}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::not_me>* = nullptr,
std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable=[]() { return Type(); }) :
Wrapper{
std::forward<Callable>(callable),
[](const Source& x) { return Type{x}; }
}
{}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable) :
_callable{
std::make_shared<Callable>(
std::forward<Callable>(callable)
)
}
{}
Type call(const std::vector<Type>& args) const {
return const_cast<const WrapperConcept*>(_callable.get())->call(args);
}
Type call(const std::vector<Type>& args) {
return _callable->call(args);
}
template<typename... Args>
Type call(Args&&... args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->call(std::vector<Type>{std::forward<Args>(args)...});
}
template<typename... Args>
Type call(Args&&... args) {
return _callable
->call(std::vector<Type>{std::forward<Args>(args)...});
}
Type operator()(const std::vector<Source>& args) const {
return const_cast<const WrapperConcept*>(_callable.get())->eval(args);
}
Type operator()(const std::vector<Source>& args) {
return _callable->eval(args);
}
template<typename... Args>
Type operator()(Args&&... args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->eval(std::vector<Source>{std::forward<Args>(args)...});
}
template<typename... Args>
Type operator()(Args&&... args) {
return _callable
->eval(std::vector<Source>{std::forward<Args>(args)...});
}
bool operator==(const Wrapper& other) const noexcept {
return _callable == other._callable;
}
Wrapper copy() const noexcept { return Wrapper{_callable->copy()}; }
std::size_t argc() const noexcept { return _callable->argc(); }
bool is_const() const noexcept { return _callable->is_const(); }
};
}
namespace std {
template<typename Type, typename Source>
struct hash<calculate::Wrapper<Type, Source>> {
size_t operator()(const calculate::Wrapper<Type, Source>& wrapper) const {
return hash<std::shared_ptr<calculate::WrapperConcept<Type, Source>>>{}(
wrapper._callable
);
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 Kolibre
This file is part of kolibre-narrator.
Kolibre-narrator 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.
Kolibre-narrator 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 kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PortAudio.h"
#include "RingBuffer.h"
#include <iostream>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <log4cxx/logger.h>
#define RINGBUFFERSIZE 4096*16
// create logger which will become a child to logger kolibre.narrator
log4cxx::LoggerPtr narratorPaLog(log4cxx::Logger::getLogger("kolibre.narrator.portaudio"));
int pa_stream_callback(
const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData );
void pa_stream_finished_callback( void *userData );
PortAudio::PortAudio():
ringbuf(RINGBUFFERSIZE)
{
isInitialized = true;
isOpen = false;
isStarted = false;
mChannels = 0;
mRate = 0;
mLatency = 0;
pStream = NULL;
LOG4CXX_INFO(narratorPaLog, "Initializing portaudio");
mError = Pa_Initialize();
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to initialize portaudio: " << Pa_GetErrorText(mError));
isInitialized = false;
}
}
PortAudio::~PortAudio()
{
close();
if(isInitialized)
Pa_Terminate();
}
bool PortAudio::open(long rate, int channels)
{
if(mRate != rate || mChannels != channels) {
close();
}
if(!isOpen) {
//PaDeviceIndex default_device = 2;
PaDeviceIndex default_device = Pa_GetDefaultOutputDevice();
if( default_device == paNoDevice ) {
LOG4CXX_ERROR(narratorPaLog, "Pa_GetDefaultOutputDevice failed, however, device count is: " << Pa_GetDeviceCount() );
return false;
}
mOutputParameters.device = default_device; /* default output device */
mOutputParameters.channelCount = channels;
mOutputParameters.sampleFormat = paFloat32;
mOutputParameters.suggestedLatency = Pa_GetDeviceInfo( mOutputParameters.device )->defaultHighOutputLatency;
mOutputParameters.hostApiSpecificStreamInfo = NULL;
const PaDeviceInfo* devinfo = Pa_GetDeviceInfo(mOutputParameters.device);
const PaHostApiInfo* hostapiinfo = Pa_GetHostApiInfo(devinfo->hostApi);
LOG4CXX_DEBUG(narratorPaLog, "Opening device: " << devinfo->name << " (" << hostapiinfo->name << "), channels: " << channels << ", rate: " << rate <<" (" << devinfo->defaultSampleRate << ")");
unsigned long framesPerBuffer = 1024;
#ifdef WIN32
framesPerBuffer = 4096;
#endif
mError = Pa_OpenStream(&pStream, NULL, &mOutputParameters, rate, framesPerBuffer/*paFramesPerBufferUnspecified*/,
paNoFlag, pa_stream_callback, this);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to open stream: " << Pa_GetErrorText(mError));
return false;
}
mRate = rate;
mChannels = channels;
isOpen = true;
isStarted = false;
mError = Pa_SetStreamFinishedCallback(pStream, pa_stream_finished_callback);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to set FinishedCallback: " << Pa_GetErrorText(mError));
}
}
return true;
}
long PortAudio::stop()
{
if(isStarted) {
mError = Pa_StopStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to stop stream: " << Pa_GetErrorText(mError));
ringbuf.flush();
isStarted = false;
}
return mLatency;
}
long PortAudio::abort()
{
if(isStarted) {
LOG4CXX_DEBUG(narratorPaLog, "Aborting stream");
mError = Pa_AbortStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to abort stream: " << Pa_GetErrorText(mError));
ringbuf.flush();
isStarted = false;
}
return mLatency;
}
bool PortAudio::close()
{
stop();
if(isOpen) {
mError = Pa_CloseStream(pStream);
if(mError != paNoError)
{
LOG4CXX_ERROR(narratorPaLog, "Failed to close stream: " << Pa_GetErrorText(mError));
}
else
{
isOpen = false;
}
}
return true;
}
long PortAudio::getRate()
{
return mRate;
}
int PortAudio::getChannels()
{
return mChannels;
}
long PortAudio::getRemainingms()
{
size_t bufferedData = ringbuf.getReadAvailable();
long bufferms = 0;
if(mChannels != 0 && mRate != 0)
bufferms = (long) (1000.0 * bufferedData) / mChannels / mRate;
return bufferms + mLatency;
}
/*
Blocks until data can be written.
If no data can be written in 2ms*100 the stream gets restarted.
returns the amount of data that can be written.
*/
unsigned int PortAudio::getWriteAvailable()
{
size_t writeAvailable = 0;
int waitCount = 0;
int failCount = 0;
while( writeAvailable == 0 ) {
writeAvailable = ringbuf.getWriteAvailable();
if( writeAvailable == 0 ) {
usleep(200000); //200 ms
//LOG4CXX_DEBUG(narratorPaLog, "getWriteAvailable = 0, Pa_IsStreamActive = " << Pa_IsStreamActive(pStream));
}
if(waitCount++ > 10) {
LOG4CXX_ERROR(narratorPaLog, "getWriteAvailable waittime exceeded, restarting stream");
mError = Pa_AbortStream(pStream);
// If abortstream fails, try reopening
if(failCount++ > 0 || ( mError != paNoError && mError != paStreamIsStopped )) {
LOG4CXX_ERROR(narratorPaLog, "Failed to abort stream, trying to close and reopen: " << Pa_GetErrorText(mError));
mError = Pa_CloseStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to close stream: " << Pa_GetErrorText(mError));
isOpen = false;
open(mRate, mChannels);
}
mError = Pa_StartStream(pStream);
if(mError != paNoError) LOG4CXX_ERROR(narratorPaLog, "[PortAudio::getWriteAvailable] Failed to start stream: " << Pa_GetErrorText(mError));
isStarted = true;
waitCount = 0;
}
}
//LOG4CXX_DEBUG(narratorPaLog, "getWriteAvailable = " << writeAvailable << ", Pa_IsStreamActive = " << Pa_IsStreamActive(pStream));
return writeAvailable;
}
bool PortAudio::write(float *buffer, unsigned int samples)
{
size_t elemWritten = ringbuf.writeElements(buffer, samples*mChannels);
// Try starting the stream
if(!isStarted && ringbuf.getWriteAvailable() <= (RINGBUFFERSIZE/2)) {
LOG4CXX_TRACE(narratorPaLog, "Starting stream");
mError = Pa_StartStream(pStream);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "[PortAudio::write] Failed to start stream: " << Pa_GetErrorText(mError));
}
mLatency = (long) (Pa_GetStreamInfo(pStream)->outputLatency * 1000.0);
isStarted = true;
}
else if(!isStarted )
LOG4CXX_TRACE(narratorPaLog, "Buffering: " << ((RINGBUFFERSIZE - ringbuf.getWriteAvailable()) * 100) / (RINGBUFFERSIZE) << "%");
if( elemWritten < samples)
return false;
return false;
}
long unsigned int min( long unsigned int a, long unsigned int b )
{
if( a < b )
return a;
return b;
}
/*
@note With the exception of Pa_GetStreamCpuLoad() it is not permissable to call
PortAudio API functions from within the stream callback.
*/
int pa_stream_callback(
const void *input,
void *output, // Write frameCount*channels here
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
(void) timeInfo; /* Prevent unused variable warning. */
(void) input; /* Prevent unused variable warning. */
//if(statusFlags & paOutputUnderflow)
// LOG4CXX_WARN(narratorPaLog, "Output underflow!");
//if(statusFlags & paOutputOverflow)
// LOG4CXX_WARN(narratorPaLog, "Output overflow!");
//if(statusFlags & paPrimingOutput)
// LOG4CXX_WARN(narratorPaLog, "Priming output!");
static long underrunms = 0;
RingBuffer *ringbuf = &((PortAudio*)userData)->ringbuf;
int channels = ((PortAudio*)userData)->mChannels;
long rate = ((PortAudio*)userData)->mRate;
float* outbuf = (float*)output;
size_t elementsRead = ringbuf->readElements(outbuf, frameCount * channels);
if( elementsRead < frameCount*channels ) {
memset( (outbuf+(elementsRead)), 0, (frameCount*channels-elementsRead)*sizeof(float) );
underrunms += (long) (frameCount * channels * 1000.0) / rate;
//LOG4CXX_DEBUG(narratorPaLog, " Less read than requested, underrun ms:" << underrunms );
} else {
//LOG4CXX_TRACE(narratorPaLog, " availableElements: " << availableElements << " elementsToRead: " << elementsToRead << " elementsRead:" << elementsRead);
underrunms = 0;
}
if(underrunms > 500) return paComplete;
return paContinue; // paAbort, paComplete
}
void pa_stream_finished_callback( void *userData )
{
((PortAudio*)userData)->isStarted = false;
//std::cout << __FUNCTION__ << " Finished" << std::endl;
}
<commit_msg>Revert log message output<commit_after>/*
Copyright (C) 2012 Kolibre
This file is part of kolibre-narrator.
Kolibre-narrator 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.
Kolibre-narrator 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 kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PortAudio.h"
#include "RingBuffer.h"
#include <iostream>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <log4cxx/logger.h>
#define RINGBUFFERSIZE 4096*16
// create logger which will become a child to logger kolibre.narrator
log4cxx::LoggerPtr narratorPaLog(log4cxx::Logger::getLogger("kolibre.narrator.portaudio"));
int pa_stream_callback(
const void *input,
void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData );
void pa_stream_finished_callback( void *userData );
PortAudio::PortAudio():
ringbuf(RINGBUFFERSIZE)
{
isInitialized = true;
isOpen = false;
isStarted = false;
mChannels = 0;
mRate = 0;
mLatency = 0;
pStream = NULL;
LOG4CXX_INFO(narratorPaLog, "Initializing portaudio");
mError = Pa_Initialize();
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to initialize portaudio: " << Pa_GetErrorText(mError));
isInitialized = false;
}
}
PortAudio::~PortAudio()
{
close();
if(isInitialized)
Pa_Terminate();
}
bool PortAudio::open(long rate, int channels)
{
if(mRate != rate || mChannels != channels) {
close();
}
if(!isOpen) {
//PaDeviceIndex default_device = 2;
PaDeviceIndex default_device = Pa_GetDefaultOutputDevice();
if( default_device == paNoDevice ) {
LOG4CXX_ERROR(narratorPaLog, "Pa_GetDefaultOutputDevice failed, however, device count is: " << Pa_GetDeviceCount() );
return false;
}
mOutputParameters.device = default_device; /* default output device */
mOutputParameters.channelCount = channels;
mOutputParameters.sampleFormat = paFloat32;
mOutputParameters.suggestedLatency = Pa_GetDeviceInfo( mOutputParameters.device )->defaultHighOutputLatency;
mOutputParameters.hostApiSpecificStreamInfo = NULL;
const PaDeviceInfo* devinfo = Pa_GetDeviceInfo(mOutputParameters.device);
const PaHostApiInfo* hostapiinfo = Pa_GetHostApiInfo(devinfo->hostApi);
LOG4CXX_DEBUG(narratorPaLog, "Opening device: " << devinfo->name << " (" << hostapiinfo->name << "), channels: " << channels << ", rate: " << rate <<" (" << devinfo->defaultSampleRate << ")");
unsigned long framesPerBuffer = 1024;
#ifdef WIN32
framesPerBuffer = 4096;
#endif
mError = Pa_OpenStream(&pStream, NULL, &mOutputParameters, rate, framesPerBuffer/*paFramesPerBufferUnspecified*/,
paNoFlag, pa_stream_callback, this);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to open stream: " << Pa_GetErrorText(mError));
return false;
}
mRate = rate;
mChannels = channels;
isOpen = true;
isStarted = false;
mError = Pa_SetStreamFinishedCallback(pStream, pa_stream_finished_callback);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to set FinishedCallback: " << Pa_GetErrorText(mError));
}
}
return true;
}
long PortAudio::stop()
{
if(isStarted) {
mError = Pa_StopStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to stop stream: " << Pa_GetErrorText(mError));
ringbuf.flush();
isStarted = false;
}
return mLatency;
}
long PortAudio::abort()
{
if(isStarted) {
LOG4CXX_DEBUG(narratorPaLog, "Aborting stream");
mError = Pa_AbortStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to abort stream: " << Pa_GetErrorText(mError));
ringbuf.flush();
isStarted = false;
}
return mLatency;
}
bool PortAudio::close()
{
stop();
if(isOpen) {
mError = Pa_CloseStream(pStream);
if(mError != paNoError)
{
LOG4CXX_ERROR(narratorPaLog, "Failed to close stream: " << Pa_GetErrorText(mError));
}
else
{
isOpen = false;
}
}
return true;
}
long PortAudio::getRate()
{
return mRate;
}
int PortAudio::getChannels()
{
return mChannels;
}
long PortAudio::getRemainingms()
{
size_t bufferedData = ringbuf.getReadAvailable();
long bufferms = 0;
if(mChannels != 0 && mRate != 0)
bufferms = (long) (1000.0 * bufferedData) / mChannels / mRate;
return bufferms + mLatency;
}
/*
Blocks until data can be written.
If no data can be written in 2ms*100 the stream gets restarted.
returns the amount of data that can be written.
*/
unsigned int PortAudio::getWriteAvailable()
{
size_t writeAvailable = 0;
int waitCount = 0;
int failCount = 0;
while( writeAvailable == 0 ) {
writeAvailable = ringbuf.getWriteAvailable();
if( writeAvailable == 0 ) {
usleep(200000); //200 ms
//LOG4CXX_DEBUG(narratorPaLog, "getWriteAvailable = 0, Pa_IsStreamActive = " << Pa_IsStreamActive(pStream));
}
if(waitCount++ > 10) {
LOG4CXX_ERROR(narratorPaLog, "getWriteAvailable waittime exceeded, restarting stream");
mError = Pa_AbortStream(pStream);
// If abortstream fails, try reopening
if(failCount++ > 0 || ( mError != paNoError && mError != paStreamIsStopped )) {
LOG4CXX_ERROR(narratorPaLog, "Failed to abort stream, trying to close and reopen: " << Pa_GetErrorText(mError));
mError = Pa_CloseStream(pStream);
if(mError != paNoError)
LOG4CXX_ERROR(narratorPaLog, "Failed to close stream: " << Pa_GetErrorText(mError));
isOpen = false;
open(mRate, mChannels);
}
mError = Pa_StartStream(pStream);
if(mError != paNoError) LOG4CXX_ERROR(narratorPaLog, "Failed to start stream: " << Pa_GetErrorText(mError));
isStarted = true;
waitCount = 0;
}
}
//LOG4CXX_DEBUG(narratorPaLog, "getWriteAvailable = " << writeAvailable << ", Pa_IsStreamActive = " << Pa_IsStreamActive(pStream));
return writeAvailable;
}
bool PortAudio::write(float *buffer, unsigned int samples)
{
size_t elemWritten = ringbuf.writeElements(buffer, samples*mChannels);
// Try starting the stream
if(!isStarted && ringbuf.getWriteAvailable() <= (RINGBUFFERSIZE/2)) {
LOG4CXX_TRACE(narratorPaLog, "Starting stream");
mError = Pa_StartStream(pStream);
if(mError != paNoError) {
LOG4CXX_ERROR(narratorPaLog, "Failed to start stream: " << Pa_GetErrorText(mError));
}
mLatency = (long) (Pa_GetStreamInfo(pStream)->outputLatency * 1000.0);
isStarted = true;
}
else if(!isStarted )
LOG4CXX_TRACE(narratorPaLog, "Buffering: " << ((RINGBUFFERSIZE - ringbuf.getWriteAvailable()) * 100) / (RINGBUFFERSIZE) << "%");
if( elemWritten < samples)
return false;
return false;
}
long unsigned int min( long unsigned int a, long unsigned int b )
{
if( a < b )
return a;
return b;
}
/*
@note With the exception of Pa_GetStreamCpuLoad() it is not permissable to call
PortAudio API functions from within the stream callback.
*/
int pa_stream_callback(
const void *input,
void *output, // Write frameCount*channels here
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
(void) timeInfo; /* Prevent unused variable warning. */
(void) input; /* Prevent unused variable warning. */
//if(statusFlags & paOutputUnderflow)
// LOG4CXX_WARN(narratorPaLog, "Output underflow!");
//if(statusFlags & paOutputOverflow)
// LOG4CXX_WARN(narratorPaLog, "Output overflow!");
//if(statusFlags & paPrimingOutput)
// LOG4CXX_WARN(narratorPaLog, "Priming output!");
static long underrunms = 0;
RingBuffer *ringbuf = &((PortAudio*)userData)->ringbuf;
int channels = ((PortAudio*)userData)->mChannels;
long rate = ((PortAudio*)userData)->mRate;
float* outbuf = (float*)output;
size_t elementsRead = ringbuf->readElements(outbuf, frameCount * channels);
if( elementsRead < frameCount*channels ) {
memset( (outbuf+(elementsRead)), 0, (frameCount*channels-elementsRead)*sizeof(float) );
underrunms += (long) (frameCount * channels * 1000.0) / rate;
//LOG4CXX_DEBUG(narratorPaLog, " Less read than requested, underrun ms:" << underrunms );
} else {
//LOG4CXX_TRACE(narratorPaLog, " availableElements: " << availableElements << " elementsToRead: " << elementsToRead << " elementsRead:" << elementsRead);
underrunms = 0;
}
if(underrunms > 500) return paComplete;
return paContinue; // paAbort, paComplete
}
void pa_stream_finished_callback( void *userData )
{
((PortAudio*)userData)->isStarted = false;
//std::cout << __FUNCTION__ << " Finished" << std::endl;
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <iterator>
#include <utility>
namespace helene
{
namespace detail
{
template <class Iterator, class IteratorTag>
constexpr bool is_iterator_of_category_v =
std::is_same<typename std::iterator_traits<Iterator>::iterator_category,
IteratorTag>::value;
template <class Iterator, class IteratorTag>
constexpr bool is_at_least_iterator_of_category_v = std::is_base_of<
IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>::value;
} // namespace detail
/** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp>
*
* \brief An iterator adaptor that adapts any iterator to wrap around when
* incremented beyond a range determined on construction
*/
template <class UnderlyingIterator>
class circular_iterator
{
// friend declarations primary purose to allow private member access when
// converting to const_iterator version of UnderlyingIterator
template <class OtherUnderlying>
friend class circular_iterator;
public:
static_assert(
detail::is_at_least_iterator_of_category_v<
UnderlyingIterator,
std::random_access_iterator_tag>,
"circular_iterator requires random access underlying iterator");
typedef typename std::iterator_traits<UnderlyingIterator>::value_type
value_type;
typedef typename std::iterator_traits<UnderlyingIterator>::difference_type
difference_type;
typedef
typename std::iterator_traits<UnderlyingIterator>::reference reference;
typedef typename std::iterator_traits<UnderlyingIterator>::pointer pointer;
typedef std::random_access_iterator_tag iterator_category;
public:
circular_iterator() = default;
circular_iterator(UnderlyingIterator first,
UnderlyingIterator last,
UnderlyingIterator current)
: wrap_size_(std::distance(first, last)),
index_(std::distance(first, current)),
base_(first)
{
}
// converting constructor primary purpose for conversion to const_iterator
// underlying
template <class OtherUnderlying>
circular_iterator(const circular_iterator<OtherUnderlying>& other)
: wrap_size_(other.wrap_size_), index_(other.index_), base_(other.base_)
{
}
bool
operator==(const circular_iterator& other)
{
const auto base_diff = base_ - other.base_;
return base_diff == other.index_ - index_;
}
bool
operator!=(const circular_iterator& other)
{
return !operator==(other);
}
reference operator*()
{
return base_[local_index(index_)];
}
circular_iterator&
operator++()
{
++index_;
return *this;
}
circular_iterator
operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
circular_iterator&
operator--()
{
--index_;
return *this;
}
circular_iterator
operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
circular_iterator&
operator+=(difference_type n)
{
index_ += n;
return *this;
}
circular_iterator&
operator-=(difference_type n)
{
index_ -= n;
return *this;
}
friend circular_iterator
operator+(const circular_iterator& lhs, difference_type rhs)
{
auto temp = lhs;
temp += rhs;
return temp;
}
friend circular_iterator
operator+(difference_type lhs, const circular_iterator& rhs)
{
return rhs + lhs;
}
friend circular_iterator
operator-(const circular_iterator& lhs, difference_type rhs)
{
auto temp = lhs;
temp -= rhs;
return temp;
}
difference_type
operator-(const circular_iterator& other)
{
return index_ - other.index_;
}
typename circular_iterator::reference
operator[](typename circular_iterator::difference_type n)
{
return base_[local_index(index_ + n)];
}
bool
operator<(const circular_iterator& other)
{
return index_ < other.index_;
}
bool
operator>(const circular_iterator& other)
{
return index_ > other.index_;
}
bool
operator<=(const circular_iterator& other)
{
return index_ <= other.index_;
}
bool
operator>=(const circular_iterator& other)
{
return index_ >= other.index_;
}
private:
difference_type
local_index(difference_type index) const
{
const auto remainder = index % wrap_size_;
if(remainder < 0)
{
return wrap_size_ + remainder;
}
else
{
return remainder;
}
}
private:
difference_type wrap_size_;
difference_type index_;
UnderlyingIterator base_;
};
} // namespace helene
<commit_msg>Add underlying_position and wrap_size member functions to circular_iterator. modified: include/circular_iterator.hpp<commit_after>#pragma once
#include <type_traits>
#include <iterator>
#include <utility>
namespace helene
{
namespace detail
{
template <class Iterator, class IteratorTag>
constexpr bool is_iterator_of_category_v =
std::is_same<typename std::iterator_traits<Iterator>::iterator_category,
IteratorTag>::value;
template <class Iterator, class IteratorTag>
constexpr bool is_at_least_iterator_of_category_v = std::is_base_of<
IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>::value;
} // namespace detail
/** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp>
*
* \brief An iterator adaptor that adapts any iterator to wrap around when
* incremented beyond a range determined on construction
*/
template <class UnderlyingIterator>
class circular_iterator
{
// friend declarations primary purose to allow private member access when
// converting to const_iterator version of UnderlyingIterator
template <class OtherUnderlying>
friend class circular_iterator;
public:
static_assert(
detail::is_at_least_iterator_of_category_v<
UnderlyingIterator,
std::random_access_iterator_tag>,
"circular_iterator requires random access underlying iterator");
typedef typename std::iterator_traits<UnderlyingIterator>::value_type
value_type;
typedef typename std::iterator_traits<UnderlyingIterator>::difference_type
difference_type;
typedef
typename std::iterator_traits<UnderlyingIterator>::reference reference;
typedef typename std::iterator_traits<UnderlyingIterator>::pointer pointer;
typedef std::random_access_iterator_tag iterator_category;
public:
circular_iterator() = default;
circular_iterator(UnderlyingIterator first,
UnderlyingIterator last,
UnderlyingIterator current)
: wrap_size_(std::distance(first, last)),
index_(std::distance(first, current)),
base_(first)
{
}
// converting constructor primary purpose for conversion to const_iterator
// underlying
template <class OtherUnderlying>
circular_iterator(const circular_iterator<OtherUnderlying>& other)
: wrap_size_(other.wrap_size_), index_(other.index_), base_(other.base_)
{
}
bool
operator==(const circular_iterator& other)
{
const auto base_diff = base_ - other.base_;
return base_diff == other.index_ - index_;
}
bool
operator!=(const circular_iterator& other)
{
return !operator==(other);
}
reference operator*()
{
return base_[local_index(index_)];
}
circular_iterator&
operator++()
{
++index_;
return *this;
}
circular_iterator
operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
circular_iterator&
operator--()
{
--index_;
return *this;
}
circular_iterator
operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
circular_iterator&
operator+=(difference_type n)
{
index_ += n;
return *this;
}
circular_iterator&
operator-=(difference_type n)
{
index_ -= n;
return *this;
}
friend circular_iterator
operator+(const circular_iterator& lhs, difference_type rhs)
{
auto temp = lhs;
temp += rhs;
return temp;
}
friend circular_iterator
operator+(difference_type lhs, const circular_iterator& rhs)
{
return rhs + lhs;
}
friend circular_iterator
operator-(const circular_iterator& lhs, difference_type rhs)
{
auto temp = lhs;
temp -= rhs;
return temp;
}
difference_type
operator-(const circular_iterator& other)
{
return index_ - other.index_;
}
typename circular_iterator::reference
operator[](typename circular_iterator::difference_type n)
{
return base_[local_index(index_ + n)];
}
bool
operator<(const circular_iterator& other)
{
return index_ < other.index_;
}
bool
operator>(const circular_iterator& other)
{
return index_ > other.index_;
}
bool
operator<=(const circular_iterator& other)
{
return index_ <= other.index_;
}
bool
operator>=(const circular_iterator& other)
{
return index_ >= other.index_;
}
public:
difference_type
underlying_position() const
{
return index_;
}
difference_type
wrap_size() const
{
return wrap_size_;
}
private:
difference_type
local_index(difference_type index) const
{
const auto remainder = index % wrap_size_;
if(remainder < 0)
{
return wrap_size_ + remainder;
}
else
{
return remainder;
}
}
private:
difference_type wrap_size_;
difference_type index_;
UnderlyingIterator base_;
};
} // namespace helene
<|endoftext|> |
<commit_before>/*
* Copyright 2021 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skottie/src/effects/Effects.h"
#include "include/effects/SkRuntimeEffect.h"
#include "modules/skottie/src/Adapter.h"
#include "modules/skottie/src/SkottieJson.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGColorFilter.h"
namespace skottie::internal {
#ifdef SK_ENABLE_SKSL
namespace {
class SkSLShaderNode final : public sksg::CustomRenderNode {
public:
explicit SkSLShaderNode(sk_sp<RenderNode> child) : INHERITED({std::move(child)}) {}
SG_ATTRIBUTE(Shader, sk_sp<SkShader>, fEffectShader)
private:
SkRect onRevalidate(sksg::InvalidationController* ic, const SkMatrix& ctm) override {
const auto& child = this->children()[0];
return child->revalidate(ic, ctm);
}
void onRender(SkCanvas* canvas, const RenderContext* ctx) const override {
const auto& bounds = this->bounds();
const auto local_ctx = ScopedRenderContext(canvas, ctx)
.setIsolation(bounds, canvas->getTotalMatrix(), true);
canvas->saveLayer(&bounds, nullptr);
this->children()[0]->render(canvas, local_ctx);
SkPaint effect_paint;
effect_paint.setShader(fEffectShader);
effect_paint.setBlendMode(SkBlendMode::kSrcIn);
canvas->drawPaint(effect_paint);
}
const RenderNode* onNodeAt(const SkPoint&) const override { return nullptr; } // no hit-testing
sk_sp<SkShader> fEffectShader;
using INHERITED = sksg::CustomRenderNode;
};
class SkSLEffectAdapter final : public DiscardableAdapterBase<SkSLEffectAdapter,
SkSLShaderNode> {
public:
SkSLEffectAdapter(const skjson::ArrayValue& jprops,
const AnimationBuilder& abuilder,
sk_sp<SkSLShaderNode> node)
: INHERITED(std::move(node))
{
enum : size_t {
kSkSL_index = 0,
kFirstUniform_index = 1,
};
if (jprops.size() < 1) {
return;
}
const skjson::ObjectValue* jSkSL = jprops[kSkSL_index];
if (!jSkSL) {
return;
}
const skjson::StringValue* jShader = (*jSkSL)["sh"];
if (!jShader) {
return;
}
SkString shader = SkString(jShader->begin(), jShader->size());
auto result = SkRuntimeEffect::MakeForShader(shader, {});
if (!result.effect) {
abuilder.log(Logger::Level::kError, nullptr, "Failed to parse SkSL shader: %s",
result.errorText.c_str());
return;
}
fEffect = std::move(result.effect);
// construct dynamic uniform list from jprops, skip SkSL property
for (size_t i = kFirstUniform_index; i < jprops.size(); i++) {
const skjson::ObjectValue* jprop = jprops[i];
if (!jprop) { continue; }
const skjson::StringValue* uniformName = (*jprop)["nm"];
if (!uniformName) { continue; }
auto uniformTuple = std::make_tuple(SkString(uniformName->begin(),
uniformName->size()),
std::make_unique<VectorValue>());
fUniforms.push_back(std::move(uniformTuple));
this->bind(abuilder, (*jprop)["v"], std::get<1>(fUniforms.back()).get());
}
}
private:
void onSync() override {
this->node()->setShader(buildEffectShader());
}
sk_sp<SkShader> buildEffectShader() const {
if (!fEffect) {
return nullptr;
}
// TODO: consider dumping builder and work with lower level API
SkRuntimeShaderBuilder builder = SkRuntimeShaderBuilder(fEffect);
for (const auto& uniform : fUniforms) {
const auto& name = std::get<0>(uniform);
const auto& data = std::get<1>(uniform);
auto metadata = fEffect->findUniform(name.c_str());
// TODO: build SkData from SkRuntimeEffect::Uniform data
switch (metadata->type) {
case SkRuntimeEffect::Uniform::Type::kFloat:
builder.uniform(name.c_str()) = data->at(0); break;
default:
printf("!!! %s\n", "uniform data type not supported");
}
}
return builder.makeShader(&SkMatrix::I(), false);
}
sk_sp<SkRuntimeEffect> fEffect;
std::vector<std::tuple<SkString, std::unique_ptr<VectorValue>>> fUniforms;
using INHERITED = DiscardableAdapterBase<SkSLEffectAdapter, SkSLShaderNode>;
};
} // namespace
#endif // SK_ENABLE_SKSL
sk_sp<sksg::RenderNode> EffectBuilder::attachSkSLEffect(const skjson::ArrayValue& jprops,
sk_sp<sksg::RenderNode> layer) const {
#ifdef SK_ENABLE_SKSL
auto shaderNode = sk_make_sp<SkSLShaderNode>(std::move(layer));
return fBuilder->attachDiscardableAdapter<SkSLEffectAdapter>(jprops, *fBuilder, shaderNode);
#else
return layer;
#endif
}
} // namespace skottie::internal
<commit_msg>discard SkRuntimeEffect builder in SkSLEffect to use lower level API<commit_after>/*
* Copyright 2021 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skottie/src/effects/Effects.h"
#include "include/effects/SkRuntimeEffect.h"
#include "include/private/SkMalloc.h"
#include "modules/skottie/src/Adapter.h"
#include "modules/skottie/src/SkottieJson.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGColorFilter.h"
namespace skottie::internal {
#ifdef SK_ENABLE_SKSL
namespace {
class SkSLShaderNode final : public sksg::CustomRenderNode {
public:
explicit SkSLShaderNode(sk_sp<RenderNode> child) : INHERITED({std::move(child)}) {}
SG_ATTRIBUTE(Shader, sk_sp<SkShader>, fEffectShader)
private:
SkRect onRevalidate(sksg::InvalidationController* ic, const SkMatrix& ctm) override {
const auto& child = this->children()[0];
return child->revalidate(ic, ctm);
}
void onRender(SkCanvas* canvas, const RenderContext* ctx) const override {
const auto& bounds = this->bounds();
const auto local_ctx = ScopedRenderContext(canvas, ctx)
.setIsolation(bounds, canvas->getTotalMatrix(), true);
canvas->saveLayer(&bounds, nullptr);
this->children()[0]->render(canvas, local_ctx);
SkPaint effect_paint;
effect_paint.setShader(fEffectShader);
effect_paint.setBlendMode(SkBlendMode::kSrcIn);
canvas->drawPaint(effect_paint);
}
const RenderNode* onNodeAt(const SkPoint&) const override { return nullptr; } // no hit-testing
sk_sp<SkShader> fEffectShader;
using INHERITED = sksg::CustomRenderNode;
};
class SkSLEffectAdapter final : public DiscardableAdapterBase<SkSLEffectAdapter,
SkSLShaderNode> {
public:
SkSLEffectAdapter(const skjson::ArrayValue& jprops,
const AnimationBuilder& abuilder,
sk_sp<SkSLShaderNode> node)
: INHERITED(std::move(node))
{
enum : size_t {
kSkSL_index = 0,
kFirstUniform_index = 1,
};
if (jprops.size() < 1) {
return;
}
const skjson::ObjectValue* jSkSL = jprops[kSkSL_index];
if (!jSkSL) {
return;
}
const skjson::StringValue* jShader = (*jSkSL)["sh"];
if (!jShader) {
return;
}
SkString shader = SkString(jShader->begin(), jShader->size());
auto result = SkRuntimeEffect::MakeForShader(shader, {});
if (!result.effect) {
abuilder.log(Logger::Level::kError, nullptr, "Failed to parse SkSL shader: %s",
result.errorText.c_str());
return;
}
fEffect = std::move(result.effect);
// construct dynamic uniform list from jprops, skip SkSL property
for (size_t i = kFirstUniform_index; i < jprops.size(); i++) {
const skjson::ObjectValue* jprop = jprops[i];
if (!jprop) { continue; }
const skjson::StringValue* uniformName = (*jprop)["nm"];
if (!uniformName) { continue; }
auto uniformTuple = std::make_tuple(SkString(uniformName->begin(),
uniformName->size()),
std::make_unique<VectorValue>());
fUniforms.push_back(std::move(uniformTuple));
this->bind(abuilder, (*jprop)["v"], std::get<1>(fUniforms.back()).get());
}
}
private:
void onSync() override {
if (!fEffect) {
return;
}
sk_sp<SkShader> shader = fEffect->makeShader(buildUniformData(), {/* TODO: child support */}, &SkMatrix::I(), false);
this->node()->setShader(std::move(shader));
}
sk_sp<SkData> buildUniformData() const {
auto uniformData = SkData::MakeUninitialized(fEffect->uniformSize());
SkASSERT(uniformData);
sk_bzero(uniformData->writable_data(), uniformData->size());
for (const auto& uniform : fUniforms) {
const auto& name = std::get<0>(uniform);
const auto& data = std::get<1>(uniform);
auto metadata = fEffect->findUniform(name.c_str());
if (metadata && metadata->count == static_cast<int>(data->size())) {
auto dst = reinterpret_cast<uint8_t*>(uniformData->writable_data()) + metadata->offset;
memcpy(reinterpret_cast<void*>(dst), data->data(), data->size() * sizeof(float));
} else {
SkDebugf("cannot set malformed uniform: %s", name.c_str());
}
}
return uniformData;
}
sk_sp<SkRuntimeEffect> fEffect;
std::vector<std::tuple<SkString, std::unique_ptr<VectorValue>>> fUniforms;
using INHERITED = DiscardableAdapterBase<SkSLEffectAdapter, SkSLShaderNode>;
};
} // namespace
#endif // SK_ENABLE_SKSL
sk_sp<sksg::RenderNode> EffectBuilder::attachSkSLEffect(const skjson::ArrayValue& jprops,
sk_sp<sksg::RenderNode> layer) const {
#ifdef SK_ENABLE_SKSL
auto shaderNode = sk_make_sp<SkSLShaderNode>(std::move(layer));
return fBuilder->attachDiscardableAdapter<SkSLEffectAdapter>(jprops, *fBuilder, shaderNode);
#else
return layer;
#endif
}
} // namespace skottie::internal
<|endoftext|> |
<commit_before>/*
Copyright 2014 Rogier van Dalen.
This file is part of Rogier van Dalen's Mathematical tools library for C++.
This library 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 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 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/>.
*/
/** \file
Define a magma that is a tuple of other magmas, where "plus" takes the best of
the two values according to a lexicographical ordering.
*/
#ifndef MATH_LEXICOGRAPHICAL_HPP_INCLUDED
#define MATH_LEXICOGRAPHICAL_HPP_INCLUDED
#include <type_traits>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>
#include "meta/vector.hpp"
#include "meta/all.hpp"
#include "utility/type_sequence_traits.hpp"
#include "range/tuple.hpp"
#include "range/call_unpack.hpp"
#include "range/equal.hpp"
#include "range/less_lexicographical.hpp"
#include "range/transform.hpp"
#include "range/all.hpp"
#include "magma.hpp"
#include "detail/tuple_helper.hpp"
namespace math {
/**
The lexicographical semiring.
This is a semiring that has multiple components.
Operations \ref plus and \ref choose are defined as taking the best in a strict
weak ordering.
The ordering is defined by lexicographical comparison: if the first components
are the same, the second components are compared, et cetera.
Often, the user will not care about the ordering of the later components, but it
still needs to be defined to make this a proper semiring.
For example, the first component could be of type \ref cost or
\ref max_semiring, indicating a cost or probability.
The components following it could form the payload, for example, the word
sequence.
Used on the correct automaton, the right algorithm might yield the lowest-cost
or highest-probability word sequence.
All components must be monoids over \ref times, and have \ref choose defined.
The first component must be a semiring over \ref times and \ref choose.
Each of the other elements must almost be a semiring, but does not have to have
a multiplicative annihilator.
The first component is used to indicate the additive identity (and, thus, the
multiplicative annihilator), \ref zero(), of the whole semiring.
When the first component is zero, the meaning of the whole semiring object is
the additive identity, whatever the value of the other components.
Any two objects with the first component equal and the additive identity will
therefore compare equal.
Such objects can, however, have detectably different elements after the first
component.
This type is implicitly convertible from another lexicographical semiring if
all components are.
It is explicitly convertible from if one or more of the components is explicitly
convertible (and the rest is implicitly convertible).
This semiring does not have \ref divide.
This would require each component to be divided, which is impossible if any is
an annihilator.
Then, any element of a lexicographical semiring that has any component that is
an annihilator would have to be an annihilator itself.
This is functionality that could be added, but should not be the default.
It is not currently implemented.
lexicographical objects can be constructed explicitly with a list of argument,
each of which is pairwise convertible to the component.
They can also be constructed from a compatible lexicographical: implicitly if
all components are implicitly convertible; and explicitly if some are only
explicitly convertible.
It has a member function \c components() which returns the range with the
components in order.
\tparam Components
Type of the form \ref over\<...> with the magmas that should be contained.
All the magmas must have an ordered \c choose.
The first of them must be a semiring over \c times and \c choose.
The rest must be semirings except for the annihilator.
That is, each must be a commutative monoid over \c choose; a monoid over
\c times; and \c times must distribute over \c choose.
\internal
There is some documentation of members in lexicographical <over <...>>, but
Sphinx refuses some of the syntax anyway.
*/
template <class Components> class lexicographical;
template <class ComponentTags> struct lexicographical_tag;
template <class ... Components>
struct decayed_magma_tag <lexicographical <over <Components ...>>>
{
typedef lexicographical_tag <
over <typename magma_tag <Components>::type ...>> type;
};
template <class ... Components> class lexicographical <over <Components ...>> {
public:
typedef meta::vector <Components ...> component_types;
typedef range::tuple <Components ...> components_type;
private:
typedef typename meta::first <component_types>::type first_component_type;
typedef typename meta::drop <component_types>::type rest_component_type;
static_assert (meta::all <meta::vector <std::is_same <
Components, typename std::decay <Components>::type> ...>>::value,
"The components may not be cv- or reference-qualified.");
static_assert (meta::all <meta::vector <
has <callable::order <callable::choose> (Components, Components)> ...
>>::value, "All components must have an ordered 'choose'.");
static_assert (meta::all <meta::vector <
is::monoid <callable::times, Components> ...>>::value,
"All components must be monoids over 'times'.");
static_assert (meta::all <meta::vector <
is::monoid <callable::choose, Components> ...>>::value,
"All components must be monoids over 'choose'.");
static_assert (meta::all <meta::vector <
is::commutative <callable::choose, Components> ...>>::value,
"For all components, 'choose' must be commutative.");
public:
/**
Evaluate to \c true iff this is a semiring in \a Direction.
For this to be true, the first component must be a semiring in \a Direction,
and for the other components, \c times is distributive over \c choose in
\a Direction.
*/
template <class Direction> struct is_semiring
: boost::mpl::and_ <
is::semiring <Direction,
callable::times, callable::choose, first_component_type>,
meta::all <meta::vector <is::distributive <Direction,
callable::times, callable::choose, Components> ...>>
> {};
static_assert (is_semiring <left>::value || is_semiring <right>::value,
"The components must allow this to be a semiring in at least one "
"direction.");
components_type components_;
public:
/**
Construct from arguments that are pairwise convertible to the components.
This constructor is implicit.
*/
template <class ... Arguments, class Enable = typename boost::enable_if <
utility::are_constructible <
meta::vector <Components ...>, meta::vector <Arguments ...>>>::type>
explicit lexicographical (Arguments && ... arguments)
: components_ (std::forward <Arguments> (arguments) ...) {}
lexicographical (lexicographical const &) = default;
lexicographical (lexicographical &&) = default;
/**
Construct from a lexicographical with different component types, all of
which are implicitly convertible to the component types of this.
This constructor is implicit.
\param other The lexicographical to copy.
*/
template <class ... OtherComponents, class Enable = typename
boost::enable_if <utility::are_convertible <
meta::vector <OtherComponents const & ...>,
meta::vector <Components ...>>
>::type>
lexicographical (lexicographical <over <OtherComponents ...>> const & other)
: components_ (other.components()) {}
/**
Construct from a lexicographical with different component types, at least
one of which is explicitly convertible and not implicitly convertible.
This constructor is explicit.
\param other The lexicographical to copy.
*/
template <class ... OtherComponents>
explicit lexicographical (
lexicographical <over <OtherComponents ...>> const & other, typename
boost::enable_if <
tuple_helper::components_constructible_only <
meta::vector <Components ...>,
meta::vector <OtherComponents const & ...>>
>::type * = 0)
: components_ (other.components()) {}
lexicographical & operator = (lexicographical const &) = default;
lexicographical & operator = (lexicographical &&) = default;
components_type & components() { return components_; }
components_type const & components() const { return components_; }
};
namespace callable {
struct make_lexicographical {
template <class ... Components>
lexicographical <over <Components ...>> operator() (
Components const & ... components) const
{ return lexicographical <over <Components ...>> (components ...); }
};
struct make_lexicographical_over {
template <class Components>
auto operator() (Components && components) const
RETURNS (range::call_unpack (
make_lexicographical(), std::forward <Components> (components)));
};
} // namespace callable
static auto constexpr make_lexicographical = callable::make_lexicographical();
static auto constexpr make_lexicographical_over
= callable::make_lexicographical_over();
namespace detail {
template <class Type> struct is_lexicographical_tag : boost::mpl::false_ {};
template <class ... ComponentTags> struct is_lexicographical_tag <
lexicographical_tag <over <ComponentTags ...>>>
: boost::mpl::true_ {};
} // namespace detail
namespace operation {
namespace tuple_helper {
template <class ... ComponentTags> struct get_components <
lexicographical_tag <over <ComponentTags ...>>>
{
template <class Lexicographical>
auto operator() (Lexicographical const & l) const
RETURNS (l.components());
};
} // namespace tuple_helper
/* Queries. */
template <class ... ComponentTags>
struct is_member <lexicographical_tag <over <ComponentTags ...>>>
{
template <class Lexicographical>
auto operator() (Lexicographical const & l) const
RETURNS (range::all (range::transform (
::math::is_member, l.components())));
};
// is_annihilator.
/*
If the operation has an inverse: any component being an annihilator makes
the whole product an annihilator.
If not, then the default implementation (compare component-per-component
with the result of annihilator()) works.
*/
template <class ComponentTags> struct is_annihilator <
lexicographical_tag <ComponentTags>, callable::times>
{
template <class Lexicographical> auto operator() (
Lexicographical const & l) const
RETURNS (math::is_annihilator <callable::times> (
range::first (l.components())));
};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct equal <lexicographical_tag <ComponentTags>>
: tuple_helper::equal_if_annihilator <callable::times,
tuple_helper::equal_components <math::callable::equal>> {};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct approximately_equal <lexicographical_tag <ComponentTags>>
: tuple_helper::equal_if_annihilator <callable::times,
tuple_helper::equal_components <math::callable::approximately_equal>>
{};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct compare <lexicographical_tag <ComponentTags>>
: tuple_helper::compare_if_annihilator <callable::times,
tuple_helper::compare_components <math::callable::compare>> {};
/* Produce. */
template <class ... ComponentTags>
struct identity <lexicographical_tag <over <ComponentTags ...>>,
callable::times>
{
auto operator() () const
RETURNS (make_lexicographical (
identity <ComponentTags, callable::times>()() ...));
};
/**
Generalised 0.
This is (0, 1 ...) because apart from for the first component, the plus
operation is not guaranteed to be defined.
*/
template <class FirstComponentTag, class ... ComponentTags>
struct identity <lexicographical_tag <over <
FirstComponentTag, ComponentTags ...>>, callable::choose>
{
auto operator() () const
RETURNS (make_lexicographical (
identity <FirstComponentTag, callable::choose>()(),
identity <ComponentTags, callable::times>()() ...));
};
// plus: forward to implementation for "choose".
template <class Tags>
struct identity <lexicographical_tag <Tags>, callable::plus>
: identity <lexicographical_tag <Tags>, callable::choose> {};
/**
Multiplicative annihilator: equal to the additive identity.
*/
template <class FirstComponentTag, class ... ComponentTags>
struct annihilator <lexicographical_tag <over <
FirstComponentTag, ComponentTags ...>>, callable::times>
{
auto operator() () const
RETURNS (make_lexicographical (
annihilator <FirstComponentTag, callable::times>()(),
identity <ComponentTags, callable::times>()() ...));
};
/* Operations. */
template <class Tags>
struct order <lexicographical_tag <Tags>, callable::choose>
: tuple_helper::compare_components <
math::callable::order <callable::choose>> {};
// order <plus>: forward to order <choose>.
template <class Tags>
struct order <lexicographical_tag <Tags>, callable::plus>
: order <lexicographical_tag <Tags>, callable::choose> {};
/**
Apply the multiplication operation on the weights, and on the values.
*/
template <class ... ComponentTags>
struct times <lexicographical_tag <over <ComponentTags ...>>>
: tuple_helper::binary_operation <callable::make_lexicographical,
meta::vector <times <ComponentTags> ...>> {};
// Semiring under times and choose/plus: depends on the direction.
template <class FirstComponentTag, class ... ComponentTags, class Direction>
struct is_semiring <
lexicographical_tag <over <FirstComponentTag, ComponentTags ...>>,
Direction, callable::times, callable::choose>
: meta::all <meta::vector <
is_semiring <FirstComponentTag,
Direction, callable::times, callable::choose>,
is_distributive <ComponentTags,
Direction, callable::times, callable::choose> ...>> {};
template <class ComponentTags, class Direction> struct is_semiring <
lexicographical_tag <ComponentTags>,
Direction, callable::times, callable::plus>
: is_semiring <lexicographical_tag <ComponentTags>,
Direction, callable::times, callable::choose> {};
/*
divide is undefined.
It would have to call divide on all its components, and if one of them was
an annihilator, the whole lexicographical semiring would have to be an
annihilator.
This would probably require an interface similar to product's.
*/
template <class ... Tags>
struct print <lexicographical_tag <over <Tags ...>>>
: tuple_helper::print_components <meta::vector <Tags ...>> {};
template <class ... ComponentTags,
class ... Components1, class ... Components2>
struct unify_type <lexicographical_tag <over <ComponentTags ...>>,
lexicographical <over <Components1 ...>>,
lexicographical <over <Components2 ...>>>
{
// Unify both underlying types in parallel.
typedef lexicographical <over <typename unify_type <
ComponentTags, Components1, Components2>::type ...>> type;
};
} // namespace operation
MATH_MAGMA_GENERATE_OPERATORS (detail::is_lexicographical_tag)
} // namespace math
#endif // MATH_LEXICOGRAPHICAL_HPP_INCLUDED
<commit_msg>Rephrase SFINAE for a lexicographical constructor<commit_after>/*
Copyright 2014 Rogier van Dalen.
This file is part of Rogier van Dalen's Mathematical tools library for C++.
This library 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 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 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/>.
*/
/** \file
Define a magma that is a tuple of other magmas, where "plus" takes the best of
the two values according to a lexicographical ordering.
*/
#ifndef MATH_LEXICOGRAPHICAL_HPP_INCLUDED
#define MATH_LEXICOGRAPHICAL_HPP_INCLUDED
#include <type_traits>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>
#include "meta/vector.hpp"
#include "meta/all.hpp"
#include "utility/type_sequence_traits.hpp"
#include "range/tuple.hpp"
#include "range/call_unpack.hpp"
#include "range/equal.hpp"
#include "range/less_lexicographical.hpp"
#include "range/transform.hpp"
#include "range/all.hpp"
#include "magma.hpp"
#include "detail/tuple_helper.hpp"
namespace math {
/**
The lexicographical semiring.
This is a semiring that has multiple components.
Operations \ref plus and \ref choose are defined as taking the best in a strict
weak ordering.
The ordering is defined by lexicographical comparison: if the first components
are the same, the second components are compared, et cetera.
Often, the user will not care about the ordering of the later components, but it
still needs to be defined to make this a proper semiring.
For example, the first component could be of type \ref cost or
\ref max_semiring, indicating a cost or probability.
The components following it could form the payload, for example, the word
sequence.
Used on the correct automaton, the right algorithm might yield the lowest-cost
or highest-probability word sequence.
All components must be monoids over \ref times, and have \ref choose defined.
The first component must be a semiring over \ref times and \ref choose.
Each of the other elements must almost be a semiring, but does not have to have
a multiplicative annihilator.
The first component is used to indicate the additive identity (and, thus, the
multiplicative annihilator), \ref zero(), of the whole semiring.
When the first component is zero, the meaning of the whole semiring object is
the additive identity, whatever the value of the other components.
Any two objects with the first component equal and the additive identity will
therefore compare equal.
Such objects can, however, have detectably different elements after the first
component.
This type is implicitly convertible from another lexicographical semiring if
all components are.
It is explicitly convertible from if one or more of the components is explicitly
convertible (and the rest is implicitly convertible).
This semiring does not have \ref divide.
This would require each component to be divided, which is impossible if any is
an annihilator.
Then, any element of a lexicographical semiring that has any component that is
an annihilator would have to be an annihilator itself.
This is functionality that could be added, but should not be the default.
It is not currently implemented.
lexicographical objects can be constructed explicitly with a list of argument,
each of which is pairwise convertible to the component.
They can also be constructed from a compatible lexicographical: implicitly if
all components are implicitly convertible; and explicitly if some are only
explicitly convertible.
It has a member function \c components() which returns the range with the
components in order.
\tparam Components
Type of the form \ref over\<...> with the magmas that should be contained.
All the magmas must have an ordered \c choose.
The first of them must be a semiring over \c times and \c choose.
The rest must be semirings except for the annihilator.
That is, each must be a commutative monoid over \c choose; a monoid over
\c times; and \c times must distribute over \c choose.
\internal
There is some documentation of members in lexicographical <over <...>>, but
Sphinx refuses some of the syntax anyway.
*/
template <class Components> class lexicographical;
template <class ComponentTags> struct lexicographical_tag;
template <class ... Components>
struct decayed_magma_tag <lexicographical <over <Components ...>>>
{
typedef lexicographical_tag <
over <typename magma_tag <Components>::type ...>> type;
};
template <class ... Components> class lexicographical <over <Components ...>> {
public:
typedef meta::vector <Components ...> component_types;
typedef range::tuple <Components ...> components_type;
private:
typedef typename meta::first <component_types>::type first_component_type;
typedef typename meta::drop <component_types>::type rest_component_type;
static_assert (meta::all <meta::vector <std::is_same <
Components, typename std::decay <Components>::type> ...>>::value,
"The components may not be cv- or reference-qualified.");
static_assert (meta::all <meta::vector <
has <callable::order <callable::choose> (Components, Components)> ...
>>::value, "All components must have an ordered 'choose'.");
static_assert (meta::all <meta::vector <
is::monoid <callable::times, Components> ...>>::value,
"All components must be monoids over 'times'.");
static_assert (meta::all <meta::vector <
is::monoid <callable::choose, Components> ...>>::value,
"All components must be monoids over 'choose'.");
static_assert (meta::all <meta::vector <
is::commutative <callable::choose, Components> ...>>::value,
"For all components, 'choose' must be commutative.");
public:
/**
Evaluate to \c true iff this is a semiring in \a Direction.
For this to be true, the first component must be a semiring in \a Direction,
and for the other components, \c times is distributive over \c choose in
\a Direction.
*/
template <class Direction> struct is_semiring
: boost::mpl::and_ <
is::semiring <Direction,
callable::times, callable::choose, first_component_type>,
meta::all <meta::vector <is::distributive <Direction,
callable::times, callable::choose, Components> ...>>
> {};
static_assert (is_semiring <left>::value || is_semiring <right>::value,
"The components must allow this to be a semiring in at least one "
"direction.");
components_type components_;
public:
/**
Construct from arguments that are pairwise convertible to the components.
This constructor is implicit.
*/
template <class ... Arguments, class Enable = typename boost::enable_if <
utility::are_constructible <
meta::vector <Components ...>, meta::vector <Arguments ...>>>::type>
explicit lexicographical (Arguments && ... arguments)
: components_ (std::forward <Arguments> (arguments) ...) {}
lexicographical (lexicographical const &) = default;
lexicographical (lexicographical &&) = default;
/**
Construct from a lexicographical with different component types, all of
which are implicitly convertible to the component types of this.
This constructor is implicit.
\param other The lexicographical to copy.
*/
template <class ... OtherComponents>
lexicographical (lexicographical <over <OtherComponents ...>> const & other,
typename boost::enable_if <utility::are_convertible <
meta::vector <OtherComponents const & ...>,
meta::vector <Components ...>>
>::type * = 0)
: components_ (other.components()) {}
/**
Construct from a lexicographical with different component types, at least
one of which is explicitly convertible and not implicitly convertible.
This constructor is explicit.
\param other The lexicographical to copy.
*/
template <class ... OtherComponents>
explicit lexicographical (
lexicographical <over <OtherComponents ...>> const & other, typename
boost::enable_if <
tuple_helper::components_constructible_only <
meta::vector <Components ...>,
meta::vector <OtherComponents const & ...>>
>::type * = 0)
: components_ (other.components()) {}
lexicographical & operator = (lexicographical const &) = default;
lexicographical & operator = (lexicographical &&) = default;
components_type & components() { return components_; }
components_type const & components() const { return components_; }
};
namespace callable {
struct make_lexicographical {
template <class ... Components>
lexicographical <over <Components ...>> operator() (
Components const & ... components) const
{ return lexicographical <over <Components ...>> (components ...); }
};
struct make_lexicographical_over {
template <class Components>
auto operator() (Components && components) const
RETURNS (range::call_unpack (
make_lexicographical(), std::forward <Components> (components)));
};
} // namespace callable
static auto constexpr make_lexicographical = callable::make_lexicographical();
static auto constexpr make_lexicographical_over
= callable::make_lexicographical_over();
namespace detail {
template <class Type> struct is_lexicographical_tag : boost::mpl::false_ {};
template <class ... ComponentTags> struct is_lexicographical_tag <
lexicographical_tag <over <ComponentTags ...>>>
: boost::mpl::true_ {};
} // namespace detail
namespace operation {
namespace tuple_helper {
template <class ... ComponentTags> struct get_components <
lexicographical_tag <over <ComponentTags ...>>>
{
template <class Lexicographical>
auto operator() (Lexicographical const & l) const
RETURNS (l.components());
};
} // namespace tuple_helper
/* Queries. */
template <class ... ComponentTags>
struct is_member <lexicographical_tag <over <ComponentTags ...>>>
{
template <class Lexicographical>
auto operator() (Lexicographical const & l) const
RETURNS (range::all (range::transform (
::math::is_member, l.components())));
};
// is_annihilator.
/*
If the operation has an inverse: any component being an annihilator makes
the whole product an annihilator.
If not, then the default implementation (compare component-per-component
with the result of annihilator()) works.
*/
template <class ComponentTags> struct is_annihilator <
lexicographical_tag <ComponentTags>, callable::times>
{
template <class Lexicographical> auto operator() (
Lexicographical const & l) const
RETURNS (math::is_annihilator <callable::times> (
range::first (l.components())));
};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct equal <lexicographical_tag <ComponentTags>>
: tuple_helper::equal_if_annihilator <callable::times,
tuple_helper::equal_components <math::callable::equal>> {};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct approximately_equal <lexicographical_tag <ComponentTags>>
: tuple_helper::equal_if_annihilator <callable::times,
tuple_helper::equal_components <math::callable::approximately_equal>>
{};
// Compare annihilators equal, otherwise compare components.
template <class ComponentTags>
struct compare <lexicographical_tag <ComponentTags>>
: tuple_helper::compare_if_annihilator <callable::times,
tuple_helper::compare_components <math::callable::compare>> {};
/* Produce. */
template <class ... ComponentTags>
struct identity <lexicographical_tag <over <ComponentTags ...>>,
callable::times>
{
auto operator() () const
RETURNS (make_lexicographical (
identity <ComponentTags, callable::times>()() ...));
};
/**
Generalised 0.
This is (0, 1 ...) because apart from for the first component, the plus
operation is not guaranteed to be defined.
*/
template <class FirstComponentTag, class ... ComponentTags>
struct identity <lexicographical_tag <over <
FirstComponentTag, ComponentTags ...>>, callable::choose>
{
auto operator() () const
RETURNS (make_lexicographical (
identity <FirstComponentTag, callable::choose>()(),
identity <ComponentTags, callable::times>()() ...));
};
// plus: forward to implementation for "choose".
template <class Tags>
struct identity <lexicographical_tag <Tags>, callable::plus>
: identity <lexicographical_tag <Tags>, callable::choose> {};
/**
Multiplicative annihilator: equal to the additive identity.
*/
template <class FirstComponentTag, class ... ComponentTags>
struct annihilator <lexicographical_tag <over <
FirstComponentTag, ComponentTags ...>>, callable::times>
{
auto operator() () const
RETURNS (make_lexicographical (
annihilator <FirstComponentTag, callable::times>()(),
identity <ComponentTags, callable::times>()() ...));
};
/* Operations. */
template <class Tags>
struct order <lexicographical_tag <Tags>, callable::choose>
: tuple_helper::compare_components <
math::callable::order <callable::choose>> {};
// order <plus>: forward to order <choose>.
template <class Tags>
struct order <lexicographical_tag <Tags>, callable::plus>
: order <lexicographical_tag <Tags>, callable::choose> {};
/**
Apply the multiplication operation on the weights, and on the values.
*/
template <class ... ComponentTags>
struct times <lexicographical_tag <over <ComponentTags ...>>>
: tuple_helper::binary_operation <callable::make_lexicographical,
meta::vector <times <ComponentTags> ...>> {};
// Semiring under times and choose/plus: depends on the direction.
template <class FirstComponentTag, class ... ComponentTags, class Direction>
struct is_semiring <
lexicographical_tag <over <FirstComponentTag, ComponentTags ...>>,
Direction, callable::times, callable::choose>
: meta::all <meta::vector <
is_semiring <FirstComponentTag,
Direction, callable::times, callable::choose>,
is_distributive <ComponentTags,
Direction, callable::times, callable::choose> ...>> {};
template <class ComponentTags, class Direction> struct is_semiring <
lexicographical_tag <ComponentTags>,
Direction, callable::times, callable::plus>
: is_semiring <lexicographical_tag <ComponentTags>,
Direction, callable::times, callable::choose> {};
/*
divide is undefined.
It would have to call divide on all its components, and if one of them was
an annihilator, the whole lexicographical semiring would have to be an
annihilator.
This would probably require an interface similar to product's.
*/
template <class ... Tags>
struct print <lexicographical_tag <over <Tags ...>>>
: tuple_helper::print_components <meta::vector <Tags ...>> {};
template <class ... ComponentTags,
class ... Components1, class ... Components2>
struct unify_type <lexicographical_tag <over <ComponentTags ...>>,
lexicographical <over <Components1 ...>>,
lexicographical <over <Components2 ...>>>
{
// Unify both underlying types in parallel.
typedef lexicographical <over <typename unify_type <
ComponentTags, Components1, Components2>::type ...>> type;
};
} // namespace operation
MATH_MAGMA_GENERATE_OPERATORS (detail::is_lexicographical_tag)
} // namespace math
#endif // MATH_LEXICOGRAPHICAL_HPP_INCLUDED
<|endoftext|> |
<commit_before>//===- CloneModule.cpp - Clone an entire module ---------------------------===//
//
// This file implements the CloneModule interface which makes a copy of an
// entire module.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constant.h"
#include "ValueMapper.h"
/// CloneModule - Return an exact copy of the specified module. This is not as
/// easy as it might seem because we have to worry about making copies of global
/// variables and functions, and making their (intializers and references,
/// respectively) refer to the right globals.
///
Module *CloneModule(const Module *M) {
// First off, we need to create the new module...
Module *New = new Module(M->getModuleIdentifier());
New->setEndianness(M->getEndianness());
New->setPointerSize(M->getPointerSize());
// Create the value map that maps things from the old module over to the new
// module.
std::map<const Value*, Value*> ValueMap;
// Loop over all of the global variables, making corresponding globals in the
// new module. Here we add them to the ValueMap and to the new Module. We
// don't worry about attributes or initializers, they will come later.
//
for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
ValueMap[I] = new GlobalVariable(I->getType()->getElementType(), false,
GlobalValue::ExternalLinkage, 0,
I->getName(), New);
// Loop over the functions in the module, making external functions as before
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
ValueMap[I]=new Function(cast<FunctionType>(I->getType()->getElementType()),
GlobalValue::ExternalLinkage, I->getName(), New);
// Now that all of the things that global variable initializer can refer to
// have been created, loop through and copy the global variable referrers
// over... We also set the attributes on the global now.
//
for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
GlobalVariable *GV = cast<GlobalVariable>(ValueMap[I]);
if (I->hasInitializer())
GV->setInitializer(cast<Constant>(MapValue(I->getInitializer(),
ValueMap)));
GV->setLinkage(I->getLinkage());
}
// Similarly, copy over function bodies now...
//
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
Function *F = cast<Function>(ValueMap[I]);
if (!I->isExternal()) {
Function::aiterator DestI = F->abegin();
for (Function::const_aiterator J = I->abegin(); J != I->aend(); ++J) {
DestI->setName(J->getName());
ValueMap[J] = DestI++;
}
std::vector<ReturnInst*> Returns; // Ignore returns cloned...
CloneFunctionInto(F, I, ValueMap, Returns);
}
F->setLinkage(I->getLinkage());
}
return New;
}
<commit_msg>Make sure that the cloned module retains the type symbol table entries!<commit_after>//===- CloneModule.cpp - Clone an entire module ---------------------------===//
//
// This file implements the CloneModule interface which makes a copy of an
// entire module.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/SymbolTable.h"
#include "llvm/Constant.h"
#include "ValueMapper.h"
/// CloneModule - Return an exact copy of the specified module. This is not as
/// easy as it might seem because we have to worry about making copies of global
/// variables and functions, and making their (intializers and references,
/// respectively) refer to the right globals.
///
Module *CloneModule(const Module *M) {
// First off, we need to create the new module...
Module *New = new Module(M->getModuleIdentifier());
New->setEndianness(M->getEndianness());
New->setPointerSize(M->getPointerSize());
// Copy all of the type symbol table entries over...
const SymbolTable &SymTab = M->getSymbolTable();
SymbolTable::const_iterator TypeI = SymTab.find(Type::TypeTy);
if (TypeI != SymTab.end())
for (SymbolTable::VarMap::const_iterator I = TypeI->second.begin(),
E = TypeI->second.end(); I != E; ++I)
New->addTypeName(I->first, cast<Type>(I->second));
// Create the value map that maps things from the old module over to the new
// module.
std::map<const Value*, Value*> ValueMap;
// Loop over all of the global variables, making corresponding globals in the
// new module. Here we add them to the ValueMap and to the new Module. We
// don't worry about attributes or initializers, they will come later.
//
for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
ValueMap[I] = new GlobalVariable(I->getType()->getElementType(), false,
GlobalValue::ExternalLinkage, 0,
I->getName(), New);
// Loop over the functions in the module, making external functions as before
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
ValueMap[I]=new Function(cast<FunctionType>(I->getType()->getElementType()),
GlobalValue::ExternalLinkage, I->getName(), New);
// Now that all of the things that global variable initializer can refer to
// have been created, loop through and copy the global variable referrers
// over... We also set the attributes on the global now.
//
for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
GlobalVariable *GV = cast<GlobalVariable>(ValueMap[I]);
if (I->hasInitializer())
GV->setInitializer(cast<Constant>(MapValue(I->getInitializer(),
ValueMap)));
GV->setLinkage(I->getLinkage());
}
// Similarly, copy over function bodies now...
//
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
Function *F = cast<Function>(ValueMap[I]);
if (!I->isExternal()) {
Function::aiterator DestI = F->abegin();
for (Function::const_aiterator J = I->abegin(); J != I->aend(); ++J) {
DestI->setName(J->getName());
ValueMap[J] = DestI++;
}
std::vector<ReturnInst*> Returns; // Ignore returns cloned...
CloneFunctionInto(F, I, ValueMap, Returns);
}
F->setLinkage(I->getLinkage());
}
return New;
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC.
#include "include/core/SkTypeface.h"
#include "modules/skparagraph/include/FontCollection.h"
#include "modules/skparagraph/include/Paragraph.h"
#include "modules/skparagraph/src/ParagraphImpl.h"
namespace skia {
namespace textlayout {
bool FontCollection::FamilyKey::operator==(const FontCollection::FamilyKey& other) const {
return fFamilyNames == other.fFamilyNames && fFontStyle == other.fFontStyle;
}
size_t FontCollection::FamilyKey::Hasher::operator()(const FontCollection::FamilyKey& key) const {
size_t hash = 0;
for (const SkString& family : key.fFamilyNames) {
hash ^= std::hash<std::string>()(family.c_str());
}
return hash ^
std::hash<uint32_t>()(key.fFontStyle.weight()) ^
std::hash<uint32_t>()(key.fFontStyle.slant());
}
FontCollection::FontCollection()
: fEnableFontFallback(true)
, fDefaultFamilyName(DEFAULT_FONT_FAMILY) { }
size_t FontCollection::getFontManagersCount() const { return this->getFontManagerOrder().size(); }
void FontCollection::setAssetFontManager(sk_sp<SkFontMgr> font_manager) {
fAssetFontManager = font_manager;
}
void FontCollection::setDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
fDynamicFontManager = font_manager;
}
void FontCollection::setTestFontManager(sk_sp<SkFontMgr> font_manager) {
fTestFontManager = font_manager;
}
void FontCollection::setDefaultFontManager(sk_sp<SkFontMgr> fontManager,
const char defaultFamilyName[]) {
fDefaultFontManager = std::move(fontManager);
fDefaultFamilyName = defaultFamilyName;
}
void FontCollection::setDefaultFontManager(sk_sp<SkFontMgr> fontManager) {
fDefaultFontManager = fontManager;
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> FontCollection::getFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (fDynamicFontManager) {
order.push_back(fDynamicFontManager);
}
if (fAssetFontManager) {
order.push_back(fAssetFontManager);
}
if (fTestFontManager) {
order.push_back(fTestFontManager);
}
if (fDefaultFontManager && fEnableFontFallback) {
order.push_back(fDefaultFontManager);
}
return order;
}
std::vector<sk_sp<SkTypeface>> FontCollection::findTypefaces(const std::vector<SkString>& familyNames, SkFontStyle fontStyle) {
// Look inside the font collections cache first
FamilyKey familyKey(familyNames, fontStyle);
auto found = fTypefaces.find(familyKey);
if (found) {
return *found;
}
std::vector<sk_sp<SkTypeface>> typefaces;
for (const SkString& familyName : familyNames) {
sk_sp<SkTypeface> match = matchTypeface(familyName, fontStyle);
if (match) {
typefaces.emplace_back(std::move(match));
}
}
if (typefaces.empty()) {
sk_sp<SkTypeface> match = matchTypeface(fDefaultFamilyName, fontStyle);
if (match) {
typefaces.emplace_back(std::move(match));
}
}
fTypefaces.set(familyKey, typefaces);
return typefaces;
}
sk_sp<SkTypeface> FontCollection::matchTypeface(const SkString& familyName, SkFontStyle fontStyle) {
for (const auto& manager : this->getFontManagerOrder()) {
SkFontStyleSet* set = manager->matchFamily(familyName.c_str());
if (nullptr == set || set->count() == 0) {
continue;
}
for (int i = 0; i < set->count(); ++i) {
set->createTypeface(i);
}
sk_sp<SkTypeface> match(set->matchStyle(fontStyle));
if (match) {
return match;
}
}
return nullptr;
}
// Find ANY font in available font managers that resolves the unicode codepoint
sk_sp<SkTypeface> FontCollection::defaultFallback(SkUnichar unicode, SkFontStyle fontStyle, const SkString& locale) {
for (const auto& manager : this->getFontManagerOrder()) {
std::vector<const char*> bcp47;
if (!locale.isEmpty()) {
bcp47.push_back(locale.c_str());
}
sk_sp<SkTypeface> typeface(manager->matchFamilyStyleCharacter(
0, fontStyle, bcp47.data(), bcp47.size(), unicode));
if (typeface != nullptr) {
return typeface;
}
}
return nullptr;
}
sk_sp<SkTypeface> FontCollection::defaultFallback() {
if (fDefaultFontManager == nullptr) {
return nullptr;
}
auto result = fDefaultFontManager->matchFamilyStyle(fDefaultFamilyName.c_str(), SkFontStyle());
return sk_ref_sp<SkTypeface>(result);
}
void FontCollection::disableFontFallback() { fEnableFontFallback = false; }
void FontCollection::enableFontFallback() { fEnableFontFallback = true; }
} // namespace textlayout
} // namespace skia
<commit_msg>Roll external/skia c937bc50250d..189f30216bd7 (1 commits)<commit_after>// Copyright 2019 Google LLC.
#include "include/core/SkTypeface.h"
#include "modules/skparagraph/include/FontCollection.h"
#include "modules/skparagraph/include/Paragraph.h"
#include "modules/skparagraph/src/ParagraphImpl.h"
namespace skia {
namespace textlayout {
bool FontCollection::FamilyKey::operator==(const FontCollection::FamilyKey& other) const {
return fFamilyNames == other.fFamilyNames && fFontStyle == other.fFontStyle;
}
size_t FontCollection::FamilyKey::Hasher::operator()(const FontCollection::FamilyKey& key) const {
size_t hash = 0;
for (const SkString& family : key.fFamilyNames) {
hash ^= std::hash<std::string>()(family.c_str());
}
return hash ^
std::hash<uint32_t>()(key.fFontStyle.weight()) ^
std::hash<uint32_t>()(key.fFontStyle.slant());
}
FontCollection::FontCollection()
: fEnableFontFallback(true)
, fDefaultFamilyName(DEFAULT_FONT_FAMILY) { }
size_t FontCollection::getFontManagersCount() const { return this->getFontManagerOrder().size(); }
void FontCollection::setAssetFontManager(sk_sp<SkFontMgr> font_manager) {
fAssetFontManager = font_manager;
}
void FontCollection::setDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
fDynamicFontManager = font_manager;
}
void FontCollection::setTestFontManager(sk_sp<SkFontMgr> font_manager) {
fTestFontManager = font_manager;
}
void FontCollection::setDefaultFontManager(sk_sp<SkFontMgr> fontManager,
const char defaultFamilyName[]) {
fDefaultFontManager = std::move(fontManager);
fDefaultFamilyName = defaultFamilyName;
}
void FontCollection::setDefaultFontManager(sk_sp<SkFontMgr> fontManager) {
fDefaultFontManager = fontManager;
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> FontCollection::getFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (fDynamicFontManager) {
order.push_back(fDynamicFontManager);
}
if (fAssetFontManager) {
order.push_back(fAssetFontManager);
}
if (fTestFontManager) {
order.push_back(fTestFontManager);
}
if (fDefaultFontManager && fEnableFontFallback) {
order.push_back(fDefaultFontManager);
}
return order;
}
std::vector<sk_sp<SkTypeface>> FontCollection::findTypefaces(const std::vector<SkString>& familyNames, SkFontStyle fontStyle) {
// Look inside the font collections cache first
FamilyKey familyKey(familyNames, fontStyle);
auto found = fTypefaces.find(familyKey);
if (found) {
return *found;
}
std::vector<sk_sp<SkTypeface>> typefaces;
for (const SkString& familyName : familyNames) {
sk_sp<SkTypeface> match = matchTypeface(familyName, fontStyle);
if (match) {
typefaces.emplace_back(std::move(match));
}
}
if (typefaces.empty()) {
sk_sp<SkTypeface> match = matchTypeface(fDefaultFamilyName, fontStyle);
if (match) {
typefaces.emplace_back(std::move(match));
}
}
fTypefaces.set(familyKey, typefaces);
return typefaces;
}
sk_sp<SkTypeface> FontCollection::matchTypeface(const SkString& familyName, SkFontStyle fontStyle) {
for (const auto& manager : this->getFontManagerOrder()) {
sk_sp<SkFontStyleSet> set(manager->matchFamily(familyName.c_str()));
if (!set || set->count() == 0) {
continue;
}
for (int i = 0; i < set->count(); ++i) {
set->createTypeface(i);
}
sk_sp<SkTypeface> match(set->matchStyle(fontStyle));
if (match) {
return match;
}
}
return nullptr;
}
// Find ANY font in available font managers that resolves the unicode codepoint
sk_sp<SkTypeface> FontCollection::defaultFallback(SkUnichar unicode, SkFontStyle fontStyle, const SkString& locale) {
for (const auto& manager : this->getFontManagerOrder()) {
std::vector<const char*> bcp47;
if (!locale.isEmpty()) {
bcp47.push_back(locale.c_str());
}
sk_sp<SkTypeface> typeface(manager->matchFamilyStyleCharacter(
0, fontStyle, bcp47.data(), bcp47.size(), unicode));
if (typeface != nullptr) {
return typeface;
}
}
return nullptr;
}
sk_sp<SkTypeface> FontCollection::defaultFallback() {
if (fDefaultFontManager == nullptr) {
return nullptr;
}
auto result = fDefaultFontManager->matchFamilyStyle(fDefaultFamilyName.c_str(), SkFontStyle());
return sk_ref_sp<SkTypeface>(result);
}
void FontCollection::disableFontFallback() { fEnableFontFallback = false; }
void FontCollection::enableFontFallback() { fEnableFontFallback = true; }
} // namespace textlayout
} // namespace skia
<|endoftext|> |
<commit_before>//CPUĸ
#if !defined (_WIN32) && !defined (_WIN64)
#define LINUX
#include <sysconf.h>
#else
#define WINDOWS
#include <windows.h>
#endif
unsigned core_count()
{
unsigned count = 1; // һ
#if defined (LINUX)
count = sysconf(_SC_NPROCESSORS_CONF);
#elif defined (WINDOWS)
SYSTEM_INFO si;
GetSystemInfo(&si);
count = si.dwNumberOfProcessors;
#endif
return count;
}
<commit_msg>syc's second try<commit_after>//CPUĸ
#if !defined (_WIN32) && !defined (_WIN64)
#define LINUX
#include <sysconf.h>
#else
#define WINDOWS
#include <windows.h>
#endif
unsigned core_count()
{
unsigned count = 1; // һ
#if defined (LINUX)
count = sysconf(_SC_NPROCESSORS_CONF);
#elif defined (WINDOWS)
SYSTEM_INFO si;
GetSystemInfo(&si);
count = si.dwNumberOfProcessors;
#endif
// syc
return count;
}
<|endoftext|> |
<commit_before>#include "File.h"
#include "gtest/gtest.h"
#include <random>
using namespace joedb;
static const uint64_t joedb_magic = 0x0000620165646A6FULL;
class File_Test: public::testing::Test
{
protected:
virtual void SetUp()
{
File file("existing.tmp", Open_Mode::create_new);
file.write<uint64_t>(joedb_magic);
file.write<bool>(false);
file.write<bool>(true);
}
virtual void TearDown()
{
std::remove("locked.tmp");
std::remove("existing.tmp");
std::remove("new.tmp");
}
};
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_failure)
{
EXPECT_ANY_THROW
(
File file("not_existing.tmp", Open_Mode::read_existing)
);
EXPECT_ANY_THROW
(
File file("not_existing.tmp", Open_Mode::write_existing)
);
EXPECT_ANY_THROW
(
File file("existing.tmp", Open_Mode::create_new)
);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_lock)
{
std::remove("locked.tmp");
{
File locked_file_1("locked.tmp", Open_Mode::create_new);
locked_file_1.write<int>(1234);
EXPECT_ANY_THROW
(
File locked_file_2("locked.tmp", Open_Mode::write_existing)
);
}
{
File locked_file_1("locked.tmp", Open_Mode::write_existing);
EXPECT_ANY_THROW
(
File locked_file_2("locked.tmp", Open_Mode::write_existing)
);
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_success)
{
{
File file("existing.tmp", Open_Mode::read_existing);
EXPECT_EQ(file.get_mode(), Open_Mode::read_existing);
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
new_file.flush();
EXPECT_EQ(new_file.get_mode(), Open_Mode::create_new);
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_existing)
{
File existing("existing.tmp", Open_Mode::read_existing);
EXPECT_EQ(existing.read<uint64_t>(), joedb_magic);
EXPECT_EQ(existing.read<bool>(), false);
EXPECT_EQ(existing.read<bool>(), true);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_write_integer)
{
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
new_file.write<uint64_t>(joedb_magic);
new_file.set_position(0);
EXPECT_EQ(joedb_magic, new_file.read<uint64_t>());
}
std::random_device rd;
std::mt19937_64 gen(rd());
const int N = 1000;
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint16_t value = uint16_t(gen());
new_file.set_position(0);
new_file.compact_write<uint16_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint16_t>());
}
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint32_t value = uint32_t(gen());
new_file.set_position(0);
new_file.compact_write<uint32_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint32_t>());
}
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint64_t value = uint64_t(gen()) & 0x1fffffffffffffffULL;
new_file.set_position(0);
new_file.compact_write<uint64_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint64_t>());
}
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_write_string)
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
const std::string s("joedb!!!");
new_file.write_string(s);
new_file.set_position(0);
EXPECT_EQ(new_file.read_string(), s);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, position_test)
{
std::remove("new.tmp");
File file("new.tmp", Open_Mode::create_new);
EXPECT_EQ(0ULL, file.get_position());
file.set_position(size_t(-1));
EXPECT_EQ(0ULL, file.get_position());
const uint64_t N = 100;
for (int i = N; --i >= 0;)
file.write<uint8_t>('x');
EXPECT_EQ(N, file.get_position());
const uint64_t pos = 12;
file.set_position(pos);
EXPECT_EQ(pos, file.get_position());
const uint8_t x = file.read<uint8_t>();
EXPECT_EQ('x', x);
EXPECT_EQ(pos + 1, file.get_position());
file.set_position(N + 2);
EXPECT_EQ(N + 2, file.get_position());
file.write<uint8_t>('x');
file.set_position(N + 1);
const uint8_t c = file.read<uint8_t>();
EXPECT_EQ(0, c);
EXPECT_FALSE(file.is_end_of_file());
EXPECT_EQ(N + 2, file.get_position());
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, eof)
{
std::remove("new.tmp");
File file("new.tmp", Open_Mode::create_new);
EXPECT_FALSE(file.is_end_of_file());
file.read<uint8_t>();
EXPECT_TRUE(file.is_end_of_file());
file.set_position(0);
const int N = 100000;
for (int i = N; --i >= 0;)
file.write<uint8_t>('x');
EXPECT_FALSE(file.is_end_of_file());
file.set_position(N - 1);
EXPECT_FALSE(file.is_end_of_file());
uint8_t c = file.read<uint8_t>();
EXPECT_EQ('x', c);
EXPECT_FALSE(file.is_end_of_file());
file.read<uint8_t>();
EXPECT_TRUE(file.is_end_of_file());
}
<commit_msg>Don't use random_device, so that tests run with valgrind.<commit_after>#include "File.h"
#include "gtest/gtest.h"
#include <random>
using namespace joedb;
static const uint64_t joedb_magic = 0x0000620165646A6FULL;
class File_Test: public::testing::Test
{
protected:
virtual void SetUp()
{
File file("existing.tmp", Open_Mode::create_new);
file.write<uint64_t>(joedb_magic);
file.write<bool>(false);
file.write<bool>(true);
}
virtual void TearDown()
{
std::remove("locked.tmp");
std::remove("existing.tmp");
std::remove("new.tmp");
}
};
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_failure)
{
EXPECT_ANY_THROW
(
File file("not_existing.tmp", Open_Mode::read_existing)
);
EXPECT_ANY_THROW
(
File file("not_existing.tmp", Open_Mode::write_existing)
);
EXPECT_ANY_THROW
(
File file("existing.tmp", Open_Mode::create_new)
);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_lock)
{
std::remove("locked.tmp");
{
File locked_file_1("locked.tmp", Open_Mode::create_new);
locked_file_1.write<int>(1234);
EXPECT_ANY_THROW
(
File locked_file_2("locked.tmp", Open_Mode::write_existing)
);
}
{
File locked_file_1("locked.tmp", Open_Mode::write_existing);
EXPECT_ANY_THROW
(
File locked_file_2("locked.tmp", Open_Mode::write_existing)
);
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, open_success)
{
{
File file("existing.tmp", Open_Mode::read_existing);
EXPECT_EQ(file.get_mode(), Open_Mode::read_existing);
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
new_file.flush();
EXPECT_EQ(new_file.get_mode(), Open_Mode::create_new);
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_existing)
{
File existing("existing.tmp", Open_Mode::read_existing);
EXPECT_EQ(existing.read<uint64_t>(), joedb_magic);
EXPECT_EQ(existing.read<bool>(), false);
EXPECT_EQ(existing.read<bool>(), true);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_write_integer)
{
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
new_file.write<uint64_t>(joedb_magic);
new_file.set_position(0);
EXPECT_EQ(joedb_magic, new_file.read<uint64_t>());
}
#if 0
std::random_device rd; // not supported by valgrind
std::mt19937_64 gen(rd());
#else
std::mt19937_64 gen(0);
#endif
const int N = 1000;
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint16_t value = uint16_t(gen());
new_file.set_position(0);
new_file.compact_write<uint16_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint16_t>());
}
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint32_t value = uint32_t(gen());
new_file.set_position(0);
new_file.compact_write<uint32_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint32_t>());
}
}
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
for (int i = N; --i >= 0;)
{
uint64_t value = uint64_t(gen()) & 0x1fffffffffffffffULL;
new_file.set_position(0);
new_file.compact_write<uint64_t>(value);
new_file.set_position(0);
EXPECT_EQ(value, new_file.compact_read<uint64_t>());
}
}
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, read_write_string)
{
std::remove("new.tmp");
File new_file("new.tmp", Open_Mode::create_new);
const std::string s("joedb!!!");
new_file.write_string(s);
new_file.set_position(0);
EXPECT_EQ(new_file.read_string(), s);
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, position_test)
{
std::remove("new.tmp");
File file("new.tmp", Open_Mode::create_new);
EXPECT_EQ(0ULL, file.get_position());
file.set_position(size_t(-1));
EXPECT_EQ(0ULL, file.get_position());
const uint64_t N = 100;
for (int i = N; --i >= 0;)
file.write<uint8_t>('x');
EXPECT_EQ(N, file.get_position());
const uint64_t pos = 12;
file.set_position(pos);
EXPECT_EQ(pos, file.get_position());
const uint8_t x = file.read<uint8_t>();
EXPECT_EQ('x', x);
EXPECT_EQ(pos + 1, file.get_position());
file.set_position(N + 2);
EXPECT_EQ(N + 2, file.get_position());
file.write<uint8_t>('x');
file.set_position(N + 1);
const uint8_t c = file.read<uint8_t>();
EXPECT_EQ(0, c);
EXPECT_FALSE(file.is_end_of_file());
EXPECT_EQ(N + 2, file.get_position());
}
/////////////////////////////////////////////////////////////////////////////
TEST_F(File_Test, eof)
{
std::remove("new.tmp");
File file("new.tmp", Open_Mode::create_new);
EXPECT_FALSE(file.is_end_of_file());
file.read<uint8_t>();
EXPECT_TRUE(file.is_end_of_file());
file.set_position(0);
const int N = 100000;
for (int i = N; --i >= 0;)
file.write<uint8_t>('x');
EXPECT_FALSE(file.is_end_of_file());
file.set_position(N - 1);
EXPECT_FALSE(file.is_end_of_file());
uint8_t c = file.read<uint8_t>();
EXPECT_EQ('x', c);
EXPECT_FALSE(file.is_end_of_file());
file.read<uint8_t>();
EXPECT_TRUE(file.is_end_of_file());
}
<|endoftext|> |
<commit_before>/*=============================================================================
Copyright (c) 2012-2014 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Calculate convex hull using Qhull / libqhullcpp
// All interfacing with the library will be done in this module
#include "libgibbs/include/libgibbs_pch.hpp"
#include "libgibbs/include/optimizer/utils/convex_hull.hpp"
#include "external/libqhullcpp/QhullError.h"
#include "external/libqhullcpp/QhullQh.h"
#include "external/libqhullcpp/QhullFacet.h"
#include "external/libqhullcpp/QhullFacetList.h"
#include "external/libqhullcpp/QhullHyperplane.h"
#include "external/libqhullcpp/QhullLinkedList.h"
#include "external/libqhullcpp/QhullVertex.h"
#include "external/libqhullcpp/QhullVertexSet.h"
#include "external/libqhullcpp/Qhull.h"
#include <boost/assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <string>
#include <sstream>
#include <algorithm>
#include <functional>
#include <cmath>
using orgQhull::Qhull;
using orgQhull::QhullError;
using orgQhull::QhullFacet;
using orgQhull::QhullFacetList;
using orgQhull::QhullQh;
using orgQhull::RboxPoints;
using orgQhull::QhullVertex;
using orgQhull::QhullVertexSet;
namespace Optimizer { namespace details {
std::vector<double> restore_dependent_dimensions (
const std::vector<double> &point,
const std::set<std::size_t> &dependent_dimensions);
// Modified QuickHull algorithm using d-dimensional Beneath-Beyond
// Reference: N. Perevoshchikova, et al., 2012, Computational Materials Science.
// "A convex hull algorithm for a grid minimization of Gibbs energy as initial step
// in equilibrium calculations in two-phase multicomponent alloys"
std::vector<std::vector<double>> lower_convex_hull (
const std::vector<std::vector<double>> &points,
const std::set<std::size_t> &dependent_dimensions,
const double critical_edge_length,
std::function<double(const std::vector<double>&)> calculate_objective
) {
BOOST_ASSERT(points.size() > 0);
BOOST_ASSERT(critical_edge_length > 0);
const double coplanarity_allowance = 0.001; // max energy difference (%/100) to still be on tie plane
const std::size_t point_dimension = points.begin()->size();
const std::size_t point_count = points.size();
const std::size_t point_buffer_size = point_dimension * point_count;
std::vector<std::vector<double>> candidate_points, final_points; // vertices of tie hyperplanes
double point_buffer[point_buffer_size-1];
std::size_t buffer_offset = 0;
std::string Qhullcommand = "";
if (points.size() == 1) { // Special case: No composition dependence
auto return_point = restore_dependent_dimensions ( points.front(), dependent_dimensions );
final_points.emplace_back ( std::move ( return_point ) );
return final_points;
}
// Copy all of the points into a buffer compatible with Qhull
for (auto pt : points) {
for (auto coord : pt) {
if (buffer_offset >= point_buffer_size) break;
point_buffer[buffer_offset++] = coord;
}
}
BOOST_ASSERT(buffer_offset == point_buffer_size);
// Mark dependent dimensions for Qhull so they can be discarded
for (auto dim : dependent_dimensions) {
std::stringstream stream;
// Qhull command "Qbk:0Bk:0" drops dimension k from consideration
stream << " " << "Qb" << dim << ":0B" << dim << ":0";
Qhullcommand += stream.str();
}
std::cout << "DEBUG: Qhullcommand: " << Qhullcommand.c_str() << std::endl;
// Make the call to Qhull
Qhull qhull("", point_dimension, point_count, point_buffer, Qhullcommand.c_str());
// Get all of the facets
QhullFacetList facets = qhull.facetList();
for (auto facet : facets) {
if (facet.isDefined() && facet.isGood() && facet.isSimplicial()) {
double orientation = *(facet.hyperplane().constEnd()-1); // last coordinate (energy)
if (orientation > 0) continue; // consider only the facets of the lower convex hull
QhullVertexSet vertices = facet.vertices();
const std::size_t vertex_count = vertices.size();
// Only facets with edges beyond the critical length are candidate tie hyperplanes
// Check the length of all edges (dimension 1) in the facet
for (auto vertex1 = 0; vertex1 < vertex_count; ++vertex1) {
std::vector<double> pt_vert1 = vertices[vertex1].point().toStdVector();
//pt_vert1.pop_back(); // Remove the last coordinate (energy) for this check
for (auto vertex2 = 0; vertex2 < vertex1; ++vertex2) {
std::vector<double> pt_vert2 = vertices[vertex2].point().toStdVector();
//pt_vert2.pop_back(); // Remove the last coordinate (energy) for this check
std::vector<double> difference ( pt_vert2.size() );
std::vector<double> midpoint ( pt_vert2.size() ); // midpoint of the edge
std::transform (pt_vert2.begin(), pt_vert2.end(),
pt_vert1.begin(), midpoint.begin(), std::plus<double>() );
for (auto &coord : midpoint) coord /= 2;
const double lever_rule_energy = midpoint.back();
midpoint.pop_back(); // remove energy coordinate
midpoint = restore_dependent_dimensions ( midpoint, dependent_dimensions );
const double true_energy = calculate_objective ( midpoint );
// If the true energy is "much" greater, it's a true tie line
std::cout << "pt_vert1: ";
for (auto &coord : pt_vert1) std::cout << coord << ",";
std::cout << ":: ";
std::cout << "pt_vert2: ";
for (auto &coord : pt_vert2) std::cout << coord << ",";
std::cout << ":: ";
std::cout << "midpoint: ";
for (auto &coord : midpoint) std::cout << coord << ",";
std::cout << std::endl;
std::cout << "true_energy: " << true_energy << " lever_rule_energy: " << lever_rule_energy << std::endl;
// We use fabs() here so we don't accidentally flip the sign of the comparison
if ( (true_energy-lever_rule_energy)/fabs(lever_rule_energy) < coplanarity_allowance ) {
continue; // not a true tie line, skip it
}
double distance = 0;
// Subtract vertex1 from vertex2 to get the distance
std::transform (pt_vert2.begin(), pt_vert2.end()-1,
pt_vert1.begin(), difference.begin(), std::minus<double>() );
// Sum the square of all elements of vertex2-vertex1
for (auto coord : difference) distance += std::pow(coord,2);
// Square root the result
distance = sqrt(distance);
// if the edge length is large enough, this is a candidate tie hyperplane
if (distance > critical_edge_length) {
std::cout << "Edge length: " << distance << std::endl;
std::cout << "Vertex1: ";
for (auto coord : pt_vert1) std::cout << coord << ",";
std::cout << std::endl;
std::cout << "Vertex2: ";
for (auto coord : pt_vert2) std::cout << coord << ",";
std::cout << std::endl;
candidate_points.push_back(pt_vert1);
candidate_points.push_back(pt_vert2);
std::cout << facet;
}
}
}
}
}
if (candidate_points.size() > 0) {
// There is at least one tie hyperplane
// First, remove duplicate points
// too_similar is a binary predicate for determining if the minima are too close in state space
auto too_similar = [] ( const std::vector<double> &a, const std::vector<double> &b ) {
if ( a.size() != b.size() ) {
return false;
}
for ( auto i = 0; i < a.size(); ++i ) {
if ( fabs ( a[i]-b[i] ) > 0.01 ) {
return false; // at least one element is different enough
}
}
return true; // all elements compared closely
};
std::sort ( candidate_points.begin(), candidate_points.end() );
auto new_end = std::unique ( candidate_points.begin(), candidate_points.end(), too_similar );
// Fix the deduplicated point list to have no empty elements
candidate_points.resize( std::distance( candidate_points.begin(), new_end ) );
std::cout << "CANDIDATE POINTS AFTER DEDUPLICATION" << std::endl;
for (auto pt : candidate_points) {
for (auto coord : pt) {
std::cout << coord << ",";
}
std::cout << std::endl;
}
std::cout << "candidate_points.size() = " << candidate_points.size() << std::endl;
// Second, restore the dependent variables to the correct coordinate placement
for (const auto pt : candidate_points) {
final_points.emplace_back ( restore_dependent_dimensions ( pt, dependent_dimensions ) );
}
}
else {
// No tie hyperplanes have been found
// Return the point with the lowest energy (last coordinate)
auto minimum_point_iterator = points.cbegin();
for (auto pt = points.cbegin(); pt != points.cend(); ++pt) {
// Check the energy values
if (*(minimum_point_iterator->cend()-1) > *(pt->cend()-1)) {
// This point is lower in energy
minimum_point_iterator = pt;
}
}
std::vector<double> return_point ( *minimum_point_iterator );
return_point.pop_back(); // Remove energy coordinate
final_points.emplace_back ( std::move ( return_point ) );
}
std::cout << "FINAL TIE POINTS" << std::endl;
for (auto pt : final_points) {
for (auto coord : pt) {
std::cout << coord << ",";
}
std::cout << std::endl;
}
return final_points;
}
// Add the dependent site fraction coordinates back to the point
std::vector<double> restore_dependent_dimensions (
const std::vector<double> &point,
const std::set<std::size_t> &dependent_dimensions) {
std::vector<double> final_point;
final_point.reserve ( point.size() + dependent_dimensions.size() );
std::size_t sublattice_offset = 0;
auto iter = point.cbegin();
for (auto dim : dependent_dimensions) {
double point_sum = 0;
for (auto coord = sublattice_offset; coord < dim; ++coord) {
std::cout << "sublattice_offset: " << sublattice_offset << " coord: " << coord << " dim: " << dim << std::endl;
point_sum += *iter;
final_point.push_back ( *iter );
if (iter != point.cend()) ++iter;
}
// add back the dependent component
final_point.emplace_back ( 1 - point_sum ); // dependent coordinate is 1 - independents
sublattice_offset = dim+1; // move to next sublattice
}
return final_point;
}
} // namespace details
} // namespace Optimizer<commit_msg>Clean up point buffer construction with more C++-like approach.<commit_after>/*=============================================================================
Copyright (c) 2012-2014 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Calculate convex hull using Qhull / libqhullcpp
#include "libgibbs/include/libgibbs_pch.hpp"
#include "libgibbs/include/optimizer/utils/convex_hull.hpp"
#include "external/libqhullcpp/RboxPoints.h"
#include "external/libqhullcpp/QhullError.h"
#include "external/libqhullcpp/QhullQh.h"
#include "external/libqhullcpp/QhullFacet.h"
#include "external/libqhullcpp/QhullFacetList.h"
#include "external/libqhullcpp/QhullHyperplane.h"
#include "external/libqhullcpp/QhullLinkedList.h"
#include "external/libqhullcpp/QhullPoint.h"
#include "external/libqhullcpp/QhullVertex.h"
#include "external/libqhullcpp/QhullVertexSet.h"
#include "external/libqhullcpp/Qhull.h"
#include <boost/assert.hpp>
#include <string>
#include <sstream>
#include <algorithm>
#include <functional>
#include <cmath>
using orgQhull::RboxPoints;
using orgQhull::Qhull;
using orgQhull::QhullError;
using orgQhull::QhullFacet;
using orgQhull::QhullFacetList;
using orgQhull::QhullPoint;
using orgQhull::QhullQh;
using orgQhull::RboxPoints;
using orgQhull::QhullVertex;
using orgQhull::QhullVertexSet;
namespace Optimizer { namespace details {
std::vector<double> restore_dependent_dimensions (
const std::vector<double> &point,
const std::set<std::size_t> &dependent_dimensions);
// Modified QuickHull algorithm using d-dimensional Beneath-Beyond
// Reference: N. Perevoshchikova, et al., 2012, Computational Materials Science.
// "A convex hull algorithm for a grid minimization of Gibbs energy as initial step
// in equilibrium calculations in two-phase multicomponent alloys"
std::vector<std::vector<double>> lower_convex_hull (
const std::vector<std::vector<double>> &points,
const std::set<std::size_t> &dependent_dimensions,
const double critical_edge_length,
std::function<double(const std::vector<double>&)> calculate_objective
) {
BOOST_ASSERT(points.size() > 0);
BOOST_ASSERT(critical_edge_length > 0);
const double coplanarity_allowance = 0.001; // max energy difference (%/100) to still be on tie plane
const std::size_t point_dimension = points.begin()->size();
const std::size_t point_count = points.size();
std::vector<std::vector<double>> candidate_points, final_points; // vertices of tie hyperplanes
RboxPoints point_buffer;
point_buffer.setDimension ( point_dimension );
point_buffer.reserveCoordinates ( point_count );
std::string Qhullcommand = "";
if (points.size() == 1) { // Special case: No composition dependence
auto return_point = restore_dependent_dimensions ( points.front(), dependent_dimensions );
final_points.emplace_back ( std::move ( return_point ) );
return final_points;
}
// Copy all of the points into a buffer compatible with Qhull
for (auto pt : points) {
point_buffer.append ( QhullPoint ( point_dimension, &pt[0] ) );
}
// Mark dependent dimensions for Qhull so they can be discarded
for (auto dim : dependent_dimensions) {
std::stringstream stream;
// Qhull command "Qbk:0Bk:0" drops dimension k from consideration
stream << " " << "Qb" << dim << ":0B" << dim << ":0";
Qhullcommand += stream.str();
}
std::cout << "DEBUG: Qhullcommand: " << Qhullcommand.c_str() << std::endl;
// Make the call to Qhull
Qhull qhull ( point_buffer, Qhullcommand.c_str() );
// Get all of the facets
QhullFacetList facets = qhull.facetList();
for (auto facet : facets) {
if (facet.isDefined() && facet.isGood() /*&& facet.isSimplicial()*/) {
double orientation = *(facet.hyperplane().constEnd()-1); // last coordinate (energy)
if (orientation > 0) continue; // consider only the facets of the lower convex hull
QhullVertexSet vertices = facet.vertices();
const std::size_t vertex_count = vertices.size();
// Only facets with edges beyond the critical length are candidate tie hyperplanes
// Check the length of all edges (dimension 1) in the facet
for (auto vertex1 = 0; vertex1 < vertex_count; ++vertex1) {
std::vector<double> pt_vert1 = vertices[vertex1].point().toStdVector();
//pt_vert1.pop_back(); // Remove the last coordinate (energy) for this check
for (auto vertex2 = 0; vertex2 < vertex1; ++vertex2) {
std::vector<double> pt_vert2 = vertices[vertex2].point().toStdVector();
//pt_vert2.pop_back(); // Remove the last coordinate (energy) for this check
std::vector<double> difference ( pt_vert2.size() );
std::vector<double> midpoint ( pt_vert2.size() ); // midpoint of the edge
std::transform (pt_vert2.begin(), pt_vert2.end(),
pt_vert1.begin(), midpoint.begin(), std::plus<double>() );
for (auto &coord : midpoint) coord /= 2;
const double lever_rule_energy = midpoint.back();
midpoint.pop_back(); // remove energy coordinate
midpoint = restore_dependent_dimensions ( midpoint, dependent_dimensions );
const double true_energy = calculate_objective ( midpoint );
// If the true energy is "much" greater, it's a true tie line
std::cout << "pt_vert1(" << vertices[vertex1].point().id() << "): ";
for (auto &coord : pt_vert1) std::cout << coord << ",";
std::cout << ":: ";
std::cout << "pt_vert2(" << vertices[vertex2].point().id() << "): ";
for (auto &coord : pt_vert2) std::cout << coord << ",";
std::cout << ":: ";
std::cout << "midpoint: ";
for (auto &coord : midpoint) std::cout << coord << ",";
std::cout << std::endl;
std::cout << "true_energy: " << true_energy << " lever_rule_energy: " << lever_rule_energy << std::endl;
// We use fabs() here so we don't accidentally flip the sign of the comparison
if ( (true_energy-lever_rule_energy)/fabs(lever_rule_energy) < coplanarity_allowance ) {
continue; // not a true tie line, skip it
}
double distance = 0;
// Subtract vertex1 from vertex2 to get the distance
std::transform (pt_vert2.begin(), pt_vert2.end()-1,
pt_vert1.begin(), difference.begin(), std::minus<double>() );
// Sum the square of all elements of vertex2-vertex1
for (auto coord : difference) distance += std::pow(coord,2);
// Square root the result
distance = sqrt(distance);
// if the edge length is large enough, this is a candidate tie hyperplane
if (distance > critical_edge_length) {
std::cout << "Edge length: " << distance << std::endl;
std::cout << "Vertex1: ";
for (auto coord : pt_vert1) std::cout << coord << ",";
std::cout << std::endl;
std::cout << "Vertex2: ";
for (auto coord : pt_vert2) std::cout << coord << ",";
std::cout << std::endl;
candidate_points.push_back(pt_vert1);
candidate_points.push_back(pt_vert2);
std::cout << facet;
}
}
}
}
}
if (candidate_points.size() > 0) {
// There is at least one tie hyperplane
// First, remove duplicate points
// too_similar is a binary predicate for determining if the minima are too close in state space
auto too_similar = [] ( const std::vector<double> &a, const std::vector<double> &b ) {
if ( a.size() != b.size() ) {
return false;
}
for ( auto i = 0; i < a.size(); ++i ) {
if ( fabs ( a[i]-b[i] ) > 0.01 ) {
return false; // at least one element is different enough
}
}
return true; // all elements compared closely
};
std::sort ( candidate_points.begin(), candidate_points.end() );
auto new_end = std::unique ( candidate_points.begin(), candidate_points.end(), too_similar );
// Fix the deduplicated point list to have no empty elements
candidate_points.resize( std::distance( candidate_points.begin(), new_end ) );
std::cout << "CANDIDATE POINTS AFTER DEDUPLICATION" << std::endl;
for (auto pt : candidate_points) {
for (auto coord : pt) {
std::cout << coord << ",";
}
std::cout << std::endl;
}
std::cout << "candidate_points.size() = " << candidate_points.size() << std::endl;
// Second, restore the dependent variables to the correct coordinate placement
for (const auto pt : candidate_points) {
final_points.emplace_back ( restore_dependent_dimensions ( pt, dependent_dimensions ) );
}
}
else {
// No tie hyperplanes have been found
// Return the point with the lowest energy (last coordinate)
auto minimum_point_iterator = points.cbegin();
for (auto pt = points.cbegin(); pt != points.cend(); ++pt) {
// Check the energy values
if (*(minimum_point_iterator->cend()-1) > *(pt->cend()-1)) {
// This point is lower in energy
minimum_point_iterator = pt;
}
}
std::vector<double> return_point ( *minimum_point_iterator );
return_point.pop_back(); // Remove energy coordinate
final_points.emplace_back ( std::move ( return_point ) );
}
std::cout << "FINAL TIE POINTS" << std::endl;
for (auto pt : final_points) {
for (auto coord : pt) {
std::cout << coord << ",";
}
std::cout << std::endl;
}
return final_points;
}
// Add the dependent site fraction coordinates back to the point
std::vector<double> restore_dependent_dimensions (
const std::vector<double> &point,
const std::set<std::size_t> &dependent_dimensions) {
std::vector<double> final_point;
final_point.reserve ( point.size() + dependent_dimensions.size() );
std::size_t sublattice_offset = 0;
auto iter = point.cbegin();
for (auto dim : dependent_dimensions) {
double point_sum = 0;
for (auto coord = sublattice_offset; coord < dim; ++coord) {
std::cout << "sublattice_offset: " << sublattice_offset << " coord: " << coord << " dim: " << dim << std::endl;
point_sum += *iter;
final_point.push_back ( *iter );
if (iter != point.cend()) ++iter;
}
// add back the dependent component
final_point.emplace_back ( 1 - point_sum ); // dependent coordinate is 1 - independents
sublattice_offset = dim+1; // move to next sublattice
}
return final_point;
}
} // namespace details
} // namespace Optimizer<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright 2013 Evan Drumwright
* This library is distributed under the terms of the Apache V2.0
* License (obtainable from http://www.apache.org/licenses/LICENSE-2.0).
****************************************************************************/
/// Computes the dot product between a velocity and a momentum
REAL SVELOCITY::dot(const SMOMENTUM& v2) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v2.pose)
throw FrameException();
#endif
const REAL* d1 = data();
const REAL* d2 = v2.data();
return d1[3]*d2[0] + d1[4]*d2[1] + d1[5]*d2[2]+
d1[0]*d2[3] + d1[1]*d2[4] + d1[2]*d2[5];
}
/// Computes the dot product between a velocity and a force
REAL SVELOCITY::dot(const SFORCE& v2) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v2.pose)
throw FrameException();
#endif
const REAL* d1 = data();
const REAL* d2 = v2.data();
return d1[3]*d2[0] + d1[4]*d2[1] + d1[5]*d2[2]+
d1[0]*d2[3] + d1[1]*d2[4] + d1[2]*d2[5];
}
/// Returns the spatial cross product between two velocity vectors
SVELOCITY SVELOCITY::cross(const SVELOCITY& v) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v.pose)
throw FrameException();
#endif
VECTOR3 ax = get_angular();
VECTOR3 bx = get_linear();
// multiply
VECTOR3 vtop = v.get_angular();
VECTOR3 vbot = v.get_linear();
VECTOR3 top = VECTOR3::cross(ax, vtop);
VECTOR3 bot = VECTOR3::cross(bx, vtop) + VECTOR3::cross(ax, vbot);
return SVELOCITY(top, bot, pose);
}
/// Returns the spatial cross product between a velocity and an acceleration
SFORCE SVELOCITY::cross(const SMOMENTUM& m) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != m.pose)
throw FrameException();
#endif
VECTOR3 ax = get_angular();
VECTOR3 bx = get_linear();
// multiply
VECTOR3 vtop = m.get_angular();
VECTOR3 vbot = m.get_linear();
VECTOR3 bot = VECTOR3::cross(ax, vtop);
VECTOR3 top = VECTOR3::cross(bx, vtop) + VECTOR3::cross(ax, vbot);
return SFORCE(top, bot, pose);
}
<commit_msg>Fixed momentum cross operation<commit_after>/****************************************************************************
* Copyright 2013 Evan Drumwright
* This library is distributed under the terms of the Apache V2.0
* License (obtainable from http://www.apache.org/licenses/LICENSE-2.0).
****************************************************************************/
/// Computes the dot product between a velocity and a momentum
REAL SVELOCITY::dot(const SMOMENTUM& v2) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v2.pose)
throw FrameException();
#endif
const REAL* d1 = data();
const REAL* d2 = v2.data();
return d1[3]*d2[0] + d1[4]*d2[1] + d1[5]*d2[2]+
d1[0]*d2[3] + d1[1]*d2[4] + d1[2]*d2[5];
}
/// Computes the dot product between a velocity and a force
REAL SVELOCITY::dot(const SFORCE& v2) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v2.pose)
throw FrameException();
#endif
const REAL* d1 = data();
const REAL* d2 = v2.data();
return d1[3]*d2[0] + d1[4]*d2[1] + d1[5]*d2[2]+
d1[0]*d2[3] + d1[1]*d2[4] + d1[2]*d2[5];
}
/// Returns the spatial cross product between two velocity vectors
SVELOCITY SVELOCITY::cross(const SVELOCITY& v) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != v.pose)
throw FrameException();
#endif
VECTOR3 ax = get_angular();
VECTOR3 bx = get_linear();
// multiply
VECTOR3 vtop = v.get_angular();
VECTOR3 vbot = v.get_linear();
VECTOR3 top = VECTOR3::cross(ax, vtop);
VECTOR3 bot = VECTOR3::cross(bx, vtop) + VECTOR3::cross(ax, vbot);
return SVELOCITY(top, bot, pose);
}
/// Returns the spatial cross product between a velocity and a momentum (force)
/**
* | -ax -bx |
* | 0 -ax |
*/
SFORCE SVELOCITY::cross(const SMOMENTUM& m) const
{
// verify that both vectors are defined in the same frame
#ifndef NEXCEPT
if (pose != m.pose)
throw FrameException();
#endif
VECTOR3 ax = get_angular();
VECTOR3 bx = get_linear();
// multiply
VECTOR3 vtop = m.get_angular();
VECTOR3 vbot = m.get_linear();
VECTOR3 top = VECTOR3::cross(ax, vtop) + VECTOR3::cross(bx, vbot);
VECTOR3 bot = VECTOR3::cross(ax, vbot);
return SFORCE(bot, top, pose);
}
<|endoftext|> |
<commit_before>//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LowerSwitch transformation rewrites switch instructions with a sequence
// of branches, which allows targets to get away with not implementing the
// switch instruction until it is convenient.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
namespace {
/// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
/// instructions. Note that this cannot be a BasicBlock pass because it
/// modifies the CFG!
class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
public:
static char ID; // Pass identification, replacement for typeid
LowerSwitch() : FunctionPass(&ID) {}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
// This is a cluster of orthogonal Transforms
AU.addPreserved<UnifyFunctionExitNodes>();
AU.addPreservedID(PromoteMemoryToRegisterID);
AU.addPreservedID(LowerInvokePassID);
AU.addPreservedID(LowerAllocationsID);
}
struct CaseRange {
Constant* Low;
Constant* High;
BasicBlock* BB;
CaseRange() : Low(0), High(0), BB(0) { }
CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
Low(low), High(high), BB(bb) { }
};
typedef std::vector<CaseRange> CaseVector;
typedef std::vector<CaseRange>::iterator CaseItr;
private:
void processSwitchInst(SwitchInst *SI);
BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
BasicBlock* OrigBlock, BasicBlock* Default);
BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
BasicBlock* OrigBlock, BasicBlock* Default);
unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
};
/// The comparison function for sorting the switch case values in the vector.
/// WARNING: Case ranges should be disjoint!
struct CaseCmp {
bool operator () (const LowerSwitch::CaseRange& C1,
const LowerSwitch::CaseRange& C2) {
const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
return CI1->getValue().slt(CI2->getValue());
}
};
}
char LowerSwitch::ID = 0;
static RegisterPass<LowerSwitch>
X("lowerswitch", "Lower SwitchInst's to branches");
// Publically exposed interface to pass...
const PassInfo *const llvm::LowerSwitchID = &X;
// createLowerSwitchPass - Interface to this file...
FunctionPass *llvm::createLowerSwitchPass() {
return new LowerSwitch();
}
bool LowerSwitch::runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
Changed = true;
processSwitchInst(SI);
}
}
return Changed;
}
// operator<< - Used for debugging purposes.
//
static raw_ostream& operator<<(raw_ostream &O,
const LowerSwitch::CaseVector &C) {
O << "[";
for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
E = C.end(); B != E; ) {
O << *B->Low << " -" << *B->High;
if (++B != E) O << ", ";
}
return O << "]";
}
// switchConvert - Convert the switch statement into a binary lookup of
// the case values. The function recursively builds this tree.
//
BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
Value* Val, BasicBlock* OrigBlock,
BasicBlock* Default)
{
unsigned Size = End - Begin;
if (Size == 1)
return newLeafBlock(*Begin, Val, OrigBlock, Default);
unsigned Mid = Size / 2;
std::vector<CaseRange> LHS(Begin, Begin + Mid);
DEBUG(errs() << "LHS: " << LHS << "\n");
std::vector<CaseRange> RHS(Begin + Mid, End);
DEBUG(errs() << "RHS: " << RHS << "\n");
CaseRange& Pivot = *(Begin + Mid);
DEBUG(errs() << "Pivot ==> "
<< cast<ConstantInt>(Pivot.Low)->getValue() << " -"
<< cast<ConstantInt>(Pivot.High)->getValue() << "\n");
BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
OrigBlock, Default);
BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
OrigBlock, Default);
// Create a new node that checks if the value is < pivot. Go to the
// left branch if it is and right branch if not.
Function* F = OrigBlock->getParent();
BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
Function::iterator FI = OrigBlock;
F->getBasicBlockList().insert(++FI, NewNode);
ICmpInst* Comp = new ICmpInst(Default->getContext(), ICmpInst::ICMP_SLT,
Val, Pivot.Low, "Pivot");
NewNode->getInstList().push_back(Comp);
BranchInst::Create(LBranch, RBranch, Comp, NewNode);
return NewNode;
}
// newLeafBlock - Create a new leaf block for the binary lookup tree. It
// checks if the switch's value == the case's value. If not, then it
// jumps to the default branch. At this point in the tree, the value
// can't be another valid case value, so the jump to the "default" branch
// is warranted.
//
BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
BasicBlock* OrigBlock,
BasicBlock* Default)
{
Function* F = OrigBlock->getParent();
LLVMContext &Context = F->getContext();
BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
Function::iterator FI = OrigBlock;
F->getBasicBlockList().insert(++FI, NewLeaf);
// Emit comparison
ICmpInst* Comp = NULL;
if (Leaf.Low == Leaf.High) {
// Make the seteq instruction...
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
Leaf.Low, "SwitchLeaf");
} else {
// Make range comparison
if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
// Val >= Min && Val <= Hi --> Val <= Hi
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
"SwitchLeaf");
} else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
// Val >= 0 && Val <= Hi --> Val <=u Hi
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
"SwitchLeaf");
} else {
// Emit V-Lo <=u Hi-Lo
Constant* NegLo = Context.getConstantExprNeg(Leaf.Low);
Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Val->getName()+".off",
NewLeaf);
Constant *UpperBound = Context.getConstantExprAdd(NegLo, Leaf.High);
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
"SwitchLeaf");
}
}
// Make the conditional branch...
BasicBlock* Succ = Leaf.BB;
BranchInst::Create(Succ, Default, Comp, NewLeaf);
// If there were any PHI nodes in this successor, rewrite one entry
// from OrigBlock to come from NewLeaf.
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode* PN = cast<PHINode>(I);
// Remove all but one incoming entries from the cluster
uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
cast<ConstantInt>(Leaf.Low)->getSExtValue();
for (uint64_t j = 0; j < Range; ++j) {
PN->removeIncomingValue(OrigBlock);
}
int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
assert(BlockIdx != -1 && "Switch didn't go to this successor??");
PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
}
return NewLeaf;
}
// Clusterify - Transform simple list of Cases into list of CaseRange's
unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
unsigned numCmps = 0;
// Start with "simple" cases
for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
Cases.push_back(CaseRange(SI->getSuccessorValue(i),
SI->getSuccessorValue(i),
SI->getSuccessor(i)));
std::sort(Cases.begin(), Cases.end(), CaseCmp());
// Merge case into clusters
if (Cases.size()>=2)
for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
BasicBlock* nextBB = J->BB;
BasicBlock* currentBB = I->BB;
// If the two neighboring cases go to the same destination, merge them
// into a single case.
if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
I->High = J->High;
J = Cases.erase(J);
} else {
I = J++;
}
}
for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
if (I->Low != I->High)
// A range counts double, since it requires two compares.
++numCmps;
}
return numCmps;
}
// processSwitchInst - Replace the specified switch instruction with a sequence
// of chained if-then insts in a balanced binary search.
//
void LowerSwitch::processSwitchInst(SwitchInst *SI) {
BasicBlock *CurBlock = SI->getParent();
BasicBlock *OrigBlock = CurBlock;
Function *F = CurBlock->getParent();
Value *Val = SI->getOperand(0); // The value we are switching on...
BasicBlock* Default = SI->getDefaultDest();
// If there is only the default destination, don't bother with the code below.
if (SI->getNumOperands() == 2) {
BranchInst::Create(SI->getDefaultDest(), CurBlock);
CurBlock->getInstList().erase(SI);
return;
}
// Create a new, empty default block so that the new hierarchy of
// if-then statements go to this and the PHI nodes are happy.
BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
F->getBasicBlockList().insert(Default, NewDefault);
BranchInst::Create(Default, NewDefault);
// If there is an entry in any PHI nodes for the default edge, make sure
// to update them as well.
for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
assert(BlockIdx != -1 && "Switch didn't go to this successor??");
PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
}
// Prepare cases vector.
CaseVector Cases;
unsigned numCmps = Clusterify(Cases, SI);
DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
<< ". Total compares: " << numCmps << "\n");
DEBUG(errs() << "Cases: " << Cases << "\n");
(void)numCmps;
BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
OrigBlock, NewDefault);
// Branch to our shiny new if-then stuff...
BranchInst::Create(SwitchBlock, OrigBlock);
// We are now done with the switch instruction, delete it.
CurBlock->getInstList().erase(SI);
}
<commit_msg>Fix a release-asserts warning. Debug functions should be marked used, if there are no other uses. If people don't need this routine anymore, if should be deleted.<commit_after>//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LowerSwitch transformation rewrites switch instructions with a sequence
// of branches, which allows targets to get away with not implementing the
// switch instruction until it is convenient.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
namespace {
/// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
/// instructions. Note that this cannot be a BasicBlock pass because it
/// modifies the CFG!
class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
public:
static char ID; // Pass identification, replacement for typeid
LowerSwitch() : FunctionPass(&ID) {}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
// This is a cluster of orthogonal Transforms
AU.addPreserved<UnifyFunctionExitNodes>();
AU.addPreservedID(PromoteMemoryToRegisterID);
AU.addPreservedID(LowerInvokePassID);
AU.addPreservedID(LowerAllocationsID);
}
struct CaseRange {
Constant* Low;
Constant* High;
BasicBlock* BB;
CaseRange() : Low(0), High(0), BB(0) { }
CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
Low(low), High(high), BB(bb) { }
};
typedef std::vector<CaseRange> CaseVector;
typedef std::vector<CaseRange>::iterator CaseItr;
private:
void processSwitchInst(SwitchInst *SI);
BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
BasicBlock* OrigBlock, BasicBlock* Default);
BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
BasicBlock* OrigBlock, BasicBlock* Default);
unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
};
/// The comparison function for sorting the switch case values in the vector.
/// WARNING: Case ranges should be disjoint!
struct CaseCmp {
bool operator () (const LowerSwitch::CaseRange& C1,
const LowerSwitch::CaseRange& C2) {
const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
return CI1->getValue().slt(CI2->getValue());
}
};
}
char LowerSwitch::ID = 0;
static RegisterPass<LowerSwitch>
X("lowerswitch", "Lower SwitchInst's to branches");
// Publically exposed interface to pass...
const PassInfo *const llvm::LowerSwitchID = &X;
// createLowerSwitchPass - Interface to this file...
FunctionPass *llvm::createLowerSwitchPass() {
return new LowerSwitch();
}
bool LowerSwitch::runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
Changed = true;
processSwitchInst(SI);
}
}
return Changed;
}
// operator<< - Used for debugging purposes.
//
static raw_ostream& operator<<(raw_ostream &O,
const LowerSwitch::CaseVector &C) __attribute((used));
static raw_ostream& operator<<(raw_ostream &O,
const LowerSwitch::CaseVector &C) {
O << "[";
for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
E = C.end(); B != E; ) {
O << *B->Low << " -" << *B->High;
if (++B != E) O << ", ";
}
return O << "]";
}
// switchConvert - Convert the switch statement into a binary lookup of
// the case values. The function recursively builds this tree.
//
BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
Value* Val, BasicBlock* OrigBlock,
BasicBlock* Default)
{
unsigned Size = End - Begin;
if (Size == 1)
return newLeafBlock(*Begin, Val, OrigBlock, Default);
unsigned Mid = Size / 2;
std::vector<CaseRange> LHS(Begin, Begin + Mid);
DEBUG(errs() << "LHS: " << LHS << "\n");
std::vector<CaseRange> RHS(Begin + Mid, End);
DEBUG(errs() << "RHS: " << RHS << "\n");
CaseRange& Pivot = *(Begin + Mid);
DEBUG(errs() << "Pivot ==> "
<< cast<ConstantInt>(Pivot.Low)->getValue() << " -"
<< cast<ConstantInt>(Pivot.High)->getValue() << "\n");
BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
OrigBlock, Default);
BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
OrigBlock, Default);
// Create a new node that checks if the value is < pivot. Go to the
// left branch if it is and right branch if not.
Function* F = OrigBlock->getParent();
BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
Function::iterator FI = OrigBlock;
F->getBasicBlockList().insert(++FI, NewNode);
ICmpInst* Comp = new ICmpInst(Default->getContext(), ICmpInst::ICMP_SLT,
Val, Pivot.Low, "Pivot");
NewNode->getInstList().push_back(Comp);
BranchInst::Create(LBranch, RBranch, Comp, NewNode);
return NewNode;
}
// newLeafBlock - Create a new leaf block for the binary lookup tree. It
// checks if the switch's value == the case's value. If not, then it
// jumps to the default branch. At this point in the tree, the value
// can't be another valid case value, so the jump to the "default" branch
// is warranted.
//
BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
BasicBlock* OrigBlock,
BasicBlock* Default)
{
Function* F = OrigBlock->getParent();
LLVMContext &Context = F->getContext();
BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
Function::iterator FI = OrigBlock;
F->getBasicBlockList().insert(++FI, NewLeaf);
// Emit comparison
ICmpInst* Comp = NULL;
if (Leaf.Low == Leaf.High) {
// Make the seteq instruction...
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
Leaf.Low, "SwitchLeaf");
} else {
// Make range comparison
if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
// Val >= Min && Val <= Hi --> Val <= Hi
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
"SwitchLeaf");
} else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
// Val >= 0 && Val <= Hi --> Val <=u Hi
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
"SwitchLeaf");
} else {
// Emit V-Lo <=u Hi-Lo
Constant* NegLo = Context.getConstantExprNeg(Leaf.Low);
Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Val->getName()+".off",
NewLeaf);
Constant *UpperBound = Context.getConstantExprAdd(NegLo, Leaf.High);
Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
"SwitchLeaf");
}
}
// Make the conditional branch...
BasicBlock* Succ = Leaf.BB;
BranchInst::Create(Succ, Default, Comp, NewLeaf);
// If there were any PHI nodes in this successor, rewrite one entry
// from OrigBlock to come from NewLeaf.
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode* PN = cast<PHINode>(I);
// Remove all but one incoming entries from the cluster
uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
cast<ConstantInt>(Leaf.Low)->getSExtValue();
for (uint64_t j = 0; j < Range; ++j) {
PN->removeIncomingValue(OrigBlock);
}
int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
assert(BlockIdx != -1 && "Switch didn't go to this successor??");
PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
}
return NewLeaf;
}
// Clusterify - Transform simple list of Cases into list of CaseRange's
unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
unsigned numCmps = 0;
// Start with "simple" cases
for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
Cases.push_back(CaseRange(SI->getSuccessorValue(i),
SI->getSuccessorValue(i),
SI->getSuccessor(i)));
std::sort(Cases.begin(), Cases.end(), CaseCmp());
// Merge case into clusters
if (Cases.size()>=2)
for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
BasicBlock* nextBB = J->BB;
BasicBlock* currentBB = I->BB;
// If the two neighboring cases go to the same destination, merge them
// into a single case.
if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
I->High = J->High;
J = Cases.erase(J);
} else {
I = J++;
}
}
for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
if (I->Low != I->High)
// A range counts double, since it requires two compares.
++numCmps;
}
return numCmps;
}
// processSwitchInst - Replace the specified switch instruction with a sequence
// of chained if-then insts in a balanced binary search.
//
void LowerSwitch::processSwitchInst(SwitchInst *SI) {
BasicBlock *CurBlock = SI->getParent();
BasicBlock *OrigBlock = CurBlock;
Function *F = CurBlock->getParent();
Value *Val = SI->getOperand(0); // The value we are switching on...
BasicBlock* Default = SI->getDefaultDest();
// If there is only the default destination, don't bother with the code below.
if (SI->getNumOperands() == 2) {
BranchInst::Create(SI->getDefaultDest(), CurBlock);
CurBlock->getInstList().erase(SI);
return;
}
// Create a new, empty default block so that the new hierarchy of
// if-then statements go to this and the PHI nodes are happy.
BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
F->getBasicBlockList().insert(Default, NewDefault);
BranchInst::Create(Default, NewDefault);
// If there is an entry in any PHI nodes for the default edge, make sure
// to update them as well.
for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
assert(BlockIdx != -1 && "Switch didn't go to this successor??");
PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
}
// Prepare cases vector.
CaseVector Cases;
unsigned numCmps = Clusterify(Cases, SI);
DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
<< ". Total compares: " << numCmps << "\n");
DEBUG(errs() << "Cases: " << Cases << "\n");
(void)numCmps;
BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
OrigBlock, NewDefault);
// Branch to our shiny new if-then stuff...
BranchInst::Create(SwitchBlock, OrigBlock);
// We are now done with the switch instruction, delete it.
CurBlock->getInstList().erase(SI);
}
<|endoftext|> |
<commit_before>#include "..\include\SceneNode.h"
namespace FGF
{
SceneNode::SceneNode(SceneNode* parent)
{
this->parent = NULL;
setParent(parent);
rot = 0.0f;
dx = dy = 0.0f;
sx = sy = 1.0f;
}
SceneNode::~SceneNode(void)
{
for(std::list<SceneNode*>::iterator i = child.begin(); i != child.end(); i++)
{
(*i)->release();
}
child.clear();
}
void SceneNode::addChild(SceneNode* child)
{
child->grab();
if(child->getParent() != NULL)
{
child->getParent()->removeChild(child);
}
this->child.push_back(child);
}
void SceneNode::removeChild(FGF::SceneNode *child)
{
this->child.remove(child);
child->release();
}
void SceneNode::setParent(SceneNode *newParent)
{
if(newParent != NULL) newParent->addChild(this);
if(this->parent != NULL) this->parent->removeChild(this);
this->parent = parent;
}
void SceneNode::rotate(float a)
{
rot += a;
}
void SceneNode::translate(float dx, float dy)
{
this->dx += dx;
this->dy += dy;
}
void SceneNode::scale(float sx, float sy)
{
this->sx *= sx;
this->sy *= sy;
}
SceneNode* SceneNode::getParent()
{
return parent;
}
void SceneNode::updateChildren(float dt)
{
std::list<SceneNode*>::iterator end = child.end();
for(std::list<SceneNode*>::iterator i = child.begin();
i != end; i++)
{
(*i)->Update(dt);
}
return;
}
void SceneNode::Update(float dt)
{
this->updateChildren(dt);
}
void SceneNode::renderChildren()
{
std::list<SceneNode*>::iterator end = child.end();
for(std::list<SceneNode*>::iterator i = child.begin();
i != end; i++)
{
(*i)->Render();
}
return;
}
void SceneNode::Render()
{
glPushMatrix();
prepare();
renderChildren();
glPopMatrix();
}
void SceneNode::prepare()
{
glTranslatef(dx,dy,0.0f);
glRotatef(rot,0.0f,0.0f,1.0f);
glScalef(sx,sy,1.0f);
}
float SceneNode::getGlobalCoord_X()
{
if(parent != NULL) return (dx + parent->getGlobalCoord_X());
else return dx;
}
float SceneNode::getGlobalCoord_Y()
{
if(parent != NULL) return (dy + parent->getGlobalCoord_Y());
else return dy;
}
float SceneNode::getGlobalRotation()
{
if(parent != NULL) return (rot + parent->getGlobalRotation());
else return rot;
}
}
<commit_msg>Поломал баг с родителями в SceneNode<commit_after>#include "..\include\SceneNode.h"
namespace FGF
{
SceneNode::SceneNode(SceneNode* parent)
{
this->parent = NULL;
setParent(parent);
rot = 0.0f;
dx = dy = 0.0f;
sx = sy = 1.0f;
this->parent = parent;
}
SceneNode::~SceneNode(void)
{
for(std::list<SceneNode*>::iterator i = child.begin(); i != child.end(); i++)
{
(*i)->release();
}
child.clear();
}
void SceneNode::addChild(SceneNode* child)
{
child->grab();
if(child->getParent() != NULL)
{
child->getParent()->removeChild(child);
}
this->child.push_back(child);
}
void SceneNode::removeChild(FGF::SceneNode *child)
{
this->child.remove(child);
child->release();
}
void SceneNode::setParent(SceneNode *newParent)
{
if(newParent != NULL) newParent->addChild(this);
else if(this->parent != NULL) parent->removeChild(this);
this->parent = parent;
}
void SceneNode::rotate(float a)
{
rot += a;
}
void SceneNode::translate(float dx, float dy)
{
this->dx += dx;
this->dy += dy;
}
void SceneNode::scale(float sx, float sy)
{
this->sx *= sx;
this->sy *= sy;
}
SceneNode* SceneNode::getParent()
{
return parent;
}
void SceneNode::updateChildren(float dt)
{
std::list<SceneNode*>::iterator end = child.end();
for(std::list<SceneNode*>::iterator i = child.begin();
i != end; i++)
{
(*i)->Update(dt);
}
return;
}
void SceneNode::Update(float dt)
{
this->updateChildren(dt);
}
void SceneNode::renderChildren()
{
std::list<SceneNode*>::iterator end = child.end();
for(std::list<SceneNode*>::iterator i = child.begin();
i != end; i++)
{
(*i)->Render();
}
return;
}
void SceneNode::Render()
{
glPushMatrix();
prepare();
renderChildren();
glPopMatrix();
}
void SceneNode::prepare()
{
glTranslatef(dx,dy,0.0f);
glRotatef(rot,0.0f,0.0f,1.0f);
glScalef(sx,sy,1.0f);
}
float SceneNode::getGlobalCoord_X()
{
if(parent != NULL) return (dx + parent->getGlobalCoord_X());
else return dx;
}
float SceneNode::getGlobalCoord_Y()
{
if(parent != NULL) return (dy + parent->getGlobalCoord_Y());
else return dy;
}
float SceneNode::getGlobalRotation()
{
if(parent != NULL) return (rot + parent->getGlobalRotation());
else return rot;
}
}
<|endoftext|> |
<commit_before>#include <Salamandre-stats/stats.hpp>
#include <Salamandre-daemon/Daemon.hpp>
#include <Salamandre-daemon/ServerBroadcast.hpp>
#include <Salamandre-daemon/define.hpp>
#include <utils/log.hpp>
#include <sys/file.h>
#include <unistd.h>
#include <iostream>
#include <csignal>
#include <tclap/CmdLine.h>
namespace salamandre
{
Daemon* daemon = nullptr;
int fd_pid;
}
void stop_server_handler(int sig)
{
utils::log::info("Stop","Recv signal",sig,"Stoping server.\n Please wait.");
if(salamandre::daemon)
salamandre::daemon->stop();
close(salamandre::fd_pid);
}
void daemonize(std::string log_path, std::string pid_path)
{
int pid = ::fork();
if (pid < 0)
{
std::cerr << "Unable to fork, exiting" << std::endl;
::exit(1);
} else if( pid != 0)
{
// Parent process, exiting
std::cout << "Turning into background... PID: " << pid << std::endl;
::exit(0);
}
// Detaching from any controlling terminal
if (::setsid() == -1)
{
::perror("Unable to detach from terminal");
::exit(1);
}
salamandre::fd_pid = ::open(pid_path.c_str(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (salamandre::fd_pid == -1)
{
::perror("Unable to create and open the pid_file");
::close(salamandre::fd_pid);
::exit(1);
}
if (::flock(salamandre::fd_pid, LOCK_EX | LOCK_NB) != 0)
{
::perror("Unable to lock the pid_file, is the daemon already running ?");
::close(salamandre::fd_pid);
::exit(1);
}
::ftruncate(salamandre::fd_pid, 0);
char buffer[32];
::snprintf(buffer, 32, "%d", ::getpid());
::write(salamandre::fd_pid, buffer, strlen(buffer));
::syncfs(salamandre::fd_pid);
std::ifstream in("/dev/null");
std::cin.rdbuf(in.rdbuf());
// That should be the good solution, but it causes segfaults
/*
std::ofstream out(log_path.c_str());
std::cout.rdbuf(out.rdbuf());
std::cerr.rdbuf(out.rdbuf());
*/
FILE * log_file = ::fopen(log_path.c_str(), "a");
::close(STDOUT_FILENO);
::dup(::fileno(log_file));
::dup2(STDOUT_FILENO, STDERR_FILENO);
::fclose(log_file);
}
int main(int argc,char* argv[])
{
int gui_port = 3842;
int server_port = 3843;
int broadcast_port = 5001;
std::string node_file_path;
bool local_only = false;
bool daemon = false;
std::string path = argv[0];
try {
TCLAP::CmdLine cmd("Salamandre Daemon", ' ', DAEMON_VERSION);
TCLAP::ValueArg<int> gui_port_arg("g", "gui-port", "Port for the GUI", false, gui_port, "int", cmd);
TCLAP::ValueArg<int> server_port_arg("s", "server-port", "Port for the server to listen", false, server_port, "int", cmd);
TCLAP::ValueArg<std::string> nodes_file_arg("f", "nodes-file", "File containing node list", false, "", "string", cmd);
TCLAP::SwitchArg local_switch("l", "local", "Whether daemon sould run stricly locally", cmd, false);
TCLAP::SwitchArg daemon_switch("d", "daemonize", "Start the server in a daemon", cmd, false);
cmd.parse(argc, argv);
local_only = local_switch.getValue();
gui_port = gui_port_arg.getValue();
server_port = server_port_arg.getValue();
node_file_path = nodes_file_arg.getValue();
daemon = daemon_switch.getValue();
} catch(TCLAP::ArgException &e) {
utils::log::critical(1,"Args ","error",e.error(),"for arg",e.argId());
}
std::cout<<"Daemon start on:"
<<"\n\tgui listen on port : "<<gui_port
<<"\n\tfile server listen on port : "<<server_port
<<"\n\tbrodcast server listen on port: "<<broadcast_port
<<"\n\tlocal only : "<<local_only
<<"\nPress ^C to exit"
<<std::endl<<std::endl;
std::signal(SIGINT, stop_server_handler);
std::signal(SIGTERM, stop_server_handler);
std::string log_file = "salamandre.log";
std::string pid_file = "salamandre.pid";
if (daemon)
{
daemonize(log_file, pid_file);
std::cout << "Daemon started on gui port : " << gui_port << ", server port : " << server_port << ", broadcast port : " << broadcast_port << std::endl;
}
try
{
salamandre::Daemon::init();
if (!node_file_path.empty())
{
salamandre::stats::Stats::load(node_file_path.c_str());
}
salamandre::daemon = new salamandre::Daemon(path, gui_port,server_port,broadcast_port,local_only);
salamandre::daemon->start();
salamandre::daemon->wait();
delete salamandre::daemon;
salamandre::daemon = nullptr;
salamandre::Daemon::close();
}
catch(ntw::SocketExeption& e)
{
utils::log::error("Socket error",e.what());
}
utils::log::info("End","Daemon is now close, Good bye");
if (daemon)
{
::unlink(pid_file.c_str());
}
return 0;
}
<commit_msg>correct log<commit_after>#include <Salamandre-stats/stats.hpp>
#include <Salamandre-daemon/Daemon.hpp>
#include <Salamandre-daemon/ServerBroadcast.hpp>
#include <Salamandre-daemon/define.hpp>
#include <utils/log.hpp>
#include <sys/file.h>
#include <unistd.h>
#include <iostream>
#include <csignal>
#include <tclap/CmdLine.h>
namespace salamandre
{
Daemon* daemon = nullptr;
int fd_pid;
}
void stop_server_handler(int sig)
{
utils::log::info("Stop","Recv signal",sig,"Stoping server.\n Please wait.");
if(salamandre::daemon)
salamandre::daemon->stop();
close(salamandre::fd_pid);
}
void daemonize(std::string log_path, std::string pid_path)
{
int pid = ::fork();
if (pid < 0)
{
std::cerr << "Unable to fork, exiting" << std::endl;
::exit(1);
} else if( pid != 0)
{
// Parent process, exiting
std::cout << "Turning into background... PID: " << pid << std::endl;
::exit(0);
}
// Detaching from any controlling terminal
if (::setsid() == -1)
{
::perror("Unable to detach from terminal");
::exit(1);
}
salamandre::fd_pid = ::open(pid_path.c_str(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (salamandre::fd_pid == -1)
{
::perror("Unable to create and open the pid_file");
::close(salamandre::fd_pid);
::exit(1);
}
if (::flock(salamandre::fd_pid, LOCK_EX | LOCK_NB) != 0)
{
::perror("Unable to lock the pid_file, is the daemon already running ?");
::close(salamandre::fd_pid);
::exit(1);
}
::ftruncate(salamandre::fd_pid, 0);
char buffer[32];
::snprintf(buffer, 32, "%d", ::getpid());
::write(salamandre::fd_pid, buffer, strlen(buffer));
::syncfs(salamandre::fd_pid);
std::ifstream in("/dev/null");
std::cin.rdbuf(in.rdbuf());
// That should be the good solution, but it causes segfaults
/*
std::ofstream out(log_path.c_str());
std::cout.rdbuf(out.rdbuf());
std::cerr.rdbuf(out.rdbuf());
*/
FILE * log_file = ::fopen(log_path.c_str(), "a");
::close(STDOUT_FILENO);
::dup(::fileno(log_file));
::dup2(STDOUT_FILENO, STDERR_FILENO);
::fclose(log_file);
}
int main(int argc,char* argv[])
{
int gui_port = 3842;
int server_port = 3843;
int broadcast_port = 5001;
std::string node_file_path;
bool local_only = false;
bool daemon = false;
std::string path = argv[0];
try {
TCLAP::CmdLine cmd("Salamandre Daemon", ' ', DAEMON_VERSION);
TCLAP::ValueArg<int> gui_port_arg("g", "gui-port", "Port for the GUI", false, gui_port, "int", cmd);
TCLAP::ValueArg<int> server_port_arg("s", "server-port", "Port for the server to listen", false, server_port, "int", cmd);
TCLAP::ValueArg<std::string> nodes_file_arg("f", "nodes-file", "File containing node list", false, "", "string", cmd);
TCLAP::SwitchArg local_switch("l", "local", "Whether daemon should run stricly locally", cmd, false);
TCLAP::SwitchArg daemon_switch("d", "daemonize", "Start the server in a daemon", cmd, false);
cmd.parse(argc, argv);
local_only = local_switch.getValue();
gui_port = gui_port_arg.getValue();
server_port = server_port_arg.getValue();
node_file_path = nodes_file_arg.getValue();
daemon = daemon_switch.getValue();
} catch(TCLAP::ArgException &e) {
utils::log::critical(1,"Args ","error",e.error(),"for arg",e.argId());
}
std::cout<<"Daemon start on:"
<<"\n\tgui listen on port : "<<gui_port
<<"\n\tfile server listen on port : "<<server_port
<<"\n\tbrodcast server listen on port: "<<broadcast_port
<<"\n\tlocal only : "<<local_only
<<"\nPress ^C to exit"
<<std::endl<<std::endl;
std::signal(SIGINT, stop_server_handler);
std::signal(SIGTERM, stop_server_handler);
std::string log_file = "salamandre.log";
std::string pid_file = "salamandre.pid";
if (daemon)
{
daemonize(log_file, pid_file);
std::cout << "Daemon started on gui port : " << gui_port << ", server port : " << server_port << ", broadcast port : " << broadcast_port << std::endl;
}
try
{
salamandre::Daemon::init();
if (!node_file_path.empty())
{
salamandre::stats::Stats::load(node_file_path.c_str());
}
salamandre::daemon = new salamandre::Daemon(path, gui_port,server_port,broadcast_port,local_only);
salamandre::daemon->start();
salamandre::daemon->wait();
delete salamandre::daemon;
salamandre::daemon = nullptr;
salamandre::Daemon::close();
}
catch(ntw::SocketExeption& e)
{
utils::log::error("Socket error",e.what());
}
utils::log::info("End","Daemon is now close, Good bye");
if (daemon)
{
::unlink(pid_file.c_str());
}
return 0;
}
<|endoftext|> |
<commit_before>
#include <gtest/gtest.h>
#include <httplib.h>
#include <future>
#include <iostream>
#ifdef _WIN32
#include <process.h>
#define msleep(n) ::Sleep(n)
#else
#define msleep(n) ::usleep(n * 1000)
#endif
using namespace std;
using namespace httplib;
const char* HOST = "localhost";
const int PORT = 1234;
#ifdef _WIN32
TEST(StartupTest, WSAStartup)
{
WSADATA wsaData;
int ret = WSAStartup(0x0002, &wsaData);
ASSERT_EQ(0, ret);
}
#endif
TEST(SplitTest, ParseQueryString)
{
string s = "key1=val1&key2=val2&key3=val3";
map<string, string> dic;
detail::split(s.c_str(), s.c_str() + s.size(), '&', [&](const char* b, const char* e) {
string key, val;
detail::split(b, e, '=', [&](const char* b, const char* e) {
if (key.empty()) {
key.assign(b, e);
} else {
val.assign(b, e);
}
});
dic[key] = val;
});
EXPECT_EQ("val1", dic["key1"]);
EXPECT_EQ("val2", dic["key2"]);
EXPECT_EQ("val3", dic["key3"]);
}
TEST(ParseQueryTest, ParseQueryString)
{
string s = "key1=val1&key2=val2&key3=val3";
map<string, string> dic;
detail::parse_query_text(s, dic);
EXPECT_EQ("val1", dic["key1"]);
EXPECT_EQ("val2", dic["key2"]);
EXPECT_EQ("val3", dic["key3"]);
}
TEST(SocketTest, OpenClose)
{
socket_t sock = detail::create_server_socket(HOST, PORT);
ASSERT_NE(-1, sock);
auto ret = detail::close_socket(sock);
EXPECT_EQ(0, ret);
}
TEST(GetHeaderValueTest, DefaultValue)
{
MultiMap map = {{"Dummy","Dummy"}};
auto val = detail::get_header_value(map, "Content-Type", "text/plain");
ASSERT_STREQ("text/plain", val);
}
TEST(GetHeaderValueTest, DefaultValueInt)
{
MultiMap map = {{"Dummy","Dummy"}};
auto val = detail::get_header_value_int(map, "Content-Length", 100);
EXPECT_EQ(100, val);
}
TEST(GetHeaderValueTest, RegularValue)
{
MultiMap map = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
auto val = detail::get_header_value(map, "Content-Type", "text/plain");
ASSERT_STREQ("text/html", val);
}
TEST(GetHeaderValueTest, RegularValueInt)
{
MultiMap map = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
auto val = detail::get_header_value_int(map, "Content-Length", 0);
EXPECT_EQ(100, val);
}
class ServerTest : public ::testing::Test {
protected:
ServerTest() : cli_(HOST, PORT), up_(false) {
}
virtual void SetUp() {
svr_.set_base_dir("./www");
svr_.get("/hi", [&](const Request& req, Response& res) {
res.set_content("Hello World!", "text/plain");
});
svr_.get("/", [&](const Request& req, Response& res) {
res.set_redirect("/hi");
});
svr_.post("/person", [&](const Request& req, Response& res) {
if (req.has_param("name") && req.has_param("note")) {
persons_[req.params.at("name")] = req.params.at("note");
} else {
res.status = 400;
}
});
svr_.get("/person/(.*)", [&](const Request& req, Response& res) {
string name = req.matches[1];
if (persons_.find(name) != persons_.end()) {
auto note = persons_[name];
res.set_content(note, "text/plain");
} else {
res.status = 404;
}
});
svr_.get("/stop", [&](const Request& req, Response& res) {
svr_.stop();
});
persons_["john"] = "programmer";
f_ = async([&](){
up_ = true;
svr_.listen(HOST, PORT);
});
while (!up_) {
msleep(1);
}
}
virtual void TearDown() {
//svr_.stop(); // NOTE: This causes dead lock on Windows.
cli_.get("/stop");
f_.get();
}
map<string, string> persons_;
Server svr_;
Client cli_;
future<void> f_;
bool up_;
};
TEST_F(ServerTest, GetMethod200)
{
auto res = cli_.get("/hi");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("Hello World!", res->body);
}
TEST_F(ServerTest, GetMethod302)
{
auto res = cli_.get("/");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(302, res->status);
EXPECT_EQ("/hi", res->get_header_value("Location"));
}
TEST_F(ServerTest, GetMethod404)
{
auto res = cli_.get("/invalid");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(404, res->status);
}
TEST_F(ServerTest, HeadMethod200)
{
auto res = cli_.head("/hi");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("", res->body);
}
TEST_F(ServerTest, HeadMethod404)
{
auto res = cli_.head("/invalid");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(404, res->status);
EXPECT_EQ("", res->body);
}
TEST_F(ServerTest, GetMethodPersonJohn)
{
auto res = cli_.get("/person/john");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("programmer", res->body);
}
TEST_F(ServerTest, PostMethod1)
{
auto res = cli_.get("/person/john1");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(404, res->status);
res = cli_.post("/person", "name=john1¬e=coder", "application/x-www-form-urlencoded");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
res = cli_.get("/person/john1");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
ASSERT_EQ("coder", res->body);
}
TEST_F(ServerTest, PostMethod2)
{
auto res = cli_.get("/person/john2");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(404, res->status);
Map params;
params["name"] = "john2";
params["note"] = "coder";
res = cli_.post("/person", params);
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
res = cli_.get("/person/john2");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
ASSERT_EQ("coder", res->body);
}
TEST_F(ServerTest, GetMethodDir)
{
auto res = cli_.get("/dir/");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
EXPECT_EQ("index.html", res->body);
}
TEST_F(ServerTest, GetMethodDirTest)
{
auto res = cli_.get("/dir/test.html");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
EXPECT_EQ("test.html", res->body);
}
TEST_F(ServerTest, InvalidBaseDir)
{
EXPECT_EQ(false, svr_.set_base_dir("invalid_dir"));
EXPECT_EQ(true, svr_.set_base_dir("./"));
}
#ifdef _WIN32
TEST(CleanupTest, WSACleanup)
{
int ret = WSACleanup();
ASSERT_EQ(0, ret);
}
#endif
// vim: et ts=4 sw=4 cin cino={1s ff=unix
<commit_msg>fixed path to the current directory.<commit_after>
#include <gtest/gtest.h>
#include <httplib.h>
#include <future>
#include <iostream>
#ifdef _WIN32
#include <process.h>
#define msleep(n) ::Sleep(n)
#else
#define msleep(n) ::usleep(n * 1000)
#endif
using namespace std;
using namespace httplib;
const char* HOST = "localhost";
const int PORT = 1234;
#ifdef _WIN32
TEST(StartupTest, WSAStartup)
{
WSADATA wsaData;
int ret = WSAStartup(0x0002, &wsaData);
ASSERT_EQ(0, ret);
}
#endif
TEST(SplitTest, ParseQueryString)
{
string s = "key1=val1&key2=val2&key3=val3";
map<string, string> dic;
detail::split(s.c_str(), s.c_str() + s.size(), '&', [&](const char* b, const char* e) {
string key, val;
detail::split(b, e, '=', [&](const char* b, const char* e) {
if (key.empty()) {
key.assign(b, e);
} else {
val.assign(b, e);
}
});
dic[key] = val;
});
EXPECT_EQ("val1", dic["key1"]);
EXPECT_EQ("val2", dic["key2"]);
EXPECT_EQ("val3", dic["key3"]);
}
TEST(ParseQueryTest, ParseQueryString)
{
string s = "key1=val1&key2=val2&key3=val3";
map<string, string> dic;
detail::parse_query_text(s, dic);
EXPECT_EQ("val1", dic["key1"]);
EXPECT_EQ("val2", dic["key2"]);
EXPECT_EQ("val3", dic["key3"]);
}
TEST(SocketTest, OpenClose)
{
socket_t sock = detail::create_server_socket(HOST, PORT);
ASSERT_NE(-1, sock);
auto ret = detail::close_socket(sock);
EXPECT_EQ(0, ret);
}
TEST(GetHeaderValueTest, DefaultValue)
{
MultiMap map = {{"Dummy","Dummy"}};
auto val = detail::get_header_value(map, "Content-Type", "text/plain");
ASSERT_STREQ("text/plain", val);
}
TEST(GetHeaderValueTest, DefaultValueInt)
{
MultiMap map = {{"Dummy","Dummy"}};
auto val = detail::get_header_value_int(map, "Content-Length", 100);
EXPECT_EQ(100, val);
}
TEST(GetHeaderValueTest, RegularValue)
{
MultiMap map = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
auto val = detail::get_header_value(map, "Content-Type", "text/plain");
ASSERT_STREQ("text/html", val);
}
TEST(GetHeaderValueTest, RegularValueInt)
{
MultiMap map = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
auto val = detail::get_header_value_int(map, "Content-Length", 0);
EXPECT_EQ(100, val);
}
class ServerTest : public ::testing::Test {
protected:
ServerTest() : cli_(HOST, PORT), up_(false) {
}
virtual void SetUp() {
svr_.set_base_dir("./www");
svr_.get("/hi", [&](const Request& req, Response& res) {
res.set_content("Hello World!", "text/plain");
});
svr_.get("/", [&](const Request& req, Response& res) {
res.set_redirect("/hi");
});
svr_.post("/person", [&](const Request& req, Response& res) {
if (req.has_param("name") && req.has_param("note")) {
persons_[req.params.at("name")] = req.params.at("note");
} else {
res.status = 400;
}
});
svr_.get("/person/(.*)", [&](const Request& req, Response& res) {
string name = req.matches[1];
if (persons_.find(name) != persons_.end()) {
auto note = persons_[name];
res.set_content(note, "text/plain");
} else {
res.status = 404;
}
});
svr_.get("/stop", [&](const Request& req, Response& res) {
svr_.stop();
});
persons_["john"] = "programmer";
f_ = async([&](){
up_ = true;
svr_.listen(HOST, PORT);
});
while (!up_) {
msleep(1);
}
}
virtual void TearDown() {
//svr_.stop(); // NOTE: This causes dead lock on Windows.
cli_.get("/stop");
f_.get();
}
map<string, string> persons_;
Server svr_;
Client cli_;
future<void> f_;
bool up_;
};
TEST_F(ServerTest, GetMethod200)
{
auto res = cli_.get("/hi");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("Hello World!", res->body);
}
TEST_F(ServerTest, GetMethod302)
{
auto res = cli_.get("/");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(302, res->status);
EXPECT_EQ("/hi", res->get_header_value("Location"));
}
TEST_F(ServerTest, GetMethod404)
{
auto res = cli_.get("/invalid");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(404, res->status);
}
TEST_F(ServerTest, HeadMethod200)
{
auto res = cli_.head("/hi");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("", res->body);
}
TEST_F(ServerTest, HeadMethod404)
{
auto res = cli_.head("/invalid");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(404, res->status);
EXPECT_EQ("", res->body);
}
TEST_F(ServerTest, GetMethodPersonJohn)
{
auto res = cli_.get("/person/john");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
EXPECT_EQ("programmer", res->body);
}
TEST_F(ServerTest, PostMethod1)
{
auto res = cli_.get("/person/john1");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(404, res->status);
res = cli_.post("/person", "name=john1¬e=coder", "application/x-www-form-urlencoded");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
res = cli_.get("/person/john1");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
ASSERT_EQ("coder", res->body);
}
TEST_F(ServerTest, PostMethod2)
{
auto res = cli_.get("/person/john2");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(404, res->status);
Map params;
params["name"] = "john2";
params["note"] = "coder";
res = cli_.post("/person", params);
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
res = cli_.get("/person/john2");
ASSERT_TRUE(res != nullptr);
ASSERT_EQ(200, res->status);
ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
ASSERT_EQ("coder", res->body);
}
TEST_F(ServerTest, GetMethodDir)
{
auto res = cli_.get("/dir/");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
EXPECT_EQ("index.html", res->body);
}
TEST_F(ServerTest, GetMethodDirTest)
{
auto res = cli_.get("/dir/test.html");
ASSERT_TRUE(res != nullptr);
EXPECT_EQ(200, res->status);
EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
EXPECT_EQ("test.html", res->body);
}
TEST_F(ServerTest, InvalidBaseDir)
{
EXPECT_EQ(false, svr_.set_base_dir("invalid_dir"));
EXPECT_EQ(true, svr_.set_base_dir("."));
}
#ifdef _WIN32
TEST(CleanupTest, WSACleanup)
{
int ret = WSACleanup();
ASSERT_EQ(0, ret);
}
#endif
// vim: et ts=4 sw=4 cin cino={1s ff=unix
<|endoftext|> |
<commit_before>#include <time.h>
#include <string>
#include <sstream>
#include "Foundation.h"
#include "AlembicLicensing.h"
#include "Alembic.h"
using namespace std;
int gLicenseToken = EC_LICENSE_RESULT_NO_LICENSE;
#if defined( EXOCORTEX_RLM_ONLY )
#include "RlmSingletonDeclarations.h"
#endif // EXOCORTEX_RLM_ONLY
bool HasFullLicense()
{
return ( GetLicense() == EC_LICENSE_RESULT_FULL_LICENSE );
}
int GetLicense()
{
if( gLicenseToken == EC_LICENSE_RESULT_NO_LICENSE )
{
// default license status, could be overriden below.
gLicenseToken = EC_LICENSE_RESULT_DEMO_LICENSE;
// check RLM license first, so that users see that RLM is either used or not prior to expiry.
#if defined( EXOCORTEX_RLM_ONLY )
{
#pragma message( "Exocortex Licensing mode: RLM only" )
static string pluginName(PLUGIN_NAME);
ESS_LOG_INFO( "Looking for RLM license for " << pluginName << "..." );
Exocortex::RlmSingleton& rlmSingleton = Exocortex::RlmSingleton::getSingleton();
RlmProductID pluginLicenseIds2[] = PLUGIN_LICENSE_IDS;
vector<RlmProductID> rlmProductIds;
for( int i = 0; i < sizeof( pluginLicenseIds2 ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds2[i] );
}
if( rlmSingleton.checkoutLicense( "", pluginName, rlmProductIds ) ) {
gLicenseToken = EC_LICENSE_RESULT_FULL_LICENSE;
return gLicenseToken;
}
}
#endif // EXOCORTEX_RLM_ONLY
#if defined( EXOCORTEX_BETA_EXPIRY_DATE )
{
#pragma message( "Exocortex Licensing mode: Fixed expiry date" )
time_t now = time(NULL);
if( now <= EXOCORTEX_BETA_EXPIRY_DATE ) { //http://unixtime-converter.com/
static string pluginName(PLUGIN_NAME);
ESS_LOG_WARNING( "Expiry date licensing is being used for " << pluginName );
gLicenseToken = EC_LICENSE_RESULT_FULL_LICENSE;
return gLicenseToken;
}
}
#endif // Exocortex_BETA_EXPIRY_DATE
}
return gLicenseToken;
}
<commit_msg>a bit more work on the integration of error reporting into 3DS Max.<commit_after>#include <time.h>
#include <string>
#include <sstream>
#include "Foundation.h"
#include "AlembicLicensing.h"
#include "Alembic.h"
using namespace std;
int gLicenseToken = EC_LICENSE_RESULT_NO_LICENSE;
#if defined( EXOCORTEX_RLM_ONLY )
#include "RlmSingletonDeclarations.h"
#endif // EXOCORTEX_RLM_ONLY
bool HasFullLicense()
{
return ( GetLicense() == EC_LICENSE_RESULT_FULL_LICENSE );
}
int GetLicense()
{
if( gLicenseToken == EC_LICENSE_RESULT_NO_LICENSE )
{
// default license status, could be overriden below.
gLicenseToken = EC_LICENSE_RESULT_DEMO_LICENSE;
// check RLM license first, so that users see that RLM is either used or not prior to expiry.
#if defined( EXOCORTEX_RLM_ONLY )
{
#pragma message( "Exocortex Licensing mode: RLM only" )
static string pluginName(PLUGIN_NAME);
ESS_LOG_INFO( "Looking for RLM license for " << pluginName << "..." );
Exocortex::RlmSingleton& rlmSingleton = Exocortex::RlmSingleton::getSingleton();
RlmProductID pluginLicenseIds2[] = PLUGIN_LICENSE_IDS;
vector<RlmProductID> rlmProductIds;
for( int i = 0; i < sizeof( pluginLicenseIds2 ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds2[i] );
}
if( rlmSingleton.checkoutLicense( "", pluginName, rlmProductIds ) ) {
gLicenseToken = EC_LICENSE_RESULT_FULL_LICENSE;
return gLicenseToken;
}
}
#endif // EXOCORTEX_RLM_ONLY
#if defined( EXOCORTEX_BETA_EXPIRY_DATE )
{
#pragma message( "Exocortex Licensing mode: Fixed expiry date" )
time_t now = time(NULL);
if( now <= EXOCORTEX_BETA_EXPIRY_DATE ) { //http://unixtime-converter.com/
static string pluginName(PLUGIN_NAME);
ESS_LOG_WARNING( "Expiry date licensing is being used for " << pluginName );
gLicenseToken = EC_LICENSE_RESULT_FULL_LICENSE;
return gLicenseToken;
}
}
#endif // Exocortex_BETA_EXPIRY_DATE
}
return gLicenseToken;
}
#ifdef EXOCORTEX_SERVICES
namespace Exocortex {
void essOnDemandInitialization() {
static string pluginName(PLUGIN_NAME);
essInitializeSoftimage( pluginName.c_str(), PLUGIN_MAJOR_VERSION, PLUGIN_MINOR_VERSION );
}
}
#endif // EXOCORTEX_SERVICES
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2021 LXQt team
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtcustomcommand.h"
#include "custombutton.h"
#include "lxqtcustomcommandconfiguration.h"
#include <QProcess>
#include <QTimer>
#include <QVBoxLayout>
#include <XdgIcon>
#include <LXQt/Globals>
#include <QDebug>
LXQtCustomCommand::LXQtCustomCommand(const ILXQtPanelPluginStartupInfo &startupInfo):
QObject(),
ILXQtPanelPlugin(startupInfo),
mProcess(new QProcess(this)),
mTimer(new QTimer(this)),
mDelayedRunTimer(new QTimer(this)),
mFirstRun(true),
mOutput(QString()),
mAutoRotate(true)
{
mButton = new CustomButton(this);
mButton->setObjectName(QLatin1String("CustomButton"));
mFont = mButton->font().toString();
mTimer->setSingleShot(true);
mDelayedRunTimer->setSingleShot(true);
mDelayedRunTimer->setInterval(500);
connect(mButton, &CustomButton::clicked, this, &LXQtCustomCommand::handleClick);
connect(mButton, &CustomButton::wheelScrolled, this, &LXQtCustomCommand::handleWheelScrolled);
connect(mTimer, &QTimer::timeout, this, &LXQtCustomCommand::runCommand);
connect(mDelayedRunTimer, &QTimer::timeout, this, &LXQtCustomCommand::runCommand);
connect(mProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &LXQtCustomCommand::handleFinished);
settingsChanged();
}
LXQtCustomCommand::~LXQtCustomCommand()
{
delete mButton;
}
QWidget *LXQtCustomCommand::widget()
{
return mButton;
}
void LXQtCustomCommand::realign()
{
mButton->setAutoRotation(mAutoRotate);
}
QDialog *LXQtCustomCommand::configureDialog()
{
if (!mConfigDialog)
mConfigDialog = new LXQtCustomCommandConfiguration(settings());
return mConfigDialog;
}
void LXQtCustomCommand::settingsChanged()
{
bool shouldRun = false;
bool oldAutoRotate = mAutoRotate;
QString oldFont = mFont;
QString oldCommand = mCommand;
bool oldRunWithBash = mRunWithBash;
bool oldRepeat = mRepeat;
int oldRepeatTimer = mRepeatTimer;
QString oldIcon = mIcon;
QString oldText = mText;
int oldMaxWidth = mMaxWidth;
mAutoRotate = settings()->value(QStringLiteral("autoRotate"), true).toBool();
mFont = settings()->value(QStringLiteral("font"), mButton->font().toString()).toString();
mCommand = settings()->value(QStringLiteral("command"), QStringLiteral("echo Configure...")).toString();
mRunWithBash = settings()->value(QStringLiteral("runWithBash"), true).toBool();
mRepeat = settings()->value(QStringLiteral("repeat"), true).toBool();
mRepeatTimer = settings()->value(QStringLiteral("repeatTimer"), 5).toInt();
mRepeatTimer = qMax(1, mRepeatTimer);
mIcon = settings()->value(QStringLiteral("icon"), QString()).toString();
mText = settings()->value(QStringLiteral("text"), QStringLiteral("%1")).toString();
mMaxWidth = settings()->value(QStringLiteral("maxWidth"), 200).toInt();
mClick = settings()->value(QStringLiteral("click"), QString()).toString();
mWheelUp = settings()->value(QStringLiteral("wheelUp"), QString()).toString();
mWheelDown = settings()->value(QStringLiteral("wheelDown"), QString()).toString();
if (oldFont != mFont) {
QFont newFont;
newFont.fromString(mFont);
if (mFirstRun) {
QTimer::singleShot(0, mButton, [this, newFont] {
mButton->setFont(newFont);
updateButton();
});
}
else {
mButton->setFont(newFont);
updateButton();
}
}
if (oldCommand != mCommand || oldRunWithBash != mRunWithBash || oldRepeat != mRepeat)
shouldRun = true;
if (oldRepeatTimer != mRepeatTimer)
mTimer->setInterval(mRepeatTimer * 1000);
if (oldIcon != mIcon) {
mButton->setIcon(XdgIcon::fromTheme(mIcon, QIcon(mIcon)));
updateButton();
}
else if (oldText != mText)
updateButton();
if (oldMaxWidth != mMaxWidth)
mButton->setMaxWidth(mMaxWidth);
if (oldAutoRotate != mAutoRotate)
mButton->setAutoRotation(mAutoRotate);
if (mFirstRun) {
mFirstRun = false;
runCommand();
}
// Delay timer for running command, avoids multiple calls on settings change while typing command or clicking "Reset"
else if (shouldRun)
mDelayedRunTimer->start();
}
void LXQtCustomCommand::handleClick()
{
if (!mClick.isEmpty())
runDetached(mClick);
}
void LXQtCustomCommand::handleFinished(int exitCode, QProcess::ExitStatus /*exitStatus*/)
{
if (exitCode == 0) {
mOutput = QString::fromUtf8(mProcess->readAllStandardOutput());
if (mOutput.endsWith(QStringLiteral("\n")))
mOutput.chop(1);
}
else
mOutput = tr("Error");
updateButton();
if (mRepeat)
mTimer->start();
}
void LXQtCustomCommand::updateButton() {
QString newText = mText;
if (newText.contains(QStringLiteral("%1")))
newText = newText.arg(mOutput);
if (mButton->icon().isNull())
mButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
else
mButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
mButton->setText(newText);
mButton->updateWidth();
}
void LXQtCustomCommand::handleWheelScrolled(int yDelta)
{
if (yDelta > 0 && !mWheelUp.isEmpty())
runDetached(mWheelUp);
else if (yDelta < 0 && !mWheelDown.isEmpty())
runDetached(mWheelDown);
}
void LXQtCustomCommand::runCommand()
{
if (mCommand.isEmpty())
return;
if (mProcess->state() != QProcess::NotRunning) {
mDelayedRunTimer->start();
return;
}
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
QStringList args;
if (mRunWithBash)
args << QStringLiteral("bash") << QStringLiteral("-c") << mCommand;
else
args = QProcess::splitCommand(mCommand);
mProcess->start(args.takeFirst(), args);
#else
QString exec;
if (mRunWithBash)
exec = QString(QStringLiteral("bash -c \"%1\"")).arg(mCommand);
else
exec = mCommand;
mProcess->start(exec);
#endif
}
void LXQtCustomCommand::runDetached(QString command)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
QStringList args = QProcess::splitCommand(command);
QProcess::startDetached(args.takeFirst(), args);
#else
QProcess::startDetached(command);
#endif
}
<commit_msg>CustomCommand: close QProcess on destructor (#1711)<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2021 LXQt team
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtcustomcommand.h"
#include "custombutton.h"
#include "lxqtcustomcommandconfiguration.h"
#include <QProcess>
#include <QTimer>
#include <QVBoxLayout>
#include <XdgIcon>
#include <LXQt/Globals>
#include <QDebug>
LXQtCustomCommand::LXQtCustomCommand(const ILXQtPanelPluginStartupInfo &startupInfo):
QObject(),
ILXQtPanelPlugin(startupInfo),
mProcess(new QProcess(this)),
mTimer(new QTimer(this)),
mDelayedRunTimer(new QTimer(this)),
mFirstRun(true),
mOutput(QString()),
mAutoRotate(true)
{
mButton = new CustomButton(this);
mButton->setObjectName(QLatin1String("CustomButton"));
mFont = mButton->font().toString();
mTimer->setSingleShot(true);
mDelayedRunTimer->setSingleShot(true);
mDelayedRunTimer->setInterval(500);
connect(mButton, &CustomButton::clicked, this, &LXQtCustomCommand::handleClick);
connect(mButton, &CustomButton::wheelScrolled, this, &LXQtCustomCommand::handleWheelScrolled);
connect(mTimer, &QTimer::timeout, this, &LXQtCustomCommand::runCommand);
connect(mDelayedRunTimer, &QTimer::timeout, this, &LXQtCustomCommand::runCommand);
connect(mProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &LXQtCustomCommand::handleFinished);
settingsChanged();
}
LXQtCustomCommand::~LXQtCustomCommand()
{
// Ensure process is closed before exiting and avoids warning from QProcess.
mProcess->close();
delete mButton;
}
QWidget *LXQtCustomCommand::widget()
{
return mButton;
}
void LXQtCustomCommand::realign()
{
mButton->setAutoRotation(mAutoRotate);
}
QDialog *LXQtCustomCommand::configureDialog()
{
if (!mConfigDialog)
mConfigDialog = new LXQtCustomCommandConfiguration(settings());
return mConfigDialog;
}
void LXQtCustomCommand::settingsChanged()
{
bool shouldRun = false;
bool oldAutoRotate = mAutoRotate;
QString oldFont = mFont;
QString oldCommand = mCommand;
bool oldRunWithBash = mRunWithBash;
bool oldRepeat = mRepeat;
int oldRepeatTimer = mRepeatTimer;
QString oldIcon = mIcon;
QString oldText = mText;
int oldMaxWidth = mMaxWidth;
mAutoRotate = settings()->value(QStringLiteral("autoRotate"), true).toBool();
mFont = settings()->value(QStringLiteral("font"), mButton->font().toString()).toString();
mCommand = settings()->value(QStringLiteral("command"), QStringLiteral("echo Configure...")).toString();
mRunWithBash = settings()->value(QStringLiteral("runWithBash"), true).toBool();
mRepeat = settings()->value(QStringLiteral("repeat"), true).toBool();
mRepeatTimer = settings()->value(QStringLiteral("repeatTimer"), 5).toInt();
mRepeatTimer = qMax(1, mRepeatTimer);
mIcon = settings()->value(QStringLiteral("icon"), QString()).toString();
mText = settings()->value(QStringLiteral("text"), QStringLiteral("%1")).toString();
mMaxWidth = settings()->value(QStringLiteral("maxWidth"), 200).toInt();
mClick = settings()->value(QStringLiteral("click"), QString()).toString();
mWheelUp = settings()->value(QStringLiteral("wheelUp"), QString()).toString();
mWheelDown = settings()->value(QStringLiteral("wheelDown"), QString()).toString();
if (oldFont != mFont) {
QFont newFont;
newFont.fromString(mFont);
if (mFirstRun) {
QTimer::singleShot(0, mButton, [this, newFont] {
mButton->setFont(newFont);
updateButton();
});
}
else {
mButton->setFont(newFont);
updateButton();
}
}
if (oldCommand != mCommand || oldRunWithBash != mRunWithBash || oldRepeat != mRepeat)
shouldRun = true;
if (oldRepeatTimer != mRepeatTimer)
mTimer->setInterval(mRepeatTimer * 1000);
if (oldIcon != mIcon) {
mButton->setIcon(XdgIcon::fromTheme(mIcon, QIcon(mIcon)));
updateButton();
}
else if (oldText != mText)
updateButton();
if (oldMaxWidth != mMaxWidth)
mButton->setMaxWidth(mMaxWidth);
if (oldAutoRotate != mAutoRotate)
mButton->setAutoRotation(mAutoRotate);
if (mFirstRun) {
mFirstRun = false;
runCommand();
}
// Delay timer for running command, avoids multiple calls on settings change while typing command or clicking "Reset"
else if (shouldRun)
mDelayedRunTimer->start();
}
void LXQtCustomCommand::handleClick()
{
if (!mClick.isEmpty())
runDetached(mClick);
}
void LXQtCustomCommand::handleFinished(int exitCode, QProcess::ExitStatus /*exitStatus*/)
{
if (exitCode == 0) {
mOutput = QString::fromUtf8(mProcess->readAllStandardOutput());
if (mOutput.endsWith(QStringLiteral("\n")))
mOutput.chop(1);
}
else
mOutput = tr("Error");
updateButton();
if (mRepeat)
mTimer->start();
}
void LXQtCustomCommand::updateButton() {
QString newText = mText;
if (newText.contains(QStringLiteral("%1")))
newText = newText.arg(mOutput);
if (mButton->icon().isNull())
mButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
else
mButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
mButton->setText(newText);
mButton->updateWidth();
}
void LXQtCustomCommand::handleWheelScrolled(int yDelta)
{
if (yDelta > 0 && !mWheelUp.isEmpty())
runDetached(mWheelUp);
else if (yDelta < 0 && !mWheelDown.isEmpty())
runDetached(mWheelDown);
}
void LXQtCustomCommand::runCommand()
{
if (mCommand.isEmpty())
return;
if (mProcess->state() != QProcess::NotRunning) {
mDelayedRunTimer->start();
return;
}
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
QStringList args;
if (mRunWithBash)
args << QStringLiteral("bash") << QStringLiteral("-c") << mCommand;
else
args = QProcess::splitCommand(mCommand);
mProcess->start(args.takeFirst(), args);
#else
QString exec;
if (mRunWithBash)
exec = QString(QStringLiteral("bash -c \"%1\"")).arg(mCommand);
else
exec = mCommand;
mProcess->start(exec);
#endif
}
void LXQtCustomCommand::runDetached(QString command)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
QStringList args = QProcess::splitCommand(command);
QProcess::startDetached(args.takeFirst(), args);
#else
QProcess::startDetached(command);
#endif
}
<|endoftext|> |
<commit_before>#include "EndScreen.hpp"
#include "../Application.hpp"
#include "Room.hpp"
#include "Player.hpp"
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/Text.hpp>
using namespace Game;
sf::Shader grayTone;
EndScreen::EndScreen(Room* room)
: mRoom(room)
, mTime(0)
{
grayTone.loadFromMemory(
"uniform float dt;\n"
"\n"
"void main(){\n"
" float gray = dot(gl_Color.rgb, vec3(0.299, 0.587, 0.114));\n"
" vec4 grayVec = vec4(gray, gray, gray, gl_Color.a);\n"
" gl_FragColor = mix(gl_Color, grayVec, dt);\n"
"}", sf::Shader::Fragment);
}
void EndScreen::update(float dt)
{
mTime += dt / 2;
grayTone.setUniform("dt", std::min(mTime, 1.f));
}
void EndScreen::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
sf::RectangleShape background(sf::Vector2f(rt.getSize()));
background.setFillColor(sf::Color(0, 0, 0, std::min(1.f, mTime) * 180));
rt.draw(background);
// TODO:
sf::Text text("", Application::getApplication()->getDefaultFont());
rt.draw(text);
}
const sf::Shader* EndScreen::getGrayscale() const
{
return &grayTone;
}<commit_msg>Some end-of-game text<commit_after>#include "EndScreen.hpp"
#include "../Application.hpp"
#include "Room.hpp"
#include "Player.hpp"
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/Text.hpp>
using namespace Game;
sf::Shader grayTone;
EndScreen::EndScreen(Room* room)
: mRoom(room)
, mTime(0)
{
grayTone.loadFromMemory(
"uniform float dt;\n"
"\n"
"void main(){\n"
" float gray = dot(gl_Color.rgb, vec3(0.299, 0.587, 0.114));\n"
" vec4 grayVec = vec4(gray, gray, gray, gl_Color.a);\n"
" gl_FragColor = mix(gl_Color, grayVec, dt);\n"
"}", sf::Shader::Fragment);
}
void EndScreen::update(float dt)
{
mTime += dt / 2;
grayTone.setUniform("dt", std::min(mTime, 1.f));
}
void EndScreen::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
sf::RectangleShape background(sf::Vector2f(rt.getSize()));
background.setFillColor(sf::Color(0, 0, 0, std::min(1.f, mTime) * 180));
rt.draw(background);
auto& player = *mRoom->getPlayer();
// TODO:
sf::Text text("Game Over", Application::getApplication()->getDefaultFont());
text.move(15, 15);
rt.draw(text);
auto rect = text.getGlobalBounds();
text.move(0, rect.height + 64);
text.setString(std::string("You managed ") + std::to_string(player.getDays()) + " days.");
rt.draw(text);
rect = text.getGlobalBounds();
text.move(0, rect.height + 15);
text.setString(std::to_string(player.getDrinksServed()) + " drinks were served.");
rt.draw(text);
rect = text.getGlobalBounds();
text.move(0, rect.height + 8);
text.setString(std::to_string(player.getDrinksPoured()) + " drinks were poured away.");
rt.draw(text);
rect = text.getGlobalBounds();
text.move(0, rect.height + 5);
text.setString(std::to_string(player.getDrinksMissed()) + " customers didn't get their orders.");
rt.draw(text);
rect = text.getGlobalBounds();
text.move(0, rect.height + 32);
text.setString(std::string("Topping out at ") + std::to_string(int(player.getMaxMoney())) + "$");
rt.draw(text);
}
const sf::Shader* EndScreen::getGrayscale() const
{
return &grayTone;
}<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Math_Angle_inl_
#define _Stroika_Foundation_Math_Angle_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Math {
inline Angle::Angle ()
: fAngleInRadians (0)
{
}
inline Angle::Angle (double angle, AngleFormat angleFormat)
: fAngleInRadians (angle)
{
switch (angleFormat) {
case eRadians:
break;
case eDegrees:
fAngleInRadians *= (2*kPi) / 360.0;
break;
case eGradians:
fAngleInRadians *= (2*kPi) / 400.0;
break;
default:
RequireNotReached ();
}
}
inline double Angle::AsRadians () const
{
return (fAngleInRadians);
}
inline double Angle::AsDegrees () const
{
return (fAngleInRadians * 360.0/(2*kPi));
}
inline double Angle::AsGradians () const
{
return (fAngleInRadians * 400.0/(2*kPi));
}
inline const Angle& Angle::operator+= (const Angle& rhs)
{
fAngleInRadians += rhs.AsRadians ();
return (*this);
}
inline const Angle& Angle::operator-= (const Angle& rhs)
{
fAngleInRadians -= rhs.AsRadians ();
return (*this);
}
inline const Angle& Angle::operator*= (double rhs)
{
fAngleInRadians *= rhs;
return (*this);
}
inline const Angle& Angle::operator/= (double rhs)
{
fAngleInRadians /= rhs;
return (*this);
}
inline Angle operator+ (const Angle& lhs, const Angle& rhs)
{
return (Angle (lhs.AsRadians () + rhs.AsRadians ()));
}
inline Angle operator- (const Angle& lhs, const Angle& rhs)
{
return (Angle (lhs.AsRadians () - rhs.AsRadians ()));
}
inline Angle operator* (const Angle& lhs, double rhs)
{
return (Angle (lhs.AsRadians () * rhs));
}
inline Angle operator* (double lhs, const Angle& rhs)
{
return (Angle (lhs * rhs.AsRadians ()));
}
inline Angle operator/ (const Angle& lhs, double rhs)
{
return (Angle (lhs.AsRadians () / rhs));
}
inline bool Math::operator== (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () == rhs.AsRadians ());
}
inline bool Math::operator!= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () != rhs.AsRadians ());
}
inline bool Math::operator< (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () < rhs.AsRadians ());
}
inline bool Math::operator<= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () <= rhs.AsRadians ());
}
inline bool Math::operator> (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () > rhs.AsRadians ());
}
inline bool Math::operator>= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () >= rhs.AsRadians ());
}
inline Angle Math::Min (const Angle& a1, const Angle& a2)
{
return ((a1 < a2)? a1: a2);
}
inline Angle Math::Max (const Angle& a1, const Angle& a2)
{
return ((a1 > a2)? a1: a2);
}
}
}
}
#endif /*_Stroika_Foundation_Math_Angle_inl_*/
<commit_msg>remove incorrect scope qualifiers (wrong namespace and also not allowed as redundant)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Math_Angle_inl_
#define _Stroika_Foundation_Math_Angle_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Math {
inline Angle::Angle ()
: fAngleInRadians (0)
{
}
inline Angle::Angle (double angle, AngleFormat angleFormat)
: fAngleInRadians (angle)
{
switch (angleFormat) {
case eRadians:
break;
case eDegrees:
fAngleInRadians *= (2*kPi) / 360.0;
break;
case eGradians:
fAngleInRadians *= (2*kPi) / 400.0;
break;
default:
RequireNotReached ();
}
}
inline double Angle::AsRadians () const
{
return (fAngleInRadians);
}
inline double Angle::AsDegrees () const
{
return (fAngleInRadians * 360.0/(2*kPi));
}
inline double Angle::AsGradians () const
{
return (fAngleInRadians * 400.0/(2*kPi));
}
inline const Angle& Angle::operator+= (const Angle& rhs)
{
fAngleInRadians += rhs.AsRadians ();
return (*this);
}
inline const Angle& Angle::operator-= (const Angle& rhs)
{
fAngleInRadians -= rhs.AsRadians ();
return (*this);
}
inline const Angle& Angle::operator*= (double rhs)
{
fAngleInRadians *= rhs;
return (*this);
}
inline const Angle& Angle::operator/= (double rhs)
{
fAngleInRadians /= rhs;
return (*this);
}
inline Angle operator+ (const Angle& lhs, const Angle& rhs)
{
return (Angle (lhs.AsRadians () + rhs.AsRadians ()));
}
inline Angle operator- (const Angle& lhs, const Angle& rhs)
{
return (Angle (lhs.AsRadians () - rhs.AsRadians ()));
}
inline Angle operator* (const Angle& lhs, double rhs)
{
return (Angle (lhs.AsRadians () * rhs));
}
inline Angle operator* (double lhs, const Angle& rhs)
{
return (Angle (lhs * rhs.AsRadians ()));
}
inline Angle operator/ (const Angle& lhs, double rhs)
{
return (Angle (lhs.AsRadians () / rhs));
}
inline bool operator== (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () == rhs.AsRadians ());
}
inline bool operator!= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () != rhs.AsRadians ());
}
inline bool operator< (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () < rhs.AsRadians ());
}
inline bool operator<= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () <= rhs.AsRadians ());
}
inline bool operator> (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () > rhs.AsRadians ());
}
inline bool operator>= (const Angle& lhs, const Angle& rhs)
{
return (lhs.AsRadians () >= rhs.AsRadians ());
}
inline Angle Min (const Angle& a1, const Angle& a2)
{
return ((a1 < a2)? a1: a2);
}
inline Angle Max (const Angle& a1, const Angle& a2)
{
return ((a1 > a2)? a1: a2);
}
}
}
}
#endif /*_Stroika_Foundation_Math_Angle_inl_*/
<|endoftext|> |
<commit_before>//
// Created by Esha Uboweja on 12/5/16.
//
#include "BinaryLayer.h"
#include "TestBinaryConvolution.h"
#define DEBUG 1
using namespace bd;
using namespace bconv;
void TestBinaryConvolution::printTestArma2(std::string testName, std::string desc, arma::mat input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma2(std::string testName, std::string desc, arma::umat input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestBM(std::string testName, std::string desc, BinaryMatrix input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor3d " << desc << " : \n";
input.print();
std::cout << std::endl;
#endif
}
void TestBinaryConvolution::printTestArma3(std::string testName, std::string desc, arma::cube input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma3(std::string testName, std::string desc, arma::ucube input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestBT3(std::string testName, std::string desc, BinaryTensor3D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor3d " << desc << " : \n"
<< input.toString() << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma4(std::string testName, std::string desc, ArmaUTensor4D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma tensor4D" << desc << " : \n";
for (uint f = 0; f < input.size(); ++f) {
std::cout << "[ARMA FILTER #" << f << "]:\n" << input[f] << std::endl;
}
#endif
}
void TestBinaryConvolution::printTestBT4(std::string testName, std::string desc, BinaryTensor4D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor4d " << desc << " : \n"
<< BinaryConvolution::bt4ToString(input) << std::endl;
#endif
}
template<typename T>
void TestBinaryConvolution::printTestVec(std::string testName, std::string desc, std::vector<T> input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] vector " << desc << " : \n";
for (auto value : input) {
std::cout << value << std::endl;
}
std::cout << std::endl;
#endif
}
bool TestBinaryConvolution::test_convolution_single(uint rows_in, uint cols_in, uint width, uint height,
uint channels, uint filters, uint stride,
Convolution conv_type) {
std::string testName = "test_convolution_single";
BinaryConvolution bconv = BinaryConvolution(width, height, channels, filters, stride, conv_type, Nonlinearity::none,
Pooling::none);
// Generate a random input matrix
arma::cube input3D = BinaryTensor3D::randomArmaCube(rows_in, cols_in, channels);
printTestArma3(testName, "Arma Input3D", input3D);
// Normalize the input
arma::cube norm_input3D = bconv.normalizeData3D(input3D);
printTestArma3(testName, "Arma Normalized Input3D", norm_input3D);
// Compute K beta matrix
arma::mat K = bconv.input2KMat(norm_input3D);
printTestArma2(testName, "Arma K betas for input", K);
/*
// Generate a random weights matrix
ArmaUTensor4D armaWeights4D = BinaryConvolution::randomTensor4DUArma(width, height, channels, filters);
printTestUArma4(testName, "Arma weights 4D", armaWeights4D);
std::vector<double> alphaPerFilter;
alphaPerFilter.reserve(filters);
for (uint f = 0; f < filters; ++f) {
alphaPerFilter.emplace_back(1.0);
}
printTestVec(testName, "weights 4D alphas", alphaPerFilter);
BinaryTensor4D bt4Weights4D = BinaryConvolution::uarmaToBT4(armaWeights4D);
printTestBT4(testName, "Binary weights 4D", bt4Weights4D);
bconv.setWeights(bt4Weights4D);
*/
return true;
}
bool TestBinaryConvolution::test_convolution() {
return test_convolution_single();
}
void TestBinaryConvolution::runAllTests() {
std::cout << "----Testing BinaryConvolution class functions...\n";
bool result = test_convolution();
std::cout << "[TestBinaryConvolution] Tests completed! Result = " << (result? "PASSED" : "FAILED") << std::endl;
}<commit_msg>setWeights calls correctly<commit_after>//
// Created by Esha Uboweja on 12/5/16.
//
#include "BinaryLayer.h"
#include "TestBinaryConvolution.h"
#define DEBUG 1
using namespace bd;
using namespace bconv;
void TestBinaryConvolution::printTestArma2(std::string testName, std::string desc, arma::mat input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma2(std::string testName, std::string desc, arma::umat input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestBM(std::string testName, std::string desc, BinaryMatrix input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor3d " << desc << " : \n";
input.print();
std::cout << std::endl;
#endif
}
void TestBinaryConvolution::printTestArma3(std::string testName, std::string desc, arma::cube input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma3(std::string testName, std::string desc, arma::ucube input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma cube " << desc << " : \n" << input << std::endl;
#endif
}
void TestBinaryConvolution::printTestBT3(std::string testName, std::string desc, BinaryTensor3D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor3d " << desc << " : \n"
<< input.toString() << std::endl;
#endif
}
void TestBinaryConvolution::printTestUArma4(std::string testName, std::string desc, ArmaUTensor4D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] arma tensor4D" << desc << " : \n";
for (uint f = 0; f < input.size(); ++f) {
std::cout << "[ARMA FILTER #" << f << "]:\n" << input[f] << std::endl;
}
#endif
}
void TestBinaryConvolution::printTestBT4(std::string testName, std::string desc, BinaryTensor4D input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] binary tensor4d " << desc << " : \n"
<< BinaryConvolution::bt4ToString(input) << std::endl;
#endif
}
template<typename T>
void TestBinaryConvolution::printTestVec(std::string testName, std::string desc, std::vector<T> input) {
#ifdef DEBUG
std::cout << "[TestBinaryConvolution::" << testName << "] vector " << desc << " : \n";
for (auto value : input) {
std::cout << value << std::endl;
}
std::cout << std::endl;
#endif
}
bool TestBinaryConvolution::test_convolution_single(uint rows_in, uint cols_in, uint width, uint height,
uint channels, uint filters, uint stride,
Convolution conv_type) {
std::string testName = "test_convolution_single";
BinaryConvolution bconv = BinaryConvolution(width, height, channels, filters, stride, conv_type, Nonlinearity::none,
Pooling::none);
// Generate a random input matrix
arma::cube input3D = BinaryTensor3D::randomArmaCube(rows_in, cols_in, channels);
printTestArma3(testName, "Arma Input3D", input3D);
// Normalize the input
arma::cube norm_input3D = bconv.normalizeData3D(input3D);
printTestArma3(testName, "Arma Normalized Input3D", norm_input3D);
// Compute K beta matrix
arma::mat K = bconv.input2KMat(norm_input3D);
printTestArma2(testName, "Arma K betas for input", K);
// Generate a random weights matrix
ArmaUTensor4D armaWeights4D = BinaryConvolution::randomTensor4DUArma(width, height, channels, filters);
printTestUArma4(testName, "Arma weights 4D", armaWeights4D);
std::vector<double> alphaPerFilter;
alphaPerFilter.reserve(filters);
for (uint f = 0; f < filters; ++f) {
alphaPerFilter.emplace_back(1.0);
}
printTestVec(testName, "weights 4D alphas", alphaPerFilter);
BinaryTensor4D bt4Weights4D = BinaryConvolution::uarmaToBT4(armaWeights4D);
printTestBT4(testName, "Binary weights 4D", bt4Weights4D);
bconv.setWeights(bt4Weights4D);
return true;
}
bool TestBinaryConvolution::test_convolution() {
return test_convolution_single();
}
void TestBinaryConvolution::runAllTests() {
std::cout << "----Testing BinaryConvolution class functions...\n";
bool result = test_convolution();
std::cout << "[TestBinaryConvolution] Tests completed! Result = " << (result? "PASSED" : "FAILED") << std::endl;
}<|endoftext|> |
<commit_before>
/*
DISCLAIMER
This software can be used freely under GNU/LGPL license.
File : Session.h
Author : Mustafa K. GILOR
Purpose : Session class for the libtcp server.
All individual session info are stored in this class.
It is automatically destroyed when last shared_ptr instance is released.
*/
#pragma once
#pragma region Includes
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/atomic.hpp>
#include <boost/noncopyable.hpp>
#include "CircularBuffer.hpp"
#include "Session_Configuration.hpp"
using boost::asio::ip::tcp;
#pragma endregion
class Session : public boost::enable_shared_from_this<Session>, public boost::noncopyable
{
public:
typedef boost::shared_ptr<Session> pointer;
/*
Invoked when client is connected
*/
void OnConnect();
/*
Disconnects the session from connected endpoint.
*/
void Disconnect();
/*
Initializes the variables required for session.
*/
void Initialize();
/*
Keep alive system callback.
*/
void CheckAlive();
/*
Inheriting class should override this method by this signature :
void OnDataReceived(char *, size_t) override;
*/
virtual void OnDataReceived(char *, size_t) = 0;
virtual void OnConnected() = 0;
virtual void OnDisconnected() = 0;
/*
Returns server's IP address
*/
std::string GetLocalIPAddress() const { return local_; }
/*
Returns IP address of connected client
*/
std::string GetRemoteIPAddress() const { return remote_; }
/*
Returns server's port
*/
unsigned short GetLocalPort() const { return localp_; }
/*
Returns connected client's port
*/
unsigned short GetRemotePort() const { return remotep_; }
/*
Returns the ID assigned to this session
*/
unsigned long long GetSessionID() const { return m_ulSessionID; }
/*
Returns the socket object
*/
tcp::socket& socket() { return socket_; }
protected:
/*
Default constructor (protected)
*/
Session(boost::asio::io_service& io_service, void * srv) :
socket_(io_service),serverPtr(srv),fragment_count(0),
isDisconnected(false),m_ulSessionID(0)
{
m_readBuffer.Allocate(RECV_BUFFER_SIZE);
m_readBuffer.Remove(RECV_BUFFER_SIZE);
}
/*
Sends given buffer to the connected endpoint.
*/
void Send(void * buf, size_t len);
private:
/*
Socket
*/
tcp::socket socket_;
/*
Ring buffer for read operation
*/
CircularBuffer m_readBuffer;
/*
A mutex for the read event.
It is claimed by any thread that completes a read event.
Other pending read event should wait until current thread completes
its' job.
*/
boost::recursive_mutex readMutex;
/*
Last data receive time.
*/
boost::atomic<unsigned long long> m_aulLastReceiveTime;
/*
Total received data amount (bytes)
*/
boost::atomic<unsigned long long> m_aulReceiveCount;
/*
Previous total received data amount (bytes)
*/
boost::atomic<unsigned long long> m_aulPrevReceiveCount;
/*
Maximum count of fragmented packet(s).
If a session exceeds the MAX_PACKET_FRAGMENT_COUNT value
it will be disconnected eventually.
*/
boost::atomic<int> fragment_count;
/*
Indicates if client is disconnected.
*/
boost::atomic<bool> isDisconnected;
/*
Identifier of this session.
It is assigned by owner server and it should not be
altered anywhere.(otherwise things might go crazy.)
*/
unsigned long long m_ulSessionID;
/*
Pointer to the owner server
*/
void * serverPtr;
/*
Variables to store IP addresses
*/
std::string local_, remote_;
/*
Variables to store port values
*/
unsigned short localp_, remotep_;
/*
Sets defined socket options for this session.
*/
void SetSocketOptions();
/*
Invoked when an asynchronous write operation is completed
*/
void OnWriteCompleted(const boost::system::error_code&, size_t s);
/*
Invoked when an asynchronous read operation is completed
*/
void OnReadCompleted(const boost::system::error_code& err, std::size_t bytes_transferred);
/*
Dispatches the parse event.
*/
void DispatchParse(size_t rSize);
/*
Issues another asynchronous read operation to fill the read buffer (if there's any data available.)
*/
void DispatchRead();
};
<commit_msg>Session ID assignation<commit_after>
/*
DISCLAIMER
This software can be used freely under GNU/LGPL license.
File : Session.h
Author : Mustafa K. GILOR
Purpose : Session class for the libtcp server.
All individual session info are stored in this class.
It is automatically destroyed when last shared_ptr instance is released.
*/
#pragma once
#pragma region Includes
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/atomic.hpp>
#include <boost/noncopyable.hpp>
#include "CircularBuffer.hpp"
#include "Session_Configuration.hpp"
using boost::asio::ip::tcp;
#pragma endregion
class Session : public boost::enable_shared_from_this<Session>, public boost::noncopyable
{
public:
typedef boost::shared_ptr<Session> pointer;
/*
Invoked when client is connected
*/
void OnConnect();
/*
Disconnects the session from connected endpoint.
*/
void Disconnect();
/*
Initializes the variables required for session.
*/
void Initialize();
/*
Keep alive system callback.
*/
void CheckAlive();
/*
Inheriting class should override this method by this signature :
void OnDataReceived(char *, size_t) override;
*/
virtual void OnDataReceived(char *, size_t) = 0;
virtual void OnConnected() = 0;
virtual void OnDisconnected() = 0;
/*
Returns server's IP address
*/
std::string GetLocalIPAddress() const { return local_; }
/*
Returns IP address of connected client
*/
std::string GetRemoteIPAddress() const { return remote_; }
/*
Returns server's port
*/
unsigned short GetLocalPort() const { return localp_; }
/*
Returns connected client's port
*/
unsigned short GetRemotePort() const { return remotep_; }
/*
Returns the ID assigned to this session
*/
unsigned long long GetSessionID() const { return m_ulSessionID; }
void SetSessionID(unsigned long long id) { m_ulSessionID = id; }
/*
Returns the socket object
*/
tcp::socket& socket() { return socket_; }
protected:
/*
Default constructor (protected)
*/
Session(boost::asio::io_service& io_service, void * srv) :
socket_(io_service),serverPtr(srv),fragment_count(0),
isDisconnected(false),m_ulSessionID(0)
{
m_readBuffer.Allocate(RECV_BUFFER_SIZE);
m_readBuffer.Remove(RECV_BUFFER_SIZE);
}
/*
Sends given buffer to the connected endpoint.
*/
void Send(void * buf, size_t len);
private:
/*
Socket
*/
tcp::socket socket_;
/*
Ring buffer for read operation
*/
CircularBuffer m_readBuffer;
/*
A mutex for the read event.
It is claimed by any thread that completes a read event.
Other pending read event should wait until current thread completes
its' job.
*/
boost::recursive_mutex readMutex;
/*
Last data receive time.
*/
boost::atomic<unsigned long long> m_aulLastReceiveTime;
/*
Total received data amount (bytes)
*/
boost::atomic<unsigned long long> m_aulReceiveCount;
/*
Previous total received data amount (bytes)
*/
boost::atomic<unsigned long long> m_aulPrevReceiveCount;
/*
Maximum count of fragmented packet(s).
If a session exceeds the MAX_PACKET_FRAGMENT_COUNT value
it will be disconnected eventually.
*/
boost::atomic<int> fragment_count;
/*
Indicates if client is disconnected.
*/
boost::atomic<bool> isDisconnected;
/*
Identifier of this session.
It is assigned by owner server and it should not be
altered anywhere.(otherwise things might go crazy.)
*/
unsigned long long m_ulSessionID;
/*
Pointer to the owner server
*/
void * serverPtr;
/*
Variables to store IP addresses
*/
std::string local_, remote_;
/*
Variables to store port values
*/
unsigned short localp_, remotep_;
/*
Sets defined socket options for this session.
*/
void SetSocketOptions();
/*
Invoked when an asynchronous write operation is completed
*/
void OnWriteCompleted(const boost::system::error_code&, size_t s);
/*
Invoked when an asynchronous read operation is completed
*/
void OnReadCompleted(const boost::system::error_code& err, std::size_t bytes_transferred);
/*
Dispatches the parse event.
*/
void DispatchParse(size_t rSize);
/*
Issues another asynchronous read operation to fill the read buffer (if there's any data available.)
*/
void DispatchRead();
};
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRepAlgoAPI_Fuse.hxx>
# include <BRepCheck_Analyzer.hxx>
# include <Standard_Failure.hxx>
# include <TopoDS_Iterator.hxx>
# include <TopTools_IndexedMapOfShape.hxx>
# include <TopExp.hxx>
#endif
#include "FeaturePartFuse.h"
#include "modelRefine.h"
#include <App/Application.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
using namespace Part;
PROPERTY_SOURCE(Part::Fuse, Part::Boolean)
Fuse::Fuse(void)
{
}
BRepAlgoAPI_BooleanOperation* Fuse::makeOperation(const TopoDS_Shape& base, const TopoDS_Shape& tool) const
{
// Let's call algorithm computing a fuse operation:
return new BRepAlgoAPI_Fuse(base, tool);
}
// ----------------------------------------------------
PROPERTY_SOURCE(Part::MultiFuse, Part::Feature)
MultiFuse::MultiFuse(void)
{
ADD_PROPERTY(Shapes,(0));
Shapes.setSize(0);
ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType)
(App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history");
History.setSize(0);
}
short MultiFuse::mustExecute() const
{
if (Shapes.isTouched())
return 1;
return 0;
}
App::DocumentObjectExecReturn *MultiFuse::execute(void)
{
std::vector<TopoDS_Shape> s;
std::vector<App::DocumentObject*> obj = Shapes.getValues();
std::vector<App::DocumentObject*>::iterator it;
for (it = obj.begin(); it != obj.end(); ++it) {
if ((*it)->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
s.push_back(static_cast<Part::Feature*>(*it)->Shape.getValue());
}
}
bool argumentsAreInCompound = false;
TopoDS_Shape compoundOfArguments;
//if only one source shape, and it is a compound - fuse children of the compound
if (s.size() == 1){
compoundOfArguments = s[0];
if (compoundOfArguments.ShapeType() == TopAbs_COMPOUND){
s.clear();
TopoDS_Iterator it(compoundOfArguments);
for (; it.More(); it.Next()) {
const TopoDS_Shape& aChild = it.Value();
s.push_back(aChild);
}
argumentsAreInCompound = true;
}
}
if (s.size() >= 2) {
try {
std::vector<ShapeHistory> history;
#if OCC_VERSION_HEX <= 0x060800
TopoDS_Shape resShape = s.front();
if (resShape.IsNull())
throw Base::Exception("Input shape is null");
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
if (it->IsNull())
throw Base::Exception("Input shape is null");
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(resShape, *it);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
resShape = mkFuse.Shape();
ShapeHistory hist1 = buildHistory(mkFuse, TopAbs_FACE, resShape, mkFuse.Shape1());
ShapeHistory hist2 = buildHistory(mkFuse, TopAbs_FACE, resShape, mkFuse.Shape2());
if (history.empty()) {
history.push_back(hist1);
history.push_back(hist2);
}
else {
for (std::vector<ShapeHistory>::iterator jt = history.begin(); jt != history.end(); ++jt)
*jt = joinHistory(*jt, hist1);
history.push_back(hist2);
}
}
#else
BRepAlgoAPI_Fuse mkFuse;
TopTools_ListOfShape shapeArguments,shapeTools;
shapeArguments.Append(s.front());
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
if (it->IsNull())
throw Base::Exception("Input shape is null");
shapeTools.Append(*it);
}
mkFuse.SetArguments(shapeArguments);
mkFuse.SetTools(shapeTools);
mkFuse.Build();
if (!mkFuse.IsDone())
throw Base::Exception("MultiFusion failed");
TopoDS_Shape resShape = mkFuse.Shape();
for (std::vector<TopoDS_Shape>::iterator it = s.begin(); it != s.end(); ++it) {
history.push_back(buildHistory(mkFuse, TopAbs_FACE, resShape, *it));
}
#endif
if (resShape.IsNull())
throw Base::Exception("Resulting shape is null");
Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
.GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean");
if (hGrp->GetBool("CheckModel", false)) {
BRepCheck_Analyzer aChecker(resShape);
if (! aChecker.IsValid() ) {
return new App::DocumentObjectExecReturn("Resulting shape is invalid");
}
}
if (hGrp->GetBool("RefineModel", false)) {
try {
TopoDS_Shape oldShape = resShape;
BRepBuilderAPI_RefineModel mkRefine(oldShape);
resShape = mkRefine.Shape();
ShapeHistory hist = buildHistory(mkRefine, TopAbs_FACE, resShape, oldShape);
for (std::vector<ShapeHistory>::iterator jt = history.begin(); jt != history.end(); ++jt)
*jt = joinHistory(*jt, hist);
}
catch (Standard_Failure) {
// do nothing
}
}
this->Shape.setValue(resShape);
if (argumentsAreInCompound){
//combine histories of every child of source compound into one
ShapeHistory overallHist;
TopTools_IndexedMapOfShape facesOfCompound;
TopAbs_ShapeEnum type = TopAbs_FACE;
TopExp::MapShapes(compoundOfArguments, type, facesOfCompound);
for (std::size_t iChild = 0; iChild < history.size(); iChild++){ //loop over children of source compound
//for each face of a child, find the inex of the face in compound, and assign the corresponding right-hand-size of the history
TopTools_IndexedMapOfShape facesOfChild;
TopExp::MapShapes(s[iChild], type, facesOfChild);
for(std::pair<const int,ShapeHistory::List> &histitem: history[iChild].shapeMap){ //loop over elements of history - that is - over faces of the child of source compound
int iFaceInChild = histitem.first;
ShapeHistory::List &iFacesInResult = histitem.second;
TopoDS_Shape srcFace = facesOfChild(iFaceInChild + 1); //+1 to convert our 0-based to OCC 1-bsed conventions
int iFaceInCompound = facesOfCompound.FindIndex(srcFace)-1;
overallHist.shapeMap[iFaceInCompound] = iFacesInResult; //this may overwrite existing info if the same face is used in several children of compound. This shouldn't be a problem, because the histories should match anyway...
}
}
history.clear();
history.push_back(overallHist);
}
this->History.setValues(history);
}
catch (Standard_Failure& e) {
return new App::DocumentObjectExecReturn(e.GetMessageString());
}
}
else {
throw Base::Exception("Not enough shape objects linked");
}
return App::DocumentObject::StdReturn;
}
<commit_msg>in mult-fusion feature check if input shapes are valid<commit_after>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRepAlgoAPI_Fuse.hxx>
# include <BRepCheck_Analyzer.hxx>
# include <Standard_Failure.hxx>
# include <TopoDS_Iterator.hxx>
# include <TopTools_IndexedMapOfShape.hxx>
# include <TopExp.hxx>
#endif
#include "FeaturePartFuse.h"
#include "modelRefine.h"
#include <App/Application.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
using namespace Part;
PROPERTY_SOURCE(Part::Fuse, Part::Boolean)
Fuse::Fuse(void)
{
}
BRepAlgoAPI_BooleanOperation* Fuse::makeOperation(const TopoDS_Shape& base, const TopoDS_Shape& tool) const
{
// Let's call algorithm computing a fuse operation:
return new BRepAlgoAPI_Fuse(base, tool);
}
// ----------------------------------------------------
PROPERTY_SOURCE(Part::MultiFuse, Part::Feature)
MultiFuse::MultiFuse(void)
{
ADD_PROPERTY(Shapes,(0));
Shapes.setSize(0);
ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType)
(App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history");
History.setSize(0);
}
short MultiFuse::mustExecute() const
{
if (Shapes.isTouched())
return 1;
return 0;
}
App::DocumentObjectExecReturn *MultiFuse::execute(void)
{
std::vector<TopoDS_Shape> s;
std::vector<App::DocumentObject*> obj = Shapes.getValues();
std::vector<App::DocumentObject*>::iterator it;
for (it = obj.begin(); it != obj.end(); ++it) {
if ((*it)->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
s.push_back(static_cast<Part::Feature*>(*it)->Shape.getValue());
}
}
bool argumentsAreInCompound = false;
TopoDS_Shape compoundOfArguments;
//if only one source shape, and it is a compound - fuse children of the compound
if (s.size() == 1){
compoundOfArguments = s[0];
if (compoundOfArguments.ShapeType() == TopAbs_COMPOUND){
s.clear();
TopoDS_Iterator it(compoundOfArguments);
for (; it.More(); it.Next()) {
const TopoDS_Shape& aChild = it.Value();
s.push_back(aChild);
}
argumentsAreInCompound = true;
}
}
if (s.size() >= 2) {
try {
std::vector<ShapeHistory> history;
#if OCC_VERSION_HEX <= 0x060800
TopoDS_Shape resShape = s.front();
if (resShape.IsNull())
throw Base::Exception("Input shape is null");
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
if (it->IsNull())
throw Base::Exception("Input shape is null");
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(resShape, *it);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
resShape = mkFuse.Shape();
ShapeHistory hist1 = buildHistory(mkFuse, TopAbs_FACE, resShape, mkFuse.Shape1());
ShapeHistory hist2 = buildHistory(mkFuse, TopAbs_FACE, resShape, mkFuse.Shape2());
if (history.empty()) {
history.push_back(hist1);
history.push_back(hist2);
}
else {
for (std::vector<ShapeHistory>::iterator jt = history.begin(); jt != history.end(); ++jt)
*jt = joinHistory(*jt, hist1);
history.push_back(hist2);
}
}
#else
BRepAlgoAPI_Fuse mkFuse;
TopTools_ListOfShape shapeArguments,shapeTools;
const TopoDS_Shape& shape = s.front();
if (shape.IsNull())
throw Base::RuntimeError("Input shape is null");
shapeArguments.Append(shape);
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
if (it->IsNull())
throw Base::RuntimeError("Input shape is null");
shapeTools.Append(*it);
}
mkFuse.SetArguments(shapeArguments);
mkFuse.SetTools(shapeTools);
mkFuse.Build();
if (!mkFuse.IsDone())
throw Base::RuntimeError("MultiFusion failed");
TopoDS_Shape resShape = mkFuse.Shape();
for (std::vector<TopoDS_Shape>::iterator it = s.begin(); it != s.end(); ++it) {
history.push_back(buildHistory(mkFuse, TopAbs_FACE, resShape, *it));
}
#endif
if (resShape.IsNull())
throw Base::RuntimeError("Resulting shape is null");
Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
.GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean");
if (hGrp->GetBool("CheckModel", false)) {
BRepCheck_Analyzer aChecker(resShape);
if (! aChecker.IsValid() ) {
return new App::DocumentObjectExecReturn("Resulting shape is invalid");
}
}
if (hGrp->GetBool("RefineModel", false)) {
try {
TopoDS_Shape oldShape = resShape;
BRepBuilderAPI_RefineModel mkRefine(oldShape);
resShape = mkRefine.Shape();
ShapeHistory hist = buildHistory(mkRefine, TopAbs_FACE, resShape, oldShape);
for (std::vector<ShapeHistory>::iterator jt = history.begin(); jt != history.end(); ++jt)
*jt = joinHistory(*jt, hist);
}
catch (Standard_Failure) {
// do nothing
}
}
this->Shape.setValue(resShape);
if (argumentsAreInCompound){
//combine histories of every child of source compound into one
ShapeHistory overallHist;
TopTools_IndexedMapOfShape facesOfCompound;
TopAbs_ShapeEnum type = TopAbs_FACE;
TopExp::MapShapes(compoundOfArguments, type, facesOfCompound);
for (std::size_t iChild = 0; iChild < history.size(); iChild++){ //loop over children of source compound
//for each face of a child, find the inex of the face in compound, and assign the corresponding right-hand-size of the history
TopTools_IndexedMapOfShape facesOfChild;
TopExp::MapShapes(s[iChild], type, facesOfChild);
for(std::pair<const int,ShapeHistory::List> &histitem: history[iChild].shapeMap){ //loop over elements of history - that is - over faces of the child of source compound
int iFaceInChild = histitem.first;
ShapeHistory::List &iFacesInResult = histitem.second;
TopoDS_Shape srcFace = facesOfChild(iFaceInChild + 1); //+1 to convert our 0-based to OCC 1-bsed conventions
int iFaceInCompound = facesOfCompound.FindIndex(srcFace)-1;
overallHist.shapeMap[iFaceInCompound] = iFacesInResult; //this may overwrite existing info if the same face is used in several children of compound. This shouldn't be a problem, because the histories should match anyway...
}
}
history.clear();
history.push_back(overallHist);
}
this->History.setValues(history);
}
catch (Standard_Failure& e) {
return new App::DocumentObjectExecReturn(e.GetMessageString());
}
}
else {
throw Base::Exception("Not enough shape objects linked");
}
return App::DocumentObject::StdReturn;
}
<|endoftext|> |
<commit_before>#include <osg/Geometry>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
static void add_user_value_func_AttributeBinding(osgDB::IntLookup* lookup)
{
lookup->add("BIND_OFF",0); // ADD_USER_VALUE("ADD_USER_VALUE( BIND_OFF );
lookup->add("BIND_OVERALL",1); // ADD_USER_VALUE( BIND_OVERALL );
lookup->add("BIND_PER_PRIMITIVE_SET",2); // ADD_USER_VALUE( BIND_PER_PRIMITIVE_SET );
lookup->add("BIND_PER_PRIMITIVE",3); //ADD_USER_VALUE( BIND_PER_PRIMITIVE );
lookup->add("BIND_PER_VERTEX",4); // ADD_USER_VALUE( BIND_PER_VERTEX );
}
static osgDB::UserLookupTableProxy s_user_lookup_table_AttributeBinding(&add_user_value_func_AttributeBinding);
USER_READ_FUNC( AttributeBinding, readAttributeBinding )
USER_WRITE_FUNC( AttributeBinding, writeAttributeBinding )
static osg::Array* readArray( osgDB::InputStream& is)
{
osg::ref_ptr<osg::Array> array;
bool hasArray = false;
is >> is.PROPERTY("Array") >> hasArray;
if ( hasArray ) array = is.readArray();
bool hasIndices = false;
is >> is.PROPERTY("Indices") >> hasIndices;
if ( hasIndices )
{
osg::ref_ptr<osg::Array> indices_array = is.readArray();
osg::ref_ptr<osg::IndexArray> indices = dynamic_cast<osg::IndexArray*>( indices_array.get() );
if (array.valid() && indices.valid()) array->setUserData(indices.get());
}
is >> is.PROPERTY("Binding");
int binding = readAttributeBinding(is);
if (array.valid()) array->setBinding(static_cast<osg::Array::Binding>(binding));
int normalizeValue = 0;
is >> is.PROPERTY("Normalize") >> normalizeValue;
if (array.valid()) array->setNormalize(normalizeValue!=0);
return array.release();
}
static void writeArray( osgDB::OutputStream& os, const osg::Array* array)
{
os << os.PROPERTY("Array") << (array!=0);
if ( array!=0 ) os << array;
else os << std::endl;
const osg::IndexArray* indices = (array!=0) ? dynamic_cast<const osg::IndexArray*>(array->getUserData()) : 0;
os << os.PROPERTY("Indices") << (indices!=0);
if ( indices!=0 ) os << indices;
else os << std::endl;
os << os.PROPERTY("Binding"); writeAttributeBinding(os, osg::getBinding(array)); os << std::endl;
os << os.PROPERTY("Normalize") << ((array!=0 && array->getNormalize()) ? 1:0) << std::endl;
}
#define ADD_ARRAYDATA_FUNCTIONS( ORIGINAL_PROP, PROP ) \
static bool check##ORIGINAL_PROP( const osg::Geometry& geom ) \
{ return geom.get##PROP()!=0; } \
static bool read##ORIGINAL_PROP( osgDB::InputStream& is, osg::Geometry& geom ) { \
is >> is.BEGIN_BRACKET; \
osg::Array* array = readArray(is); \
geom.set##PROP(array); \
is >> is.END_BRACKET; \
return true; \
} \
static bool write##ORIGINAL_PROP( osgDB::OutputStream& os, const osg::Geometry& geom ) { \
os << os.BEGIN_BRACKET << std::endl; \
writeArray(os, geom.get##PROP()); \
os << os.END_BRACKET << std::endl; \
return true; \
}
ADD_ARRAYDATA_FUNCTIONS( VertexData, VertexArray )
ADD_ARRAYDATA_FUNCTIONS( NormalData, NormalArray )
ADD_ARRAYDATA_FUNCTIONS( ColorData, ColorArray )
ADD_ARRAYDATA_FUNCTIONS( SecondaryColorData, SecondaryColorArray )
ADD_ARRAYDATA_FUNCTIONS( FogCoordData, FogCoordArray )
#define ADD_ARRAYLIST_FUNCTIONS( ORIGINAL_PROP, PROP, LISTNAME ) \
static bool check##ORIGINAL_PROP( const osg::Geometry& geom ) \
{ return geom.get##LISTNAME().size()>0; } \
static bool read##ORIGINAL_PROP( osgDB::InputStream& is, osg::Geometry& geom ) { \
unsigned int size = is.readSize(); is >> is.BEGIN_BRACKET; \
for ( unsigned int i=0; i<size; ++i ) { \
is >> is.PROPERTY("Data") >> is.BEGIN_BRACKET; \
osg::Array* array = readArray(is); \
geom.set##PROP(i, array); \
is >> is.END_BRACKET; } \
is >> is.END_BRACKET; \
return true; \
} \
static bool write##ORIGINAL_PROP( osgDB::OutputStream& os, const osg::Geometry& geom ) { \
const osg::Geometry::ArrayList& LISTNAME = geom.get##LISTNAME(); \
os.writeSize(LISTNAME.size()); os << os.BEGIN_BRACKET << std::endl; \
for ( osg::Geometry::ArrayList::const_iterator itr=LISTNAME.begin(); \
itr!=LISTNAME.end(); ++itr ) { \
os << os.PROPERTY("Data") << os.BEGIN_BRACKET << std::endl; \
writeArray(os, itr->get()); os << os.END_BRACKET << std::endl; \
} \
os << os.END_BRACKET << std::endl; \
return true; \
}
ADD_ARRAYLIST_FUNCTIONS( TexCoordData, TexCoordArray, TexCoordArrayList )
ADD_ARRAYLIST_FUNCTIONS( VertexAttribData, VertexAttribArray, VertexAttribArrayList )
struct GeometryFinishedObjectReadCallback : public osgDB::FinishedObjectReadCallback
{
virtual void objectRead(osgDB::InputStream&, osg::Object& obj)
{
osg::Geometry& geometry = static_cast<osg::Geometry&>(obj);
if (geometry.getUseVertexBufferObjects())
{
geometry.setUseVertexBufferObjects(false);
geometry.setUseVertexBufferObjects(true);
}
}
};
// implement backwards compatibility with reading/writing the FastPathHint
static bool checkFastPathHint( const osg::Geometry& geom ) { return false; }
static bool readFastPathHint( osgDB::InputStream& is, osg::Geometry& geom )
{
// Compatibility info:
// Previous Geometry wrapper (before 3.1.8) require a bool fast-path serializer.
// It saves "FastPathHint true" in ascii mode and a single [bool] in binary mode.
// Becoming a user serializer, the serializer will first read the name "FastPathHint"
// or a [bool] in the checking process, then call the reading function as here. So,
// we will only need to read one more bool variable in ascii mode; otherwise do nothing
bool value = false;
if ( !is.isBinary() ) is >> value;
return true;
}
static bool writeFastPathHint( osgDB::OutputStream& os, const osg::Geometry& geom )
{
return true;
}
REGISTER_OBJECT_WRAPPER( Geometry,
new osg::Geometry,
osg::Geometry,
"osg::Object osg::Node osg::Drawable osg::Geometry" )
{
{
UPDATE_TO_VERSION_SCOPED( 154 )
ADDED_ASSOCIATE("osg::Node")
}
//ADD_LIST_SERIALIZER( PrimitiveSetList, osg::Geometry::PrimitiveSetList ); // _primitives
ADD_VECTOR_SERIALIZER( PrimitiveSetList, osg::Geometry::PrimitiveSetList, osgDB::BaseSerializer::RW_OBJECT, 0 );
ADD_USER_SERIALIZER( VertexData ); // _vertexData
ADD_USER_SERIALIZER( NormalData ); // _normalData
ADD_USER_SERIALIZER( ColorData ); // _colorData
ADD_USER_SERIALIZER( SecondaryColorData ); // _secondaryColorData
ADD_USER_SERIALIZER( FogCoordData ); // _fogCoordData
ADD_USER_SERIALIZER( TexCoordData ); // _texCoordList
ADD_USER_SERIALIZER( VertexAttribData ); // _vertexAttribList
ADD_USER_SERIALIZER( FastPathHint ); // _fastPathHint
{
UPDATE_TO_VERSION_SCOPED( 112 )
REMOVE_SERIALIZER( VertexData );
REMOVE_SERIALIZER( NormalData );
REMOVE_SERIALIZER( ColorData );
REMOVE_SERIALIZER( SecondaryColorData );
REMOVE_SERIALIZER( FogCoordData );
REMOVE_SERIALIZER( TexCoordData );
REMOVE_SERIALIZER( VertexAttribData );
REMOVE_SERIALIZER( FastPathHint );
ADD_OBJECT_SERIALIZER( VertexArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( NormalArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( ColorArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( SecondaryColorArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( FogCoordArray, osg::Array, NULL );
ADD_VECTOR_SERIALIZER( TexCoordArrayList, osg::Geometry::ArrayList, osgDB::BaseSerializer::RW_OBJECT, 0 );
ADD_VECTOR_SERIALIZER( VertexAttribArrayList, osg::Geometry::ArrayList, osgDB::BaseSerializer::RW_OBJECT, 0 );
}
wrapper->addFinishedObjectReadCallback( new GeometryFinishedObjectReadCallback() );
}
<commit_msg>Disabled the use of the GeometryFinishedObjectReadCallback in the Geometry serializer as this doesn't look it's needed anymore.<commit_after>#include <osg/Geometry>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
// #define USE_GEOMETRY_FINALIZER_CALLBACK
static void add_user_value_func_AttributeBinding(osgDB::IntLookup* lookup)
{
lookup->add("BIND_OFF",0); // ADD_USER_VALUE("ADD_USER_VALUE( BIND_OFF );
lookup->add("BIND_OVERALL",1); // ADD_USER_VALUE( BIND_OVERALL );
lookup->add("BIND_PER_PRIMITIVE_SET",2); // ADD_USER_VALUE( BIND_PER_PRIMITIVE_SET );
lookup->add("BIND_PER_PRIMITIVE",3); //ADD_USER_VALUE( BIND_PER_PRIMITIVE );
lookup->add("BIND_PER_VERTEX",4); // ADD_USER_VALUE( BIND_PER_VERTEX );
}
static osgDB::UserLookupTableProxy s_user_lookup_table_AttributeBinding(&add_user_value_func_AttributeBinding);
USER_READ_FUNC( AttributeBinding, readAttributeBinding )
USER_WRITE_FUNC( AttributeBinding, writeAttributeBinding )
static osg::Array* readArray( osgDB::InputStream& is)
{
osg::ref_ptr<osg::Array> array;
bool hasArray = false;
is >> is.PROPERTY("Array") >> hasArray;
if ( hasArray ) array = is.readArray();
bool hasIndices = false;
is >> is.PROPERTY("Indices") >> hasIndices;
if ( hasIndices )
{
osg::ref_ptr<osg::Array> indices_array = is.readArray();
osg::ref_ptr<osg::IndexArray> indices = dynamic_cast<osg::IndexArray*>( indices_array.get() );
if (array.valid() && indices.valid()) array->setUserData(indices.get());
}
is >> is.PROPERTY("Binding");
int binding = readAttributeBinding(is);
if (array.valid()) array->setBinding(static_cast<osg::Array::Binding>(binding));
int normalizeValue = 0;
is >> is.PROPERTY("Normalize") >> normalizeValue;
if (array.valid()) array->setNormalize(normalizeValue!=0);
return array.release();
}
static void writeArray( osgDB::OutputStream& os, const osg::Array* array)
{
os << os.PROPERTY("Array") << (array!=0);
if ( array!=0 ) os << array;
else os << std::endl;
const osg::IndexArray* indices = (array!=0) ? dynamic_cast<const osg::IndexArray*>(array->getUserData()) : 0;
os << os.PROPERTY("Indices") << (indices!=0);
if ( indices!=0 ) os << indices;
else os << std::endl;
os << os.PROPERTY("Binding"); writeAttributeBinding(os, osg::getBinding(array)); os << std::endl;
os << os.PROPERTY("Normalize") << ((array!=0 && array->getNormalize()) ? 1:0) << std::endl;
}
#define ADD_ARRAYDATA_FUNCTIONS( ORIGINAL_PROP, PROP ) \
static bool check##ORIGINAL_PROP( const osg::Geometry& geom ) \
{ return geom.get##PROP()!=0; } \
static bool read##ORIGINAL_PROP( osgDB::InputStream& is, osg::Geometry& geom ) { \
is >> is.BEGIN_BRACKET; \
osg::Array* array = readArray(is); \
geom.set##PROP(array); \
is >> is.END_BRACKET; \
return true; \
} \
static bool write##ORIGINAL_PROP( osgDB::OutputStream& os, const osg::Geometry& geom ) { \
os << os.BEGIN_BRACKET << std::endl; \
writeArray(os, geom.get##PROP()); \
os << os.END_BRACKET << std::endl; \
return true; \
}
ADD_ARRAYDATA_FUNCTIONS( VertexData, VertexArray )
ADD_ARRAYDATA_FUNCTIONS( NormalData, NormalArray )
ADD_ARRAYDATA_FUNCTIONS( ColorData, ColorArray )
ADD_ARRAYDATA_FUNCTIONS( SecondaryColorData, SecondaryColorArray )
ADD_ARRAYDATA_FUNCTIONS( FogCoordData, FogCoordArray )
#define ADD_ARRAYLIST_FUNCTIONS( ORIGINAL_PROP, PROP, LISTNAME ) \
static bool check##ORIGINAL_PROP( const osg::Geometry& geom ) \
{ return geom.get##LISTNAME().size()>0; } \
static bool read##ORIGINAL_PROP( osgDB::InputStream& is, osg::Geometry& geom ) { \
unsigned int size = is.readSize(); is >> is.BEGIN_BRACKET; \
for ( unsigned int i=0; i<size; ++i ) { \
is >> is.PROPERTY("Data") >> is.BEGIN_BRACKET; \
osg::Array* array = readArray(is); \
geom.set##PROP(i, array); \
is >> is.END_BRACKET; } \
is >> is.END_BRACKET; \
return true; \
} \
static bool write##ORIGINAL_PROP( osgDB::OutputStream& os, const osg::Geometry& geom ) { \
const osg::Geometry::ArrayList& LISTNAME = geom.get##LISTNAME(); \
os.writeSize(LISTNAME.size()); os << os.BEGIN_BRACKET << std::endl; \
for ( osg::Geometry::ArrayList::const_iterator itr=LISTNAME.begin(); \
itr!=LISTNAME.end(); ++itr ) { \
os << os.PROPERTY("Data") << os.BEGIN_BRACKET << std::endl; \
writeArray(os, itr->get()); os << os.END_BRACKET << std::endl; \
} \
os << os.END_BRACKET << std::endl; \
return true; \
}
ADD_ARRAYLIST_FUNCTIONS( TexCoordData, TexCoordArray, TexCoordArrayList )
ADD_ARRAYLIST_FUNCTIONS( VertexAttribData, VertexAttribArray, VertexAttribArrayList )
struct GeometryFinishedObjectReadCallback : public osgDB::FinishedObjectReadCallback
{
virtual void objectRead(osgDB::InputStream&, osg::Object& obj)
{
osg::Geometry& geometry = static_cast<osg::Geometry&>(obj);
if (geometry.getUseVertexBufferObjects())
{
geometry.setUseVertexBufferObjects(false);
geometry.setUseVertexBufferObjects(true);
}
}
};
// implement backwards compatibility with reading/writing the FastPathHint
static bool checkFastPathHint( const osg::Geometry& geom ) { return false; }
static bool readFastPathHint( osgDB::InputStream& is, osg::Geometry& geom )
{
// Compatibility info:
// Previous Geometry wrapper (before 3.1.8) require a bool fast-path serializer.
// It saves "FastPathHint true" in ascii mode and a single [bool] in binary mode.
// Becoming a user serializer, the serializer will first read the name "FastPathHint"
// or a [bool] in the checking process, then call the reading function as here. So,
// we will only need to read one more bool variable in ascii mode; otherwise do nothing
bool value = false;
if ( !is.isBinary() ) is >> value;
return true;
}
static bool writeFastPathHint( osgDB::OutputStream& os, const osg::Geometry& geom )
{
return true;
}
REGISTER_OBJECT_WRAPPER( Geometry,
new osg::Geometry,
osg::Geometry,
"osg::Object osg::Node osg::Drawable osg::Geometry" )
{
{
UPDATE_TO_VERSION_SCOPED( 154 )
ADDED_ASSOCIATE("osg::Node")
}
//ADD_LIST_SERIALIZER( PrimitiveSetList, osg::Geometry::PrimitiveSetList ); // _primitives
ADD_VECTOR_SERIALIZER( PrimitiveSetList, osg::Geometry::PrimitiveSetList, osgDB::BaseSerializer::RW_OBJECT, 0 );
ADD_USER_SERIALIZER( VertexData ); // _vertexData
ADD_USER_SERIALIZER( NormalData ); // _normalData
ADD_USER_SERIALIZER( ColorData ); // _colorData
ADD_USER_SERIALIZER( SecondaryColorData ); // _secondaryColorData
ADD_USER_SERIALIZER( FogCoordData ); // _fogCoordData
ADD_USER_SERIALIZER( TexCoordData ); // _texCoordList
ADD_USER_SERIALIZER( VertexAttribData ); // _vertexAttribList
ADD_USER_SERIALIZER( FastPathHint ); // _fastPathHint
{
UPDATE_TO_VERSION_SCOPED( 112 )
REMOVE_SERIALIZER( VertexData );
REMOVE_SERIALIZER( NormalData );
REMOVE_SERIALIZER( ColorData );
REMOVE_SERIALIZER( SecondaryColorData );
REMOVE_SERIALIZER( FogCoordData );
REMOVE_SERIALIZER( TexCoordData );
REMOVE_SERIALIZER( VertexAttribData );
REMOVE_SERIALIZER( FastPathHint );
ADD_OBJECT_SERIALIZER( VertexArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( NormalArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( ColorArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( SecondaryColorArray, osg::Array, NULL );
ADD_OBJECT_SERIALIZER( FogCoordArray, osg::Array, NULL );
ADD_VECTOR_SERIALIZER( TexCoordArrayList, osg::Geometry::ArrayList, osgDB::BaseSerializer::RW_OBJECT, 0 );
ADD_VECTOR_SERIALIZER( VertexAttribArrayList, osg::Geometry::ArrayList, osgDB::BaseSerializer::RW_OBJECT, 0 );
}
#ifdef USE_GEOMETRY_FINALIZER_CALLBACK
wrapper->addFinishedObjectReadCallback( new GeometryFinishedObjectReadCallback() );
#endif
}
<|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 "config.h"
#include "webkit/glue/image_decoder.h"
#pragma warning(push, 0)
#include "ImageSourceSkia.h"
#include "IntSize.h"
#include "RefPtr.h"
#include "SharedBuffer.h"
#pragma warning(pop)
#include "SkBitmap.h"
namespace webkit_glue {
ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) {
}
ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size)
: desired_icon_size_(desired_icon_size) {
}
ImageDecoder::~ImageDecoder() {
}
SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) {
WebCore::ImageSourceSkia source;
WTF::RefPtr<WebCore::SharedBuffer> buffer(new WebCore::SharedBuffer(
data, static_cast<int>(size)));
source.setData(buffer.get(), true,
WebCore::IntSize(desired_icon_size_.width(),
desired_icon_size_.height()));
if (!source.isSizeAvailable())
return SkBitmap();
WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0);
if (!frame0)
return SkBitmap();
return *reinterpret_cast<SkBitmap*>(frame0);
}
} // namespace webkit_glue
<commit_msg>Convert CG images to Skia to draw.<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 "config.h"
#include "webkit/glue/image_decoder.h"
#pragma warning(push, 0)
#if defined(OS_WIN)
#include "ImageSourceSkia.h"
#elif defined(OS_MACOSX)
#include "ImageSource.h"
#include "RetainPtr.h"
#endif
#include "IntSize.h"
#include "RefPtr.h"
#include "SharedBuffer.h"
#pragma warning(pop)
#include "SkBitmap.h"
namespace webkit_glue {
ImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) {
}
ImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size)
: desired_icon_size_(desired_icon_size) {
}
ImageDecoder::~ImageDecoder() {
}
SkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) {
// What's going on here? ImageDecoder is only used by ImageResourceFetcher,
// which is only used (but extensively) by WebViewImpl. On the Mac we're using
// CoreGraphics, but right now WebViewImpl uses SkBitmaps everywhere. For now,
// this is a convenient bottleneck to convert from CGImageRefs to SkBitmaps,
// but in the future we will need to replumb to get CGImageRefs (or whatever
// the native type is) everywhere, directly.
#if defined(OS_WIN)
WebCore::ImageSourceSkia source;
#elif defined(OS_MACOSX)
WebCore::ImageSource source;
#endif
WTF::RefPtr<WebCore::SharedBuffer> buffer(new WebCore::SharedBuffer(
data, static_cast<int>(size)));
#if defined(OS_WIN)
source.setData(buffer.get(), true,
WebCore::IntSize(desired_icon_size_.width(),
desired_icon_size_.height()));
#elif defined(OS_MACOSX)
source.setData(buffer.get(), true);
#endif
if (!source.isSizeAvailable())
return SkBitmap();
WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0);
if (!frame0)
return SkBitmap();
#if defined(OS_WIN)
return *reinterpret_cast<SkBitmap*>(frame0);
#elif defined(OS_MACOSX)
// BitmapImage releases automatically, but we're bypassing it so we'll need
// to do the releasing.
RetainPtr<CGImageRef> image(AdoptCF, frame0);
SkBitmap result;
result.setConfig(SkBitmap::kARGB_8888_Config, CGImageGetWidth(image.get()),
CGImageGetHeight(image.get()));
RetainPtr<CGColorSpace> cg_color(AdoptCF, CGColorSpaceCreateDeviceRGB());
// The last parameter is a total guess. Feel free to adjust it if images draw
// incorrectly. TODO(avi): Verify byte ordering; it should be possible to
// swizzle bytes with various combinations of the byte order and alpha
// constants.
RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(
result.getPixels(),
result.width(),
result.height(),
result.bytesPerPixel() * 8 / 4,
result.rowBytes(),
cg_color.get(),
kCGImageAlphaPremultipliedFirst |
kCGBitmapByteOrder32Host));
CGRect rect = CGRectMake(0, 0,
CGImageGetWidth(image.get()),
CGImageGetHeight(image.get()));
CGContextDrawImage(context.get(), rect, image.get());
return result;
#endif
}
} // namespace webkit_glue
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#include <iostream>
#include "itkBresenhamLine.h"
int
itkBresenhamLineTest(int, char *[])
{
{
// Test BuildLine(Vector, distance)
itk::Vector<float, 2> v;
v[0] = 1;
v[1] = 1;
itk::BresenhamLine<2> line;
std::vector<itk::Offset<2>> offsets = line.BuildLine(v, 4);
if (offsets.size() != 4)
{
std::cerr << "Test failed! 'offsets' should be length 4 and it is " << offsets.size() << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < 4; ++i)
{
if (offsets[i][0] != i || offsets[i][1] != i)
{
std::cerr << "Test failed! offsets[" << i << "] should be (" << i << ", " << i << ") and it is " << offsets[i]
<< std::endl;
return EXIT_FAILURE;
}
}
}
{
// Test BuildLine(Index, Index)
itk::Index<2> p0;
p0[0] = 0;
p0[1] = 0;
itk::Index<2> p1;
p1[0] = 3;
p1[1] = 3;
itk::BresenhamLine<2> line;
std::vector<itk::Index<2>> indices = line.BuildLine(p0, p1);
if (indices.size() != 4)
{
std::cerr << "Test failed! 'indices' should be length 4 and it is " << indices.size() << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < 4; ++i)
{
if (indices[i][0] != i || indices[i][1] != i)
{
std::cerr << "Test failed! indices[" << i << "] should be (" << i << ", " << i << ") and it is " << indices[i]
<< std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "Test Passed !" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: make BresenhamLine test more sensitive to numerical problems<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#include <iostream>
#include "itkBresenhamLine.h"
int
itkBresenhamLineTest(int, char *[])
{
{
// Test BuildLine(Vector, distance)
itk::Vector<float, 2> v;
v[0] = 1;
v[1] = 1;
itk::BresenhamLine<2> line;
std::vector<itk::Offset<2>> offsets = line.BuildLine(v, 4);
if (offsets.size() != 4)
{
std::cerr << "Test failed! 'offsets' should be length 4 and it is " << offsets.size() << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < 4; ++i)
{
if (offsets[i][0] != i || offsets[i][1] != i)
{
std::cerr << "Test failed! offsets[" << i << "] should be (" << i << ", " << i << ") and it is " << offsets[i]
<< std::endl;
return EXIT_FAILURE;
}
}
}
{
// Test BuildLine(Index, Index)
itk::Index<2> p0;
p0[0] = 0;
p0[1] = 0;
itk::Index<2> p1;
p1[0] = 39;
p1[1] = 39;
itk::BresenhamLine<2> line;
std::vector<itk::Index<2>> indices = line.BuildLine(p0, p1);
if (indices.size() != 40)
{
std::cerr << "Test failed! 'indices' should be length 40 and it is " << indices.size() << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < 40; ++i)
{
if (indices[i][0] != i || indices[i][1] != i)
{
std::cerr << "Test failed! indices[" << i << "] should be (" << i << ", " << i << ") and it is " << indices[i]
<< std::endl;
return EXIT_FAILURE;
}
}
}
std::cout << "Test Passed !" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <vector>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
class RemoveInfiniteLoops : public FunctionPass {
public:
static char ID;
RemoveInfiniteLoops() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
static RegisterPass<RemoveInfiniteLoops> RIL("remove-infinite-loops",
"delete patterns like LABEL: goto LABEL"
"and replace them with exit(0)");
char RemoveInfiniteLoops::ID;
void CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2);
bool RemoveInfiniteLoops::runOnFunction(Function &F) {
Module *M = F.getParent();
std::vector<BasicBlock *> to_process;
for (BasicBlock& block : F) {
// if this is a block that jumps on itself (it has the only instruction
// which is the jump)
if (block.size() == 1 && block.getSingleSuccessor() == &block)
to_process.push_back(&block);
}
if (to_process.empty())
return false;
CallInst* ext;
LLVMContext& Ctx = M->getContext();
Type *argTy = Type::getInt32Ty(Ctx);
Function *extF
= cast<Function>(M->getOrInsertFunction("exit",
Type::getVoidTy(Ctx),
argTy, nullptr));
std::vector<Value *> args = { ConstantInt::get(argTy, 0) };
for (BasicBlock *block : to_process) {
Instruction *T = block->getTerminator();
ext = CallInst::Create(extF, args);
CloneMetadata(&*(block->begin()), ext);
ext->insertBefore(T);
// replace the jump with unreachable, since exit will terminate
// the computation
new UnreachableInst(Ctx, T);
T->eraseFromParent();
}
llvm::errs() << "Removed infinite loop in " << F.getName().data() << "\n";
return true;
}
<commit_msg>remove-infinite-loops: use __VERIFIER_silent_exit instead of exit<commit_after>// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <vector>
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)
#include "llvm/IR/InstIterator.h"
#else
#include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
class RemoveInfiniteLoops : public FunctionPass {
public:
static char ID;
RemoveInfiniteLoops() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
};
static RegisterPass<RemoveInfiniteLoops> RIL("remove-infinite-loops",
"delete patterns like LABEL: goto LABEL"
"and replace them with exit(0)");
char RemoveInfiniteLoops::ID;
void CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2);
bool RemoveInfiniteLoops::runOnFunction(Function &F) {
Module *M = F.getParent();
std::vector<BasicBlock *> to_process;
for (BasicBlock& block : F) {
// if this is a block that jumps on itself (it has the only instruction
// which is the jump)
if (block.size() == 1 && block.getSingleSuccessor() == &block)
to_process.push_back(&block);
}
if (to_process.empty())
return false;
CallInst* ext;
LLVMContext& Ctx = M->getContext();
Type *argTy = Type::getInt32Ty(Ctx);
Function *extF
= cast<Function>(M->getOrInsertFunction("__VERIFIER_silent_exit",
Type::getVoidTy(Ctx),
argTy, nullptr));
std::vector<Value *> args = { ConstantInt::get(argTy, 0) };
for (BasicBlock *block : to_process) {
Instruction *T = block->getTerminator();
ext = CallInst::Create(extF, args);
CloneMetadata(&*(block->begin()), ext);
ext->insertBefore(T);
// replace the jump with unreachable, since exit will terminate
// the computation
new UnreachableInst(Ctx, T);
T->eraseFromParent();
}
llvm::errs() << "Removed infinite loop in " << F.getName().data() << "\n";
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include <sal/config.hpp>
#include <sal/logger/fwd.hpp>
#include <sal/logger/event.hpp>
#include <sal/logger/sink.hpp>
#include <sal/assert.hpp>
#include <sal/file.hpp>
#include <sal/spinlock.hpp>
#include <mutex>
#include <string>
__sal_begin
namespace logger { namespace __bits {
template <int Tag, typename T>
struct file_sink_option_t
{
T value;
explicit file_sink_option_t (const T &value)
: value(value)
{}
};
using file_dir = file_sink_option_t<1, std::string>;
using file_max_size = file_sink_option_t<2, size_t>;
using file_buffer_size = file_sink_option_t<3, size_t>;
using file_utc_time = file_sink_option_t<4, bool>;
class file_sink_t final
: public sink_t
{
public:
template <typename... Options>
file_sink_t (const std::string &label, Options &&...options)
: suffix_('_' + label + ".log")
{
bool unused[] = { set_option(std::forward<Options>(options))..., false };
(void)unused;
auto file = make_file();
swap_file(file);
}
virtual ~file_sink_t ()
{
flush();
}
private:
using mutex_t = spinlock_t;
using lock_t = std::lock_guard<mutex_t>;
mutex_t mutex_{};
file_t file_{};
const std::string suffix_;
std::string dir_ = ".";
std::unique_ptr<std::string> buffer_{};
bool utc_time_ = true;
// if max_size_ == 0, size_ has undefined value
size_t max_size_ = 0, size_ = 0;
file_t make_file ();
void sink_event_init (event_t &event, const std::string &channel_name)
final override
{
event.time = utc_time_ ? now() : sink_t::local_now();
sink_t::init(event, channel_name);
}
void sink_event_write (event_t &event) final override;
bool set_option (file_dir &&option)
{
dir_ = std::move(option.value);
return false;
}
bool set_option (file_max_size &&option)
{
max_size_ = option.value;
return false;
}
bool set_option (file_utc_time &&option)
{
utc_time_ = option.value;
return false;
}
bool set_option (file_buffer_size &&option)
{
sal_assert(buffer_ == nullptr);
if (option.value)
{
constexpr auto min_buffer_size = 2 * event_t::max_message_size;
if (option.value < min_buffer_size)
{
option.value = min_buffer_size;
}
buffer_ = std::make_unique<std::string>();
buffer_->reserve(option.value);
}
return false;
}
void flush ()
{
if (buffer_ && buffer_->size())
{
file_.write(buffer_->data(), buffer_->size());
buffer_->clear();
}
}
void swap_file (file_t &file)
{
swap(file_, file);
}
void rotate ()
{
if (auto file = make_file())
{
flush();
swap_file(file);
}
}
};
}} // namespace logger::__bits
__sal_end
<commit_msg>logger: ignore exceptions in file_sink dtor<commit_after>#pragma once
#include <sal/config.hpp>
#include <sal/logger/fwd.hpp>
#include <sal/logger/event.hpp>
#include <sal/logger/sink.hpp>
#include <sal/assert.hpp>
#include <sal/file.hpp>
#include <sal/spinlock.hpp>
#include <mutex>
#include <string>
__sal_begin
namespace logger { namespace __bits {
template <int Tag, typename T>
struct file_sink_option_t
{
T value;
explicit file_sink_option_t (const T &value)
: value(value)
{}
};
using file_dir = file_sink_option_t<1, std::string>;
using file_max_size = file_sink_option_t<2, size_t>;
using file_buffer_size = file_sink_option_t<3, size_t>;
using file_utc_time = file_sink_option_t<4, bool>;
class file_sink_t final
: public sink_t
{
public:
template <typename... Options>
file_sink_t (const std::string &label, Options &&...options)
: suffix_('_' + label + ".log")
{
bool unused[] = { set_option(std::forward<Options>(options))..., false };
(void)unused;
auto file = make_file();
swap_file(file);
}
virtual ~file_sink_t () noexcept
{
try
{
flush();
}
catch (...)
{
// silently ignore, nothing to do
}
}
private:
using mutex_t = spinlock_t;
using lock_t = std::lock_guard<mutex_t>;
mutex_t mutex_{};
file_t file_{};
const std::string suffix_;
std::string dir_ = ".";
std::unique_ptr<std::string> buffer_{};
bool utc_time_ = true;
// if max_size_ == 0, size_ has undefined value
size_t max_size_ = 0, size_ = 0;
file_t make_file ();
void sink_event_init (event_t &event, const std::string &channel_name)
final override
{
event.time = utc_time_ ? now() : sink_t::local_now();
sink_t::init(event, channel_name);
}
void sink_event_write (event_t &event) final override;
bool set_option (file_dir &&option)
{
dir_ = std::move(option.value);
return false;
}
bool set_option (file_max_size &&option)
{
max_size_ = option.value;
return false;
}
bool set_option (file_utc_time &&option)
{
utc_time_ = option.value;
return false;
}
bool set_option (file_buffer_size &&option)
{
sal_assert(buffer_ == nullptr);
if (option.value)
{
constexpr auto min_buffer_size = 2 * event_t::max_message_size;
if (option.value < min_buffer_size)
{
option.value = min_buffer_size;
}
buffer_ = std::make_unique<std::string>();
buffer_->reserve(option.value);
}
return false;
}
void flush ()
{
if (buffer_ && buffer_->size())
{
file_.write(buffer_->data(), buffer_->size());
buffer_->clear();
}
}
void swap_file (file_t &file)
{
swap(file_, file);
}
void rotate ()
{
if (auto file = make_file())
{
flush();
swap_file(file);
}
}
};
}} // namespace logger::__bits
__sal_end
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageLuminance.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageCache.h"
#include "vtkImageLuminance.h"
//----------------------------------------------------------------------------
// Description:
// This method tells the superclass that the first axis will collapse.
void vtkImageLuminance::ExecuteImageInformation()
{
this->Output->SetNumberOfScalarComponents(1);
}
//----------------------------------------------------------------------------
// Description:
// This execute method handles boundaries.
// it handles boundaries. Pixels are just replicated to get values
// out of extent.
template <class T>
static void vtkImageLuminanceExecute(vtkImageLuminance *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int idxX, idxY, idxZ;
int maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
float luminance;
// find the region to loop over
maxX = outExt[1] - outExt[0];
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// Loop through ouput pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
for (idxY = 0; idxY <= maxY; idxY++)
{
if (!id)
{
if (!(count%target)) self->UpdateProgress(count/(50.0*target));
count++;
}
for (idxX = 0; idxX <= maxX; idxX++)
{
luminance = 0.30 * *inPtr++;
luminance += 0.59 * *inPtr++;
luminance += 0.11 * *inPtr++;
*outPtr = (T)(luminance);
outPtr++;
}
outPtr += outIncY;
inPtr += inIncY;
}
outPtr += outIncZ;
inPtr += inIncZ;
}
}
//----------------------------------------------------------------------------
// Description:
// This method contains a switch statement that calls the correct
// templated function for the input data type. The output data
// must match input type. This method does handle boundary conditions.
void vtkImageLuminance::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *inPtr = inData->GetScalarPointerForExtent(outExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetNumberOfScalarComponents() != 3)
{
vtkErrorMacro(<< "Execute: input must have 3 components, but has " << inData->GetNumberOfScalarComponents());
return;
}
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_FLOAT:
vtkImageLuminanceExecute(this,
inData, (float *)(inPtr),
outData, (float *)(outPtr), outExt, id);
break;
case VTK_INT:
vtkImageLuminanceExecute(this,
inData, (int *)(inPtr),
outData, (int *)(outPtr), outExt, id);
break;
case VTK_SHORT:
vtkImageLuminanceExecute(this,
inData, (short *)(inPtr),
outData, (short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_SHORT:
vtkImageLuminanceExecute(this,
inData, (unsigned short *)(inPtr),
outData, (unsigned short *)(outPtr),
outExt, id);
break;
case VTK_UNSIGNED_CHAR:
vtkImageLuminanceExecute(this,
inData, (unsigned char *)(inPtr),
outData, (unsigned char *)(outPtr), outExt, id);
break;
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
<commit_msg>ENH: minor comment mod<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageLuminance.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageCache.h"
#include "vtkImageLuminance.h"
//----------------------------------------------------------------------------
// Description:
// This method tells the superclass that the first axis will collapse.
void vtkImageLuminance::ExecuteImageInformation()
{
this->Output->SetNumberOfScalarComponents(1);
}
//----------------------------------------------------------------------------
// Description:
// This execute method handles boundaries.
// it handles boundaries. Pixels are just replicated to get values
// out of extent.
template <class T>
static void vtkImageLuminanceExecute(vtkImageLuminance *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int idxX, idxY, idxZ;
int maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
float luminance;
// find the region to loop over
maxX = outExt[1] - outExt[0];
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// Loop through ouput pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
for (idxY = 0; idxY <= maxY; idxY++)
{
if (!id)
{
if (!(count%target)) self->UpdateProgress(count/(50.0*target));
count++;
}
for (idxX = 0; idxX <= maxX; idxX++)
{
luminance = 0.30 * *inPtr++;
luminance += 0.59 * *inPtr++;
luminance += 0.11 * *inPtr++;
*outPtr = (T)(luminance);
outPtr++;
}
outPtr += outIncY;
inPtr += inIncY;
}
outPtr += outIncZ;
inPtr += inIncZ;
}
}
//----------------------------------------------------------------------------
// Description:
// This method contains a switch statement that calls the correct
// templated function for the input data type. The output data
// must match input type. This method does handle boundary conditions.
void vtkImageLuminance::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *inPtr = inData->GetScalarPointerForExtent(outExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetNumberOfScalarComponents() != 3)
{
vtkErrorMacro(<< "Execute: input must have 3 components, but has " << inData->GetNumberOfScalarComponents());
return;
}
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_FLOAT:
vtkImageLuminanceExecute(this,
inData, (float *)(inPtr),
outData, (float *)(outPtr), outExt, id);
break;
case VTK_INT:
vtkImageLuminanceExecute(this,
inData, (int *)(inPtr),
outData, (int *)(outPtr), outExt, id);
break;
case VTK_SHORT:
vtkImageLuminanceExecute(this,
inData, (short *)(inPtr),
outData, (short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_SHORT:
vtkImageLuminanceExecute(this,
inData, (unsigned short *)(inPtr),
outData, (unsigned short *)(outPtr),
outExt, id);
break;
case VTK_UNSIGNED_CHAR:
vtkImageLuminanceExecute(this,
inData, (unsigned char *)(inPtr),
outData, (unsigned char *)(outPtr), outExt, id);
break;
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <gcl/mp/concepts.hpp>
namespace gcl::mp::value_traits
{
template <auto... values>
requires(std::equality_comparable_with<
decltype(std::get<0>(std::tuple{values...})),
decltype(values)>&&...) constexpr static auto equal_v = []() consteval
{
return ((values == std::get<0>(std::tuple{values...})) && ...);
}
();
// Only works for Clang yet, since 11.0.0
// template <auto first_value, std::equality_comparable_with<decltype(first_value)> auto... values>
// constexpr static auto equal_v = []() consteval
// {
// return ((values == first_value) && ...);
// }
// ();
template <auto... values>
constexpr static auto not_equal_v = not equal_v<values...>;
}
namespace gcl::mp::value_traits::tests::equal
{
static_assert(equal_v<true>);
static_assert(equal_v<true, true>);
static_assert(equal_v<true, true, true>);
static_assert(equal_v<true, true, true, true>);
static_assert(not not_equal_v<true>);
static_assert(not_equal_v<true, false>);
static_assert(not_equal_v<false, true>);
static_assert(not_equal_v<false, true, true>);
static_assert(not_equal_v<true, false, true>);
static_assert(not_equal_v<true, true, false>);
static_assert(not_equal_v<false, true, true, true>);
static_assert(not_equal_v<true, false, true, true>);
static_assert(not_equal_v<true, true, false, true>);
static_assert(not_equal_v<true, true, true, false>);
}<commit_msg>[mp::value_traits] : equal_v : fix contract for equal_v<><commit_after>#pragma once
#include <gcl/mp/concepts.hpp>
namespace gcl::mp::value_traits
{
template <auto... values>
requires(std::equality_comparable_with<
decltype(std::get<0>(std::tuple{values...})),
decltype(values)>&&...) constexpr static auto equal_v = []() consteval
{
return ((values == std::get<0>(std::tuple{values...})) && ...);
}
();
// Only works for Clang yet, since 11.0.0
// template <auto first_value = int{}, std::equality_comparable_with<decltype(first_value)> auto... values>
// constexpr static auto equal_v = []() consteval
// {
// return ((values == first_value) && ...);
// }
// ();
template <auto... values>
constexpr static auto not_equal_v = not equal_v<values...>;
}
namespace gcl::mp::value_traits::tests::equal
{
static_assert(equal_v<>);
static_assert(equal_v<true>);
static_assert(equal_v<true, true>);
static_assert(equal_v<true, true, true>);
static_assert(equal_v<true, true, true, true>);
static_assert(not not_equal_v<true>);
static_assert(not_equal_v<true, false>);
static_assert(not_equal_v<false, true>);
static_assert(not_equal_v<false, true, true>);
static_assert(not_equal_v<true, false, true>);
static_assert(not_equal_v<true, true, false>);
static_assert(not_equal_v<false, true, true, true>);
static_assert(not_equal_v<true, false, true, true>);
static_assert(not_equal_v<true, true, false, true>);
static_assert(not_equal_v<true, true, true, false>);
}<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Siddharth Srivastava <akssps011@gmail.com>
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RoutingPlugin.h"
#include "ui_RoutingPlugin.h"
#include "GeoDataCoordinates.h"
#include "GeoPainter.h"
#include "MarbleDataFacade.h"
#include "MarbleGraphicsGridLayout.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "MarbleLocale.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "PositionProviderPlugin.h"
#include "routing/RoutingManager.h"
#include "routing/RoutingModel.h"
#include "routing/RouteRequest.h"
#include "ViewportParams.h"
#include "WidgetGraphicsItem.h"
#include <QtCore/QRect>
#include <QtGui/QWidget>
#include <QtGui/QToolButton>
#include <QtGui/QFont>
#include <QtGui/QActionGroup>
#include <QtGui/QPixmap>
#include <QtGui/QPlastiqueStyle>
#include <QtCore/QDebug>
namespace Marble
{
namespace
{
int const thresholdTime = 3; // in minutes
int const thresholdDistance = 1000; // in meter
}
class RoutingPluginPrivate
{
public:
MarbleWidget* m_marbleWidget;
WidgetGraphicsItem* m_widgetItem;
RoutingModel* m_routingModel;
Ui::RoutingPlugin m_widget;
bool m_nearNextInstruction;
bool m_guidanceModeEnabled;
RoutingPluginPrivate( RoutingPlugin* parent );
void updateZoomButtons( int zoomValue );
void updateZoomButtons();
void updateGuidanceModeButton();
void updateInstructionLabel( int fontSize, qreal remainingDistance );
void forceRepaint();
void updateButtonVisibility();
void reverseRoute();
void toggleGuidanceMode( bool enabled );
void updateDestinationInformation( qint32, qreal );
void updateGpsButton( PositionProviderPlugin *activePlugin );
void togglePositionTracking( bool enabled );
QString richText( const QString &source, int fontSize ) const;
QString fuzzyDistance( qreal distanceMeter ) const;
private:
RoutingPlugin* m_parent;
};
RoutingPluginPrivate::RoutingPluginPrivate( RoutingPlugin *parent ) :
m_marbleWidget( 0 ),
m_widgetItem( 0 ),
m_routingModel( 0 ),
m_nearNextInstruction( false ),
m_guidanceModeEnabled( false ),
m_parent( parent )
{
// nothing to do
}
QString RoutingPluginPrivate::richText( const QString &source, int size ) const
{
QString const fontSize = size > 0 ? "+" + fontSize : QString::number( size );
return QString( "<font size=\"%1\" color=\"black\">%2</font>" ).arg( fontSize ).arg( source );
}
QString RoutingPluginPrivate::fuzzyDistance( qreal length ) const
{
int precision = 0;
QString distanceUnit = "m";
if ( MarbleGlobal::getInstance()->locale()->distanceUnit() == Marble::MilesFeet ) {
precision = 1;
distanceUnit = "mi";
length *= METER2KM;
length *= KM2MI;
} else {
if ( length >= 1000 ) {
length /= 1000;
distanceUnit = "km";
precision = 1;
} else if ( length >= 200 ) {
length = 50 * qRound( length / 50 );
} else if ( length >= 100 ) {
length = 25 * qRound( length / 25 );
} else {
length = 10 * qRound( length / 10 );
}
}
return QString( "%1 %2" ).arg( length, 0, 'f', precision ).arg( distanceUnit );
}
void RoutingPluginPrivate::updateZoomButtons( int zoomValue )
{
int const minZoom = m_marbleWidget ? m_marbleWidget->minimumZoom() : 900;
int const maxZoom = m_marbleWidget ? m_marbleWidget->maximumZoom() : 2400;
m_widget.zoomInButton->setEnabled( zoomValue < maxZoom );
m_widget.zoomOutButton->setEnabled( zoomValue > minZoom );
forceRepaint();
}
void RoutingPluginPrivate::updateGuidanceModeButton()
{
bool const hasRoute = m_routingModel->rowCount() > 0;
m_widget.routingButton->setEnabled( hasRoute );
}
void RoutingPluginPrivate::forceRepaint()
{
if ( m_marbleWidget ) {
// Trigger a repaint of the float item. Otherwise button state updates are delayed
m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, false );
m_parent->update();
m_marbleWidget->repaint();
bool const mapCoversViewport = m_marbleWidget->viewport()->mapCoversViewport();
m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, mapCoversViewport );
}
}
void RoutingPluginPrivate::updateButtonVisibility()
{
bool const show = m_guidanceModeEnabled;
bool const near = show && m_nearNextInstruction;
m_widget.progressBar->setVisible( near );
m_widget.instructionIconLabel->setVisible( show );
m_widget.instructionLabel->setVisible( show );
// m_widget.followingInstructionIconLabel->setVisible( show );
// Disabling the next instruction turn icon for now, it seems to confuse first time users.
m_widget.followingInstructionIconLabel->setVisible( false );
m_widget.destinationDistanceLabel->setVisible( show );
m_widget.gpsButton->setVisible( !show );
m_widget.zoomOutButton->setVisible( !show );
m_widget.zoomInButton->setVisible( !show );
m_widgetItem->widget()->updateGeometry();
QSize const size = m_widgetItem->widget()->sizeHint();
m_widgetItem->widget()->resize( size );
m_widgetItem->setContentSize( size );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
qreal const pluginWidth = size.width();
int x = -10;
if ( m_guidanceModeEnabled ) {
int const parentWidth = m_marbleWidget->width();
x = qRound( ( parentWidth - pluginWidth ) / 2.0 );
}
m_parent->setPosition( QPointF( x, m_parent->position().y() ) );
}
}
void RoutingPluginPrivate::updateZoomButtons()
{
if ( m_marbleWidget ) {
updateZoomButtons( m_marbleWidget->zoom() );
}
}
void RoutingPluginPrivate::toggleGuidanceMode( bool enabled )
{
if( !m_marbleWidget || m_guidanceModeEnabled == enabled ) {
return;
}
m_guidanceModeEnabled = enabled;
updateButtonVisibility();
if( enabled ) {
QObject::connect( m_routingModel, SIGNAL( nextInstruction( qint32, qreal ) ),
m_parent, SLOT( updateDestinationInformation( qint32, qreal ) ) );
} else {
QObject::disconnect( m_routingModel, SIGNAL( nextInstruction( qint32, qreal ) ),
m_parent, SLOT( updateDestinationInformation( qint32, qreal ) ) );
}
if ( enabled ) {
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
int fontSize = smallScreen ? -1 : 1;
QString const text = QObject::tr( "Determining current location, please wait..." );
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( text ) );
}
if ( enabled ) {
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
if ( request && request->size() > 0 ) {
GeoDataCoordinates source = request->source();
if ( source.longitude() != 0.0 || source.latitude() != 0.0 ) {
GeoDataLookAt view;
view.setCoordinates( source );
view.setRange( 750 );
m_marbleWidget->flyTo( view );
}
}
}
m_marbleWidget->model()->routingManager()->setGuidanceModeEnabled( enabled );
forceRepaint();
}
void RoutingPluginPrivate::updateDestinationInformation( qint32 remainingTime, qreal remainingDistance )
{
Q_UNUSED( remainingTime );
if ( m_routingModel->rowCount() != 0 ) {
qreal distanceLeft = m_routingModel->nextInstructionDistance();
m_nearNextInstruction = distanceLeft < thresholdDistance;
int fontSize = 1;
if ( MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) {
fontSize = m_nearNextInstruction ? 1 : -1;
}
QString pixmapHtml = "<img src=\":/icons/flag.png\" /><br />";
m_widget.destinationDistanceLabel->setText( pixmapHtml + richText( fuzzyDistance( remainingDistance ), -1 ) );
m_widget.instructionIconLabel->setEnabled( m_nearNextInstruction );
m_widget.progressBar->setMaximum( thresholdDistance );
m_widget.progressBar->setValue( qRound( distanceLeft ) );
updateButtonVisibility();
QPixmap pixmap = m_routingModel->nextInstructionPixmap();
if ( !pixmap.isNull() ) {
m_widget.instructionIconLabel->setPixmap( pixmap.scaled( 64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) );
}
m_widget.followingInstructionIconLabel->setPixmap( m_routingModel->followingInstructionPixmap() );
updateInstructionLabel( fontSize, remainingDistance );
}
}
void RoutingPluginPrivate::updateInstructionLabel( int fontSize, qreal remainingDistance )
{
if( m_routingModel->remainingTime() < thresholdTime && !m_routingModel->instructionText().isEmpty() ) {
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( m_routingModel->instructionText() ) );
} else {
qreal instructionDistance = m_routingModel->nextInstructionDistance();
QString indicatorText = m_routingModel->instructionText().isEmpty() ?
richText( "Destination reached in %1 %2", fontSize ) :
richText( "Next turn in %1 %2", fontSize );
if( remainingDistance ) {
if( instructionDistance < 1000 ) {
m_widget.instructionLabel->setText( indicatorText.arg( int( instructionDistance ) ).arg( "meters" ) );
} else {
m_widget.instructionLabel->setText( indicatorText.arg( instructionDistance * METER2KM, 0, 'f', 1 ).arg( " km " ) );
}
} else {
QString content = "Arrived at destination. <a href=\"#reverse\">Calculate the way back.</a>";
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( content ) );
}
}
}
void RoutingPluginPrivate::updateGpsButton( PositionProviderPlugin *activePlugin )
{
m_widget.gpsButton->setChecked( activePlugin != 0 );
forceRepaint();
}
void RoutingPluginPrivate::togglePositionTracking( bool enabled )
{
PositionProviderPlugin* plugin = 0;
if ( enabled ) {
PluginManager* pluginManager = m_marbleWidget->model()->pluginManager();
QList<PositionProviderPlugin*> plugins = pluginManager->createPositionProviderPlugins();
if ( plugins.size() > 0 ) {
plugin = plugins.takeFirst();
}
qDeleteAll( plugins );
}
m_parent->dataFacade()->positionTracking()->setPositionProviderPlugin( plugin );
}
void RoutingPluginPrivate::reverseRoute()
{
if ( m_marbleWidget ) {
m_marbleWidget->model()->routingManager()->reverseRoute();
}
}
RoutingPlugin::RoutingPlugin( const QPointF &position ) :
AbstractFloatItem( position ),
d( new RoutingPluginPrivate( this ) )
{
setEnabled( true );
//plugin is visible by default on small screen devices
setVisible( MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen );
setPadding( 0 );
}
RoutingPlugin::~RoutingPlugin()
{
delete d;
}
QStringList RoutingPlugin::backendTypes() const
{
return QStringList( "routing" );
}
QString RoutingPlugin::name() const
{
return tr( "Routing" );
}
QString RoutingPlugin::guiString() const
{
return tr( "&Routing" );
}
QString RoutingPlugin::nameId() const
{
return QString( "routing" );
}
QString RoutingPlugin::description() const
{
return tr( "Routing information and navigation controls" );
}
QIcon RoutingPlugin::icon() const
{
return QIcon();
}
void RoutingPlugin::initialize()
{
QWidget *widget = new QWidget;
d->m_widget.setupUi( widget );
PositionProviderPlugin* activePlugin = dataFacade()->positionTracking()->positionProviderPlugin();
d->m_widget.gpsButton->setChecked( activePlugin != 0 );
d->m_widget.routingButton->setEnabled( false );
connect( d->m_widget.instructionLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( reverseRoute() ) );
d->m_widgetItem = new WidgetGraphicsItem( this );
d->m_widgetItem->setWidget( widget );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
/** @todo: The maemo styling of the progressbar adds a black background and some frame
* which are even painted when no background painting is requested like WidgetItem does.
* This looks really bad on a float item. Using a different style here, but that is only
* a workaround.
*/
d->m_widget.progressBar->setStyle( new QPlastiqueStyle );
}
MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
layout->addItem( d->m_widgetItem, 0, 0 );
setLayout( layout );
d->updateButtonVisibility();
}
bool RoutingPlugin::isInitialized() const
{
return d->m_widgetItem;
}
bool RoutingPlugin::eventFilter( QObject *object, QEvent *e )
{
if ( !enabled() || !visible() ) {
return AbstractFloatItem::eventFilter( object, e );
}
MarbleWidget *widget = dynamic_cast<MarbleWidget*> ( object );
if ( widget && !d->m_marbleWidget ) {
d->m_marbleWidget = widget;
d->m_routingModel = d->m_marbleWidget->model()->routingManager()->routingModel();
connect( d->m_marbleWidget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateGpsButton( PositionProviderPlugin* ) ) );
connect( d->m_widget.routingButton, SIGNAL( clicked( bool ) ),
this, SLOT( toggleGuidanceMode( bool ) ) );
connect( d->m_widget.gpsButton, SIGNAL( clicked( bool ) ),
this, SLOT( togglePositionTracking( bool ) ) );
connect( d->m_widget.zoomInButton, SIGNAL( clicked() ),
d->m_marbleWidget, SLOT( zoomIn() ) );
connect( d->m_widget.zoomOutButton, SIGNAL( clicked() ),
d->m_marbleWidget, SLOT( zoomOut() ) );
connect( d->m_marbleWidget, SIGNAL( themeChanged( QString ) ),
this, SLOT( updateZoomButtons() ) );
connect( d->m_marbleWidget, SIGNAL( zoomChanged( int ) ),
this, SLOT( updateZoomButtons( int ) ) );
connect( d->m_routingModel, SIGNAL( currentRouteChanged() ),
this, SLOT( updateGuidanceModeButton() ) );
d->updateGuidanceModeButton();
}
return AbstractFloatItem::eventFilter( object, e );
}
}
Q_EXPORT_PLUGIN2( RoutingPlugin, Marble::RoutingPlugin )
#include "RoutingPlugin.moc"
<commit_msg>Performance optimizations: - Avoid dynamic_casts in eventFilter which is called quite often - Only repaint marble widget when the button check state has really changed. zoomChanged() is called frequently. - Activate item caching via pixmaps. This increases rendering speed nearly by a factor of 4 on my system, painting the float item without caching takes around 55 ms, less than 1 ms with.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Siddharth Srivastava <akssps011@gmail.com>
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RoutingPlugin.h"
#include "ui_RoutingPlugin.h"
#include "GeoDataCoordinates.h"
#include "GeoPainter.h"
#include "MarbleDataFacade.h"
#include "MarbleGraphicsGridLayout.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "MarbleLocale.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "PositionProviderPlugin.h"
#include "routing/RoutingManager.h"
#include "routing/RoutingModel.h"
#include "routing/RouteRequest.h"
#include "ViewportParams.h"
#include "WidgetGraphicsItem.h"
#include <QtCore/QRect>
#include <QtGui/QWidget>
#include <QtGui/QToolButton>
#include <QtGui/QFont>
#include <QtGui/QActionGroup>
#include <QtGui/QPixmap>
#include <QtGui/QPlastiqueStyle>
namespace Marble
{
namespace
{
int const thresholdTime = 3; // in minutes
int const thresholdDistance = 1000; // in meter
}
class RoutingPluginPrivate
{
public:
MarbleWidget* m_marbleWidget;
WidgetGraphicsItem* m_widgetItem;
RoutingModel* m_routingModel;
Ui::RoutingPlugin m_widget;
bool m_nearNextInstruction;
bool m_guidanceModeEnabled;
RoutingPluginPrivate( RoutingPlugin* parent );
void updateZoomButtons( int zoomValue );
void updateZoomButtons();
void updateGuidanceModeButton();
void updateInstructionLabel( int fontSize, qreal remainingDistance );
void forceRepaint();
void updateButtonVisibility();
void reverseRoute();
void toggleGuidanceMode( bool enabled );
void updateDestinationInformation( qint32, qreal );
void updateGpsButton( PositionProviderPlugin *activePlugin );
void togglePositionTracking( bool enabled );
QString richText( const QString &source, int fontSize ) const;
QString fuzzyDistance( qreal distanceMeter ) const;
private:
RoutingPlugin* m_parent;
};
RoutingPluginPrivate::RoutingPluginPrivate( RoutingPlugin *parent ) :
m_marbleWidget( 0 ),
m_widgetItem( 0 ),
m_routingModel( 0 ),
m_nearNextInstruction( false ),
m_guidanceModeEnabled( false ),
m_parent( parent )
{
// nothing to do
}
QString RoutingPluginPrivate::richText( const QString &source, int size ) const
{
QString const fontSize = size > 0 ? "+" + fontSize : QString::number( size );
return QString( "<font size=\"%1\" color=\"black\">%2</font>" ).arg( fontSize ).arg( source );
}
QString RoutingPluginPrivate::fuzzyDistance( qreal length ) const
{
int precision = 0;
QString distanceUnit = "m";
if ( MarbleGlobal::getInstance()->locale()->distanceUnit() == Marble::MilesFeet ) {
precision = 1;
distanceUnit = "mi";
length *= METER2KM;
length *= KM2MI;
} else {
if ( length >= 1000 ) {
length /= 1000;
distanceUnit = "km";
precision = 1;
} else if ( length >= 200 ) {
length = 50 * qRound( length / 50 );
} else if ( length >= 100 ) {
length = 25 * qRound( length / 25 );
} else {
length = 10 * qRound( length / 10 );
}
}
return QString( "%1 %2" ).arg( length, 0, 'f', precision ).arg( distanceUnit );
}
void RoutingPluginPrivate::updateZoomButtons( int zoomValue )
{
int const minZoom = m_marbleWidget ? m_marbleWidget->minimumZoom() : 900;
int const maxZoom = m_marbleWidget ? m_marbleWidget->maximumZoom() : 2400;
bool const zoomInEnabled = zoomValue < maxZoom;
bool const zoomOutEnabled = zoomValue > minZoom;
if ( ( zoomInEnabled != m_widget.zoomInButton->isEnabled() ) ||
( zoomOutEnabled != m_widget.zoomOutButton->isEnabled() ) ) {
m_widget.zoomInButton->setEnabled( zoomInEnabled );
m_widget.zoomOutButton->setEnabled( zoomOutEnabled );
forceRepaint();
}
}
void RoutingPluginPrivate::updateGuidanceModeButton()
{
bool const hasRoute = m_routingModel->rowCount() > 0;
m_widget.routingButton->setEnabled( hasRoute );
}
void RoutingPluginPrivate::forceRepaint()
{
m_widgetItem->update();
if ( m_marbleWidget ) {
// Trigger a repaint of the float item. Otherwise button state updates are delayed
m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, false );
m_parent->update();
m_marbleWidget->repaint();
bool const mapCoversViewport = m_marbleWidget->viewport()->mapCoversViewport();
m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, mapCoversViewport );
}
}
void RoutingPluginPrivate::updateButtonVisibility()
{
bool const show = m_guidanceModeEnabled;
bool const near = show && m_nearNextInstruction;
m_widget.progressBar->setVisible( near );
m_widget.instructionIconLabel->setVisible( show );
m_widget.instructionLabel->setVisible( show );
// m_widget.followingInstructionIconLabel->setVisible( show );
// Disabling the next instruction turn icon for now, it seems to confuse first time users.
m_widget.followingInstructionIconLabel->setVisible( false );
m_widget.destinationDistanceLabel->setVisible( show );
m_widget.gpsButton->setVisible( !show );
m_widget.zoomOutButton->setVisible( !show );
m_widget.zoomInButton->setVisible( !show );
m_widgetItem->widget()->updateGeometry();
QSize const size = m_widgetItem->widget()->sizeHint();
m_widgetItem->widget()->resize( size );
m_widgetItem->setContentSize( size );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
qreal const pluginWidth = size.width();
int x = -10;
if ( m_guidanceModeEnabled ) {
int const parentWidth = m_marbleWidget->width();
x = qRound( ( parentWidth - pluginWidth ) / 2.0 );
}
m_parent->setPosition( QPointF( x, m_parent->position().y() ) );
}
}
void RoutingPluginPrivate::updateZoomButtons()
{
if ( m_marbleWidget ) {
updateZoomButtons( m_marbleWidget->zoom() );
}
}
void RoutingPluginPrivate::toggleGuidanceMode( bool enabled )
{
if( !m_marbleWidget || m_guidanceModeEnabled == enabled ) {
return;
}
m_guidanceModeEnabled = enabled;
updateButtonVisibility();
if( enabled ) {
QObject::connect( m_routingModel, SIGNAL( nextInstruction( qint32, qreal ) ),
m_parent, SLOT( updateDestinationInformation( qint32, qreal ) ) );
} else {
QObject::disconnect( m_routingModel, SIGNAL( nextInstruction( qint32, qreal ) ),
m_parent, SLOT( updateDestinationInformation( qint32, qreal ) ) );
}
if ( enabled ) {
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
int fontSize = smallScreen ? -1 : 1;
QString const text = QObject::tr( "Determining current location, please wait..." );
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( text ) );
}
if ( enabled ) {
RouteRequest* request = m_marbleWidget->model()->routingManager()->routeRequest();
if ( request && request->size() > 0 ) {
GeoDataCoordinates source = request->source();
if ( source.longitude() != 0.0 || source.latitude() != 0.0 ) {
GeoDataLookAt view;
view.setCoordinates( source );
view.setRange( 750 );
m_marbleWidget->flyTo( view );
}
}
}
m_marbleWidget->model()->routingManager()->setGuidanceModeEnabled( enabled );
forceRepaint();
}
void RoutingPluginPrivate::updateDestinationInformation( qint32 remainingTime, qreal remainingDistance )
{
Q_UNUSED( remainingTime );
if ( m_routingModel->rowCount() != 0 ) {
qreal distanceLeft = m_routingModel->nextInstructionDistance();
m_nearNextInstruction = distanceLeft < thresholdDistance;
int fontSize = 1;
if ( MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) {
fontSize = m_nearNextInstruction ? 1 : -1;
}
QString pixmapHtml = "<img src=\":/icons/flag.png\" /><br />";
m_widget.destinationDistanceLabel->setText( pixmapHtml + richText( fuzzyDistance( remainingDistance ), -1 ) );
m_widget.instructionIconLabel->setEnabled( m_nearNextInstruction );
m_widget.progressBar->setMaximum( thresholdDistance );
m_widget.progressBar->setValue( qRound( distanceLeft ) );
updateButtonVisibility();
QPixmap pixmap = m_routingModel->nextInstructionPixmap();
if ( !pixmap.isNull() ) {
m_widget.instructionIconLabel->setPixmap( pixmap.scaled( 64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) );
}
m_widget.followingInstructionIconLabel->setPixmap( m_routingModel->followingInstructionPixmap() );
updateInstructionLabel( fontSize, remainingDistance );
}
}
void RoutingPluginPrivate::updateInstructionLabel( int fontSize, qreal remainingDistance )
{
if( m_routingModel->remainingTime() < thresholdTime && !m_routingModel->instructionText().isEmpty() ) {
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( m_routingModel->instructionText() ) );
} else {
qreal instructionDistance = m_routingModel->nextInstructionDistance();
QString indicatorText = m_routingModel->instructionText().isEmpty() ?
richText( "Destination reached in %1 %2", fontSize ) :
richText( "Next turn in %1 %2", fontSize );
if( remainingDistance ) {
if( instructionDistance < 1000 ) {
m_widget.instructionLabel->setText( indicatorText.arg( int( instructionDistance ) ).arg( "meters" ) );
} else {
m_widget.instructionLabel->setText( indicatorText.arg( instructionDistance * METER2KM, 0, 'f', 1 ).arg( " km " ) );
}
} else {
QString content = "Arrived at destination. <a href=\"#reverse\">Calculate the way back.</a>";
m_widget.instructionLabel->setText( richText( "%1", fontSize ).arg( content ) );
}
}
}
void RoutingPluginPrivate::updateGpsButton( PositionProviderPlugin *activePlugin )
{
m_widget.gpsButton->setChecked( activePlugin != 0 );
forceRepaint();
}
void RoutingPluginPrivate::togglePositionTracking( bool enabled )
{
PositionProviderPlugin* plugin = 0;
if ( enabled ) {
PluginManager* pluginManager = m_marbleWidget->model()->pluginManager();
QList<PositionProviderPlugin*> plugins = pluginManager->createPositionProviderPlugins();
if ( plugins.size() > 0 ) {
plugin = plugins.takeFirst();
}
qDeleteAll( plugins );
}
m_parent->dataFacade()->positionTracking()->setPositionProviderPlugin( plugin );
}
void RoutingPluginPrivate::reverseRoute()
{
if ( m_marbleWidget ) {
m_marbleWidget->model()->routingManager()->reverseRoute();
}
}
RoutingPlugin::RoutingPlugin( const QPointF &position ) :
AbstractFloatItem( position ),
d( new RoutingPluginPrivate( this ) )
{
setEnabled( true );
//plugin is visible by default on small screen devices
setVisible( MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen );
setPadding( 0 );
}
RoutingPlugin::~RoutingPlugin()
{
delete d;
}
QStringList RoutingPlugin::backendTypes() const
{
return QStringList( "routing" );
}
QString RoutingPlugin::name() const
{
return tr( "Routing" );
}
QString RoutingPlugin::guiString() const
{
return tr( "&Routing" );
}
QString RoutingPlugin::nameId() const
{
return QString( "routing" );
}
QString RoutingPlugin::description() const
{
return tr( "Routing information and navigation controls" );
}
QIcon RoutingPlugin::icon() const
{
return QIcon();
}
void RoutingPlugin::initialize()
{
QWidget *widget = new QWidget;
d->m_widget.setupUi( widget );
PositionProviderPlugin* activePlugin = dataFacade()->positionTracking()->positionProviderPlugin();
d->m_widget.gpsButton->setChecked( activePlugin != 0 );
d->m_widget.routingButton->setEnabled( false );
connect( d->m_widget.instructionLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( reverseRoute() ) );
d->m_widgetItem = new WidgetGraphicsItem( this );
d->m_widgetItem->setWidget( widget );
d->m_widgetItem->setCacheMode( MarbleGraphicsItem::DeviceCoordinateCache );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
/** @todo: The maemo styling of the progressbar adds a black background and some frame
* which are even painted when no background painting is requested like WidgetItem does.
* This looks really bad on a float item. Using a different style here, but that is only
* a workaround.
*/
d->m_widget.progressBar->setStyle( new QPlastiqueStyle );
}
MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
layout->addItem( d->m_widgetItem, 0, 0 );
setLayout( layout );
d->updateButtonVisibility();
}
bool RoutingPlugin::isInitialized() const
{
return d->m_widgetItem;
}
bool RoutingPlugin::eventFilter( QObject *object, QEvent *e )
{
if ( d->m_marbleWidget || !enabled() || !visible() ) {
return AbstractFloatItem::eventFilter( object, e );
}
MarbleWidget *widget = dynamic_cast<MarbleWidget*> ( object );
if ( widget && !d->m_marbleWidget ) {
d->m_marbleWidget = widget;
d->m_routingModel = d->m_marbleWidget->model()->routingManager()->routingModel();
connect( d->m_marbleWidget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateGpsButton( PositionProviderPlugin* ) ) );
connect( d->m_widget.routingButton, SIGNAL( clicked( bool ) ),
this, SLOT( toggleGuidanceMode( bool ) ) );
connect( d->m_widget.gpsButton, SIGNAL( clicked( bool ) ),
this, SLOT( togglePositionTracking( bool ) ) );
connect( d->m_widget.zoomInButton, SIGNAL( clicked() ),
d->m_marbleWidget, SLOT( zoomIn() ) );
connect( d->m_widget.zoomOutButton, SIGNAL( clicked() ),
d->m_marbleWidget, SLOT( zoomOut() ) );
connect( d->m_marbleWidget, SIGNAL( themeChanged( QString ) ),
this, SLOT( updateZoomButtons() ) );
connect( d->m_marbleWidget, SIGNAL( zoomChanged( int ) ),
this, SLOT( updateZoomButtons( int ) ) );
connect( d->m_routingModel, SIGNAL( currentRouteChanged() ),
this, SLOT( updateGuidanceModeButton() ) );
d->updateGuidanceModeButton();
}
return AbstractFloatItem::eventFilter( object, e );
}
}
Q_EXPORT_PLUGIN2( RoutingPlugin, Marble::RoutingPlugin )
#include "RoutingPlugin.moc"
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.