hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28ee2956cf84477dcdc0600a1de4349281de5a6e | 7,636 | cpp | C++ | src/caffe/data_reader.cpp | jwyang/JULE-Caffe | 797292223e9e9021e31730c87b9abc86f08fce0c | [
"MIT"
] | 22 | 2016-11-14T18:43:50.000Z | 2020-03-05T05:51:19.000Z | src/caffe/data_reader.cpp | jwyang/JULE-Caffe | 797292223e9e9021e31730c87b9abc86f08fce0c | [
"MIT"
] | 2 | 2017-04-20T03:05:41.000Z | 2019-08-25T14:07:33.000Z | src/caffe/data_reader.cpp | jwyang/JULE-Caffe | 797292223e9e9021e31730c87b9abc86f08fce0c | [
"MIT"
] | 6 | 2016-11-22T19:37:45.000Z | 2020-02-18T13:52:22.000Z | #include <boost/thread.hpp>
#include <map>
#include <string>
#include <vector>
#include <random>
#include "caffe/common.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/data_reader.hpp"
#include "caffe/proto/caffe.pb.h"
#define use_bmat
namespace caffe {
using boost::weak_ptr;
map<const string, weak_ptr<DataReader::Body> > DataReader::bodies_;
static boost::mutex bodies_mutex_;
DataReader::DataReader(const LayerParameter& param)
: queue_pair_(new QueuePair( //
param.data_param().prefetch() * param.data_param().batch_size())) {
// Get or create a body
boost::mutex::scoped_lock lock(bodies_mutex_);
string key = source_key(param);
weak_ptr<Body>& weak = bodies_[key];
body_ = weak.lock();
if (!body_) {
body_.reset(new Body(param));
bodies_[key] = weak_ptr<Body>(body_);
}
body_->new_queue_pairs_.push(queue_pair_);
}
DataReader::~DataReader() {
string key = source_key(body_->param_);
body_.reset();
boost::mutex::scoped_lock lock(bodies_mutex_);
if (bodies_[key].expired()) {
bodies_.erase(key);
}
}
//
DataReader::QueuePair::QueuePair(int size) {
// Initialize the free queue with requested number of datums
for (int i = 0; i < size; ++i) {
free_.push(new Datum());
}
}
DataReader::QueuePair::~QueuePair() {
Datum* datum;
while (free_.try_pop(&datum)) {
delete datum;
}
while (full_.try_pop(&datum)) {
delete datum;
}
}
DataReader::Body::Body(const LayerParameter& param)
: param_(param),
new_queue_pairs_() {
StartInternalThread();
}
DataReader::Body::~Body() {
StopInternalThread();
}
void DataReader::Body::randperm(int length, std::vector<int>& indice, int groupsize, bool turnon) {
// step-1: generate length number of random float numbers
std::vector<std::pair<float, int> > num_map(length);
random_device rd; //
mt19937 gen(rd()); // generator
int length_rd = ceil(length / groupsize);
uniform_real_distribution<float> dis(0, 1);
for (int i = 0; i < length_rd; ++i) {
if (!turnon) {
num_map[i] = (std::make_pair(float(i) / length_rd, i));
}
else {
num_map[i] = (std::make_pair(dis(gen), i));
}
}
// step-2: sort generated random float numbers
std::sort(num_map.begin(), num_map.end());
// step-3: get the indice
for (int i = 0; i < length_rd; ++i) {
for (int k = 0; k < groupsize; ++k) {
if ((i * groupsize + k) >= length)
continue;
indice[i * groupsize + k] = min(num_map[i].second * groupsize + k, length - 1);
}
}
// std::random_shuffle(indice.begin(), indice.end());
}
void DataReader::Body::InternalThreadEntry() {
shared_ptr<db::DB> db(db::GetDB(param_.data_param().backend()));
db->Open(param_.data_param().source(), db::READ);
shared_ptr<db::Cursor> cursor(db->NewCursor());
vector<shared_ptr<QueuePair> > qps;
bmat bmat_parser;
//// get db size
db_size_ = 0;
while (cursor->valid()) {
// go to the next iter
cursor->Next();
++db_size_;
}
LOG(INFO) << "DB Size: " << db_size_;
DLOG(INFO) << "Restarting data prefetching from start.";
cursor->SeekToFirst();
#ifdef use_bmat
std::string leveldbpath = param_.data_param().source();
std::string dbpath = leveldbpath.substr(0, leveldbpath.find("_leveldb"));
// read bmat from hard drvier, inlcuding train_data, train_data_label and train_data_mean.
temp_data tdata;
temp_data tdata_meta;
temp_data tdata_mean;
temp_data tdata_label;
bmat_parser.read_bmat(dbpath + "_data.bmat", tdata, INT64_MAX);
//bmat_parser.read_bmat(dbpath + "_data_mean.bmat", tdata_mean, INT64_MAX);
bmat_parser.read_bmat(dbpath + "_data_label.bmat", tdata_label, INT64_MAX);
// get db size
db_size_ = tdata.rows;
LOG(INFO) << "DB Size: " << tdata.rows;
//bmat_parser.read_bmat(dbpath + "_data_meta.bmat", tdata_meta, INT64_MAX);
//tdata_label.value_int = new int[tdata_label.cols];
//char* addr = tdata_label.value;
//for (long long i = 0; i < tdata_label.rows; ++i) {
// for (long long j = 0; j < tdata_label.cols; ++j) {
// __int32* v = (__int32*)addr;
// addr = addr + sizeof(int);
// tdata_label.value_int[i * tdata_label.cols + j] = *v;
// }
//}
//tdata_meta.value_int = new int[tdata_meta.rows * tdata_meta.cols];
//addr = tdata_meta.value;
//for (long long i = 0; i < tdata_meta.rows; ++i) {
// for (long long j = 0; j < tdata_meta.cols; ++j) {
// __int32* v = (__int32*)addr;
// addr = addr + sizeof(int);
// tdata_meta.value_int[i * tdata_meta.cols + j] = *v;
// }
//}
bool isTrainPhase = dbpath.find("test") == std::string::npos;
vector<int> indice;
indice.clear();
indice.resize(tdata.rows);
randperm(tdata.rows, indice, 1, false);
#endif
try {
int solver_count = param_.phase() == TRAIN ? Caffe::solver_count() : 1;
// To ensure deterministic runs, only start running once all solvers
// are ready. But solvers need to peek on one item during initialization,
// so read one item, then wait for the next solver.
int t = 0;
#ifdef use_bmat
for (int i = 0; i < solver_count; ++i) {
shared_ptr<QueuePair> qp(new_queue_pairs_.pop());
read_one_bmat(cursor.get(), indice[t], &tdata, &tdata_meta, &tdata_label, qp.get());
++t;
qps.push_back(qp);
}
#else
for (int i = 0; i < solver_count; ++i) {
shared_ptr<QueuePair> qp(new_queue_pairs_.pop());
read_one(cursor.get(), qp.get());
qps.push_back(qp);
}
#endif
// Main loop
while (!must_stop()) {
for (int i = 0; i < solver_count; ++i) {
#ifdef use_bmat
if (t >= tdata.rows) {
if (isTrainPhase)
randperm(tdata.rows, indice, 1, true);
t = 0;
}
read_one_bmat(cursor.get(), indice[t], &tdata, &tdata_meta, &tdata_label, qps[i].get());
++t;
#else
read_one(cursor.get(), qps[i].get());
#endif
}
// Check no additional readers have been created. This can happen if
// more than one net is trained at a time per process, whether single
// or multi solver. It might also happen if two data layers have same
// name and same source.
CHECK_EQ(new_queue_pairs_.size(), 0);
}
} catch (boost::thread_interrupted&) {
// Interrupted exception is expected on shutdown
}
}
void DataReader::Body::read_one(db::Cursor* cursor, QueuePair* qp) {
Datum* datum = qp->free_.pop();
// TODO deserialize in-place instead of copy?
datum->ParseFromString(cursor->value());
qp->full_.push(datum);
// go to the next iter
cursor->Next();
if (!cursor->valid()) {
DLOG(INFO) << "Restarting data prefetching from start.";
cursor->SeekToFirst();
}
}
void DataReader::Body::read_one_bmat(db::Cursor* cursor, int idx, temp_data* data, temp_data* meta, temp_data* label, QueuePair* qp) {
Datum* datum = qp->free_.pop();
datum->ParseFromString(cursor->value());
// TODO deserialize in-place instead of copy?
//datum->set_channels(meta->value_int[0]);
//datum->set_height(meta->value_int[1]);
//datum->set_width(meta->value_int[2]);
//
//datum->clear_data();
//datum->clear_float_data();
//char *dat = new char[data->cols];
//memcpy(dat, data->GetCharData(idx), data->cols);
std::string buffer = std::string(data->value + idx * data->cols, data->cols);
datum->set_data(buffer);
datum->set_label(label->value_int[idx]);
datum->add_float_data(idx);
// datum->set_encoded(false);
qp->full_.push(datum);
// LOG(INFO) << datum->label() << " " << datum->channels() << " " << datum->width() << " " << datum->height();
// go to the next iter
//cursor->Next();
//if (!cursor->valid()) {
// DLOG(INFO) << "Restarting data prefetching from start.";
// cursor->SeekToFirst();
//}
}
} // namespace caffe
| 29.596899 | 134 | 0.651126 | [
"vector"
] |
28ef28054a11912de4c0131e519b36a8ba19f861 | 980 | cpp | C++ | UVa/11220.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | 1 | 2018-02-11T09:41:54.000Z | 2018-02-11T09:41:54.000Z | UVa/11220.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | UVa/11220.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | /*{{{*/
#pragma GCC optimize ("O2")
#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
#define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define REP(i,a,b) for (int i = a; i < b; i++)
/*}}}*/
// Let's Fight!
int main() {
_
int N;
cin >> N;
string eat;
getline(cin, eat);
getline(cin, eat);
for(int a = 1; a <= N; a++){
if(a > 1)
cout << "\n";
cout << "Case #" << a << ":\n";
string enter;
while(getline(cin, enter)){
if(enter == "")
break;
stringstream ss;
ss << enter;
string ans;
int i = 0;
string parsee;
while(ss >> parsee){
if(SZ(parsee) > i)
ans += parsee[i++];
}
cout << ans << '\n';
}
}
return 0;
}
| 18.846154 | 57 | 0.569388 | [
"vector"
] |
28f0ce5f51116aca4b80fa5c77f1449d9f6e3417 | 8,711 | cpp | C++ | tests/serialization_tests.cpp | gridem/ReplobPrototype | 8c1f7ac46c9c46e7f02b402b8bbc5febaa152c90 | [
"Apache-2.0"
] | 3 | 2016-01-11T11:42:02.000Z | 2016-12-21T14:54:44.000Z | tests/serialization_tests.cpp | gridem/ReplobPrototype | 8c1f7ac46c9c46e7f02b402b8bbc5febaa152c90 | [
"Apache-2.0"
] | null | null | null | tests/serialization_tests.cpp | gridem/ReplobPrototype | 8c1f7ac46c9c46e7f02b402b8bbc5febaa152c90 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Grigory Demchenko (aka gridem)
*
* 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 <vector>
#include <cstring>
#include <chrono>
#include <synca/synca.h>
#include <synca/log.h>
#include "ut.h"
using Ptr = Byte*;
using PtrArray = Ptr*;
using IntArray = int*;
using Buf = std::vector<Byte>;
constexpr size_t ptrSize = sizeof(Ptr);
constexpr size_t intSize = sizeof(int);
struct View
{
Ptr data;
size_t size;
};
Buf viewToBuf(View view)
{
return {view.data, view.data + view.size};
}
struct IAllocator : IObject
{
virtual void* alloc(size_t sz) = 0;
virtual void dealloc(void *p) = 0;
};
struct DefaultAllocator
{
static void* alloc(size_t sz)
{
void *p = malloc(sz);
VERIFY(p != nullptr, "Allocation failed");
return p;
}
static void dealloc(void *p) noexcept
{
free(p);
}
};
thread_local Buf t_buffer(1024*1024*10);
thread_local IAllocator* t_allocator = nullptr;
struct MemoryAllocator : IAllocator
{
MemoryAllocator()
{
t_allocator = this;
}
~MemoryAllocator()
{
t_allocator = nullptr;
if (nDealloc_)
LOG("Deallocations: " << nDealloc_ << ": " << dp_);
}
void* alloc(size_t sz) override
{
Ptr p = t_buffer.data() + offset_;
size_t diff = sz % ptrSize;
if (diff)
sz += ptrSize - diff;
offset_ += sz;
VERIFY(offset_ <= t_buffer.size(), "MemoryAllocator: allocation failed: oversize");
return p;
}
void dealloc(void *p) override
{
if (p >= t_buffer.data() && p < t_buffer.data() + t_buffer.size())
{
++ nDealloc_;
dp_ = p;
}
else
{
DefaultAllocator::dealloc(p);
}
}
size_t size() const
{
return offset_;
}
void setSize(size_t size)
{
offset_ = size;
}
private:
size_t offset_ = 0;
int nDealloc_ = 0;
void* dp_ = nullptr;
};
void* operator new(size_t sz)
{
return t_allocator ? t_allocator->alloc(sz) : DefaultAllocator::alloc(sz);
}
void operator delete(void *p) noexcept
{
t_allocator ? t_allocator->dealloc(p) : DefaultAllocator::dealloc(p);
}
void setAllocator(IAllocator* a)
{
t_allocator = a;
}
IAllocator* getAllocator()
{
return t_allocator;
}
template<typename T>
Buf serialize(const T& t)
{
View v {t_buffer.data(), 0};
{
MemoryAllocator a;
new T(t);
v.size = a.size();
}
Buf buf = viewToBuf(v);
std::memset(v.data, 0, v.size); // need to be zeroized to avoid diff collisions
return buf;
}
template<typename T>
T deserialize(const Buf& buf)
{
VERIFY(buf.size() <= t_buffer.size(), "Buffer is too large");
std::memcpy(t_buffer.data(), buf.data(), buf.size());
return *(T*)t_buffer.data();
}
template<typename T>
Buf serializeRelative(const T& t)
{
View v {t_buffer.data(), 0};
size_t total;
{
MemoryAllocator a;
new T(t);
v.size = a.size();
new T(t);
total = a.size();
}
VERIFY(v.size % ptrSize == 0, "Unaligned data"); // carefully!!! verify allocates the memory
VERIFY(v.size * 2 == total, "Unpredictable copy constructor");
int pCount = v.size / ptrSize;
int diffIndex = v.size / intSize;
auto data = PtrArray(v.data);
auto diffData = IntArray(v.data);
for (int i = 0; i < pCount; ++ i)
{
int diff = data[i + pCount] - data[i];
if (diff)
{
//LOG("Diff: " << i << ", " << diff << ", " << diffIndex);
VERIFY(diff == v.size, "Invalid pointers shift");
data[i] -= intptr_t(v.data);
diffData[diffIndex ++] = i;
}
}
diffData[diffIndex ++] = v.size / intSize;
v.size = diffIndex * intSize;
//LOG("diff index created: " << v.size << ", " << diffIndex << ", " << pCount);
Buf buf = viewToBuf(v);
std::memset(v.data, 0, total);
return buf;
}
// perform in-place transformations
template<typename T>
T& deserializeRelative(Buf& buf)
{
VERIFY(buf.size() >= intSize, "Invalid buffer size: must be >= intSize");
VERIFY(buf.size() % intSize == 0, "Invalid buffer size: must be aligned");
int intCount = buf.size() / intSize - 1; // not to include the diff index
auto intArray = IntArray(buf.data());
auto data = PtrArray(buf.data());
int diffIndex = intArray[intCount];
VERIFY(diffIndex <= intCount, "Invalid diff index");
int dataCount = diffIndex * intSize / ptrSize;
for (int i = diffIndex; i < intCount; ++ i)
{
int dataIndex = intArray[i];
//LOG("Replacing: " << i << ", " << dataIndex);
VERIFY(dataIndex < dataCount, "Invalid data index");
data[dataIndex] += intptr_t(buf.data());
}
return *(T*)buf.data();
}
template<typename T>
std::ostream& operator<<(std::ostream& o, const std::vector<T>& v)
{
for (auto&& t: v)
o << t << " ";
return o;
}
template<typename F>
void measure(const char* name, F f, size_t count)
{
auto beg = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < count; ++ i)
f();
auto end = std::chrono::high_resolution_clock::now();
int ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1.0 / count;
LOG(name << ": " << ns << "ns");
}
TEST(serialization, vector)
{
std::vector<int> v {1, 2, 3, 10, 0x30};
auto buf = serialize(v);
auto v2 = deserialize<std::vector<int>>(buf);
ASSERT_EQ(v, v2);
}
TEST(serialization, relative)
{
try
{
std::vector<int> v {1, 2, 3, 10, 47, 5};
auto buf = serializeRelative(v);
auto beg = IntArray(buf.data());
for (int i = 0; i < buf.size() / intSize; ++ i)
{
LOG(i << ": " << beg[i]);
}
auto v2 = deserializeRelative<std::vector<int>>(buf);
for (auto val: v2)
{
LOG(val);
}
ASSERT_EQ(v, v2);
}
catch (std::exception& e)
{
LOG("Error: " << e.what());
}
}
TEST(serialization, relative2)
{
try
{
std::map<std::vector<int>, int> v {{{1, 2}, 1}, {{5, 3, 2}, 5}};
auto buf = serializeRelative(v);
auto beg = IntArray(buf.data());
for (int i = 0; i < buf.size() / intSize; ++ i)
{
LOG(i << ": " << beg[i]);
}
auto v2 = deserializeRelative<std::map<std::vector<int>, int>>(buf);
ASSERT_TRUE(v == v2);
}
catch (std::exception& e)
{
LOG("Error: " << e.what());
}
}
/*
TEST(serialization, relative2BenchLite)
{
struct Lite
{
int32_t x;
std::vector<int64_t> y;
};
Lite l;
l.x = 1;
l.y = {10,11};
measure("serialize lite", [&]{
auto buf = serializeRelative(l);
}, 1000000);
}
Buf toBuf(const char* s)
{
std::string c(s);
return Buf{c.begin(), c.begin() + c.size()};
}
TEST(serialization, relative2BenchHeavy)
{
struct Lite
{
int32_t x;
std::vector<int64_t> y;
};
struct Heavy
{
std::vector<int32_t> x;
std::vector<Buf> s;
std::vector<Lite> z;
};
Heavy h;
h.x = {1,2,3,4,5,6,7,8,9,10};
h.s = {toBuf("hello"), toBuf("yes"), toBuf("this"), toBuf("is"), toBuf("dog")};
h.z = {Lite{1, {10,11}}, Lite{2, {32,33,34,35}}};
measure("serialize heavy", [&]{
auto buf = serializeRelative(h);
}, 100000);
}
TEST(deserialization, relative2BenchHeavy)
{
struct Lite
{
int32_t x;
std::vector<int64_t> y;
};
struct Heavy
{
std::vector<int32_t> x;
std::vector<Buf> s;
std::vector<Lite> z;
};
Heavy h;
h.x = {1,2,3,4,5,6,7,8,9,10};
h.s = {toBuf("hello"), toBuf("yes"), toBuf("this"), toBuf("is"), toBuf("dog")};
h.z = {Lite{1, {10,11}}, Lite{2, {32,33,34,35}}};
Buf buf = serializeRelative(h);
measure("deserialize heavy", [&]{
Heavy& h = deserializeRelative<Heavy>(buf);
}, 10000000);
}
*/
TEST(math, test)
{
ASSERT_EQ(-2, -2 % 4);
ASSERT_EQ(-2, -10 % 4);
}
CPPUT_TEST_MAIN
| 22.984169 | 99 | 0.559982 | [
"vector"
] |
28f2802b9a73499449c2ba30a87a601f16d2980a | 4,716 | cpp | C++ | Cpp/Coursera/ModernCpp/02_yellow/010_test_person/solution.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | Cpp/Coursera/ModernCpp/02_yellow/010_test_person/solution.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | Cpp/Coursera/ModernCpp/02_yellow/010_test_person/solution.cpp | neon1ks/Study | 5d40171cf3bf5e8d3a95539e91f5afec54d1daf3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <ostream>
#include <random>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
template <class T>
ostream &operator<<(ostream &os, const vector<T> &s) {
os << "{";
bool first = true;
for (const auto &x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
os << "{";
bool first = true;
for (const auto &x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class K, class V>
ostream &operator<<(ostream &os, const map<K, V> &m) {
os << "{";
bool first = true;
for (const auto &kv : m) {
if (!first) {
os << ", ";
}
first = false;
os << kv.first << ": " << kv.second;
}
return os << "}";
}
template <class T, class U>
void AssertEqual(const T &t, const U &u, const string &hint = {}) {
if (t != u) {
ostringstream os;
os << "Assertion failed: " << t << " != " << u;
if (!hint.empty()) {
os << " hint: " << hint;
}
throw runtime_error(os.str());
}
}
void Assert(bool b, const string &hint) { AssertEqual(b, true, hint); }
class TestRunner {
public:
template <class TestFunc>
void RunTest(TestFunc func, const string &test_name) {
try {
func();
cerr << test_name << " OK" << endl;
} catch (exception &e) {
++fail_count;
cerr << test_name << " fail: " << e.what() << endl;
} catch (...) {
++fail_count;
cerr << "Unknown exception caught" << endl;
}
}
~TestRunner() {
if (fail_count > 0) {
cerr << fail_count << " unit tests failed. Terminate" << endl;
exit(1);
}
}
private:
int fail_count = 0;
};
#ifdef ONLY_HOME
class Person
{
public:
void ChangeFirstName(int year, const string &first_name)
{
history[year].FirstName = first_name;
}
void ChangeLastName(int year, const string &last_name)
{
history[year].LastName = last_name;
}
string GetFullName(int year)
{
string first_name;
string last_name;
for (const auto &y : history) {
if (year < y.first) {
break;
}
if (!y.second.FirstName.empty()) {
first_name = y.second.FirstName;
}
if (!y.second.LastName.empty()) {
last_name = y.second.LastName;
}
if (year == y.first) {
break;
}
}
if (first_name.empty() && last_name.empty()) {
return "Incognito";
}
if (first_name.empty()) {
return last_name + " with unknown first name";
}
if (last_name.empty()) {
return first_name + " with unknown last name";
}
return first_name + ' ' + last_name;
}
private:
struct FirstAndLastName
{
string FirstName;
string LastName;
};
map<int, FirstAndLastName> history;
// приватные поля
};
#endif
void TestPredefinedLastNameFirst() {
Person person;
person.ChangeLastName(1965, "Sergeeva");
person.ChangeFirstName(1967, "Polina");
AssertEqual(person.GetFullName(1964), "Incognito");
AssertEqual(person.GetFullName(1966), "Sergeeva with unknown first name");
AssertEqual(person.GetFullName(1968), "Polina Sergeeva");
}
void TestPredefined() {
Person person;
person.ChangeFirstName(1965, "Polina");
person.ChangeLastName(1967, "Sergeeva");
AssertEqual(person.GetFullName(1964), "Incognito");
AssertEqual(person.GetFullName(1966), "Polina with unknown last name");
AssertEqual(person.GetFullName(1968), "Polina Sergeeva");
person.ChangeFirstName(1969, "Appolinaria");
AssertEqual(person.GetFullName(1968), "Polina Sergeeva");
AssertEqual(person.GetFullName(1969), "Appolinaria Sergeeva");
AssertEqual(person.GetFullName(1970), "Appolinaria Sergeeva");
person.ChangeLastName(1968, "Volkova");
AssertEqual(person.GetFullName(1967), "Polina Sergeeva");
AssertEqual(person.GetFullName(1968), "Polina Volkova");
AssertEqual(person.GetFullName(1969), "Appolinaria Volkova");
}
int main() {
TestRunner runner;
runner.RunTest(TestPredefined, "TestPredefined");
runner.RunTest(TestPredefinedLastNameFirst, "TestPredefinedLastNameFirst");
return 0;
}
| 24.821053 | 79 | 0.556192 | [
"vector"
] |
28fe7121de27e32870b03a7594cc0b53f59c07d4 | 4,623 | cpp | C++ | More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Robots on Ice.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | 3 | 2017-08-12T06:09:39.000Z | 2018-09-16T02:31:27.000Z | More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Robots on Ice.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | null | null | null | More Advanced Topics/More Advanced Search Techniques/Meet in the Middle A* DA*/Robots on Ice.cpp | satvik007/uva | 72a763f7ed46a34abfcf23891300d68581adeb44 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <int> vi;
int x[3], y[3];
int n, m;
unordered_map <ll, int> ans1, ans2;
int dr[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};
void dfs(int ax, int ay, ll ¤t){
for(int k=0; k<4; k++){
int tx = ax + dr[k];
int ty = ay + dc[k];
if(tx >= 0 && ty >= 0 && tx < n && ty < m && !(current & (1LL<<(m*tx + ty)))){
current |= (1LL<<(m*tx + ty));
dfs(tx, ty, current);
}
}
}
bool floodFill(int ax, int ay, ll current){
dfs(ax, ay, current);
if(n * m == 64) return current != -1;
return (current != (1LL<<(n*m)) - 1);
}
void bfs1(){
queue <int> dist; dist.push(n*m);
queue <int> q; q.push(0); q.push(1);
queue <ll> mask; mask.push(2LL);
ll current;
int tx, ax, ty, ay, distance;
bool flag;
while(!q.empty()){
ax = q.front(); q.pop();
ay = q.front(); q.pop();
distance = dist.front(); dist.pop();
current = mask.front(); mask.pop();
if(ax == 0 && ay == 0) continue;
if(ax == x[1] && ay == y[1]) {
if(distance == n * m / 2){
if(ans1.find(current) != ans1.end()) ans1[current]++;
else ans1[current] = 1;
}
continue;
}else if(distance == n*m/2) continue;
flag = false;
for(int i=0; i<3; i++){
if(x[i] == ax && y[i] == ay && distance != (i+1)*n*m/4) {
flag = true; break;
}else if(distance == (i+1)*n*m/4 && (x[i] != ax || y[i] != ay)){
flag = true; break;
}
}
if(flag) continue;
if(distance > m*n*3/4){
if(abs(ax-x[2]) + abs(ay-y[2]) > distance - m*n*3/4) continue;
}else if(distance > m * n / 2){
if(abs(ax-x[1]) + abs(ay-y[1]) > distance - m*n/2) continue;
}
if(floodFill(0, 0, current)) continue;
for(int k=0; k<4; k++){
tx = ax + dr[k];
ty = ay + dc[k];
if(tx >= 0 && ty >= 0 && tx < n && ty < m && !(current & (1LL<<(tx*m+ty)))){
q.push(tx); q.push(ty);
dist.push(distance-1);
mask.push(current | (1LL<<(m*tx + ty)));
}
}
}
}
void bfs2(){
//cout << endl;
queue <int> dist; dist.push(1);
queue <int> q; q.push(0); q.push(0);
queue <ll> mask; mask.push(1LL);
ll current;
int tx, ax, ty, ay, distance;
bool flag;
while(!q.empty()){
ax = q.front(); q.pop();
ay = q.front(); q.pop();
distance = dist.front(); dist.pop();
current = mask.front(); mask.pop();
if(ax == 0 && ay == 1) continue;
if(ax == x[1] && ay == y[1]) {
if(distance == n * m / 2){
if(ans2.find(current) != ans2.end()) ans2[current]++;
else ans2[current] = 1;
}
continue;
}else if(distance == n*m/2) continue;
flag = false;
for(int i=0; i<3; i++){
if(x[i] == ax && y[i] == ay && distance != (i+1)*n*m/4) {
flag = true; break;
}else if(distance == (i+1)*n*m/4 && (x[i] != ax || y[i] != ay)){
flag = true; break;
}
}
if(flag) continue;
if(floodFill(0, 1, current)) continue;
//cout << ax << " " << ay << " " << distance << " " << bitset <32> (current) << endl;
for(int k=0; k<4; k++){
tx = ax + dr[k];
ty = ay + dc[k];
if(tx >= 0 && ty >= 0 && tx < n && ty < m && !(current & (1LL<<(tx*m+ty)))){
q.push(tx); q.push(ty);
dist.push(distance+1);
mask.push(current | (1LL<<(m*tx + ty)));
}
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int cas = 1;
while(cin >> n >> m, n){
ans1.clear(); ans2.clear();
for(int i=0; i<3; i++){
cin >> x[i] >> y[i];
}
bfs1(); bfs2();
int counter = 0;
ll check = (1LL << (n*m)) - 1;
for(auto el1:ans2){
ll temp = el1.first;
if(n*m == 64) temp = (~temp) | (1LL<<(m*x[1] + y[1]));
else temp = ((~temp) & ((1LL << (n*m)) - 1))|(1LL<<(m*x[1] + y[1]));
if(ans1.find(temp) != ans1.end()){
counter += (el1.second * ans1[temp]);
}
}
cout << "Case " << cas++ << ": " << counter << "\n";
}
return 0;
} | 32.328671 | 93 | 0.412503 | [
"vector"
] |
28feeb826e48039da30ccd9f90b6117def3e34c6 | 20,685 | cpp | C++ | src/info.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | 2 | 2018-01-18T21:30:20.000Z | 2018-01-19T02:24:46.000Z | src/info.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | src/info.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | /*
** info.cpp
** Keeps track of available actors and their states
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** 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.
**---------------------------------------------------------------------------
**
** This is completely different from Doom's info.c.
**
*/
#include "doomstat.h"
#include "info.h"
#include "m_fixed.h"
#include "c_dispatch.h"
#include "d_net.h"
#include "v_text.h"
#include "gi.h"
#include "actor.h"
#include "r_state.h"
#include "i_system.h"
#include "p_local.h"
#include "templates.h"
#include "cmdlib.h"
#include "g_level.h"
#include "stats.h"
#include "thingdef.h"
#include "d_player.h"
#include "doomerrors.h"
#include "events.h"
#include "types.h"
#include "vm.h"
extern void LoadActors ();
extern void InitBotStuff();
extern void ClearStrifeTypes();
TArray<PClassActor *> PClassActor::AllActorClasses;
FRandom FState::pr_statetics("StateTics");
cycle_t ActionCycles;
//==========================================================================
//
// special type for the native ActorInfo. This allows to let this struct
// be handled by the generic object constructors for the VM.
//
//==========================================================================
class PActorInfo : public PCompoundType
{
public:
PActorInfo()
:PCompoundType(sizeof(FActorInfo), alignof(FActorInfo))
{
}
void SetDefaultValue(void *base, unsigned offset, TArray<FTypeAndOffset> *special) override
{
if (base != nullptr) new((uint8_t *)base + offset) FActorInfo;
if (special != nullptr)
{
special->Push(std::make_pair(this, offset));
}
}
void InitializeValue(void *addr, const void *def) const override
{
if (def == nullptr)
{
new(addr) FActorInfo;
}
else
{
new(addr) FActorInfo(*(const FActorInfo*)def);
}
}
void DestroyValue(void *addr) const override
{
FActorInfo *self = (FActorInfo*)addr;
self->~FActorInfo();
}
};
void AddActorInfo(PClass *cls)
{
auto type = new PActorInfo;
TypeTable.AddType(type, NAME_Actor);
cls->AddField("*", type, VARF_Meta);
}
void FState::SetAction(const char *name)
{
ActionFunc = FindVMFunction(RUNTIME_CLASS(AActor), name);
}
bool FState::CallAction(AActor *self, AActor *stateowner, FStateParamInfo *info, FState **stateret)
{
if (ActionFunc != nullptr)
{
ActionCycles.Clock();
VMValue params[3] = { self, stateowner, VMValue(info) };
// If the function returns a state, store it at *stateret.
// If it doesn't return a state but stateret is non-nullptr, we need
// to set *stateret to nullptr.
if (stateret != nullptr)
{
*stateret = nullptr;
if (ActionFunc->Proto == nullptr ||
ActionFunc->Proto->ReturnTypes.Size() == 0 ||
ActionFunc->Proto->ReturnTypes[0] != TypeState)
{
stateret = nullptr;
}
}
try
{
if (stateret == nullptr)
{
VMCall(ActionFunc, params, ActionFunc->ImplicitArgs, nullptr, 0);
}
else
{
VMReturn ret;
ret.PointerAt((void **)stateret);
VMCall(ActionFunc, params, ActionFunc->ImplicitArgs, &ret, 1);
}
}
catch (CVMAbortException &err)
{
err.MaybePrintMessage();
const char *callinfo = "";
if (info != nullptr && info->mStateType == STATE_Psprite)
{
if (stateowner->IsKindOf(NAME_Weapon) && stateowner != self) callinfo = "weapon ";
else callinfo = "overlay ";
}
err.stacktrace.AppendFormat("Called from %sstate %s in %s\n", callinfo, FState::StaticGetStateName(this).GetChars(), stateowner->GetClass()->TypeName.GetChars());
throw;
throw;
}
ActionCycles.Unclock();
return true;
}
else
{
return false;
}
}
//==========================================================================
//
//
//==========================================================================
int GetSpriteIndex(const char * spritename, bool add)
{
static char lastsprite[5];
static int lastindex;
// Make sure that the string is upper case and 4 characters long
char upper[5]={0,0,0,0,0};
for (int i = 0; spritename[i] != 0 && i < 4; i++)
{
upper[i] = toupper (spritename[i]);
}
// cache the name so if the next one is the same the function doesn't have to perform a search.
if (!strcmp(upper, lastsprite))
{
return lastindex;
}
strcpy(lastsprite, upper);
for (unsigned i = 0; i < sprites.Size (); ++i)
{
if (strcmp (sprites[i].name, upper) == 0)
{
return (lastindex = (int)i);
}
}
if (!add)
{
return (lastindex = -1);
}
spritedef_t temp;
strcpy (temp.name, upper);
temp.numframes = 0;
temp.spriteframes = 0;
return (lastindex = (int)sprites.Push (temp));
}
DEFINE_ACTION_FUNCTION(AActor, GetSpriteIndex)
{
PARAM_PROLOGUE;
PARAM_NAME(sprt);
ACTION_RETURN_INT(GetSpriteIndex(sprt.GetChars(), false));
}
//==========================================================================
//
// PClassActor :: StaticInit STATIC
//
//==========================================================================
void PClassActor::StaticInit()
{
sprites.Clear();
if (sprites.Size() == 0)
{
spritedef_t temp;
// Sprite 0 is always TNT1
memcpy (temp.name, "TNT1", 5);
temp.numframes = 0;
temp.spriteframes = 0;
sprites.Push (temp);
// Sprite 1 is always ----
memcpy (temp.name, "----", 5);
sprites.Push (temp);
// Sprite 2 is always ####
memcpy (temp.name, "####", 5);
sprites.Push (temp);
}
if (!batchrun) Printf ("LoadActors: Load actor definitions.\n");
ClearStrifeTypes();
LoadActors ();
InitBotStuff();
// reinit GLOBAL static stuff from gameinfo, once classes are loaded.
E_InitStaticHandlers(false);
}
//==========================================================================
//
// PClassActor :: StaticSetActorNums STATIC
//
// Called after Dehacked patches are applied
//
//==========================================================================
void PClassActor::StaticSetActorNums()
{
for (unsigned int i = 0; i < PClassActor::AllActorClasses.Size(); ++i)
{
PClassActor::AllActorClasses[i]->RegisterIDs();
}
}
//==========================================================================
//
// PClassActor :: SetReplacement
//
// Sets as a replacement class for another class.
//
//==========================================================================
bool PClassActor::SetReplacement(FName replaceName)
{
// Check for "replaces"
if (replaceName != NAME_None)
{
// Get actor name
PClassActor *replacee = PClass::FindActor(replaceName);
if (replacee == nullptr)
{
return false;
}
if (replacee != nullptr)
{
replacee->ActorInfo()->Replacement = this;
ActorInfo()->Replacee = replacee;
}
}
return true;
}
//==========================================================================
//
// PClassActor :: Finalize
//
// Installs the parsed states and does some sanity checking
//
//==========================================================================
void AActor::Finalize(FStateDefinitions &statedef)
{
try
{
statedef.FinishStates(GetClass());
}
catch (CRecoverableError &)
{
statedef.MakeStateDefines(nullptr);
throw;
}
statedef.InstallStates(GetClass(), this);
statedef.MakeStateDefines(nullptr);
}
//==========================================================================
//
// PClassActor :: RegisterIDs
//
// Registers this class's SpawnID and DoomEdNum in the appropriate tables.
//
//==========================================================================
void PClassActor::RegisterIDs()
{
PClassActor *cls = PClass::FindActor(TypeName);
if (cls == nullptr)
{
Printf(TEXTCOLOR_RED"The actor '%s' has been hidden by a non-actor of the same name\n", TypeName.GetChars());
return;
}
FActorInfo *actorInfo = ActorInfo();
if (nullptr == actorInfo)
{
// Undefined class, exiting
return;
}
// Conversation IDs have never been filtered by game so we cannot start doing that.
auto ConversationID = actorInfo->ConversationID;
if (ConversationID > 0)
{
StrifeTypes[ConversationID] = cls;
if (cls != this)
{
Printf(TEXTCOLOR_RED"Conversation ID %d refers to hidden class type '%s'\n", ConversationID, cls->TypeName.GetChars());
}
}
if (actorInfo->GameFilter == GAME_Any || (ActorInfo()->GameFilter & gameinfo.gametype))
{
auto SpawnID = actorInfo->SpawnID;
if (SpawnID > 0)
{
SpawnableThings[SpawnID] = cls;
if (cls != this)
{
Printf(TEXTCOLOR_RED"Spawn ID %d refers to hidden class type '%s'\n", SpawnID, cls->TypeName.GetChars());
}
}
auto DoomEdNum = actorInfo->DoomEdNum;
if (DoomEdNum != -1)
{
FDoomEdEntry *oldent = DoomEdMap.CheckKey(DoomEdNum);
if (oldent != nullptr && oldent->Special == -2)
{
Printf(TEXTCOLOR_RED"Editor number %d defined twice for classes '%s' and '%s'\n", DoomEdNum, cls->TypeName.GetChars(), oldent->Type->TypeName.GetChars());
}
FDoomEdEntry ent;
memset(&ent, 0, sizeof(ent));
ent.Type = cls;
ent.Special = -2; // use -2 instead of -1 so that we can recognize DECORATE defined entries and print a warning message if duplicates occur.
DoomEdMap.Insert(DoomEdNum, ent);
if (cls != this)
{
Printf(TEXTCOLOR_RED"Editor number %d refers to hidden class type '%s'\n", DoomEdNum, cls->TypeName.GetChars());
}
}
}
}
//==========================================================================
//
// PClassActor :: GetReplacement
//
//==========================================================================
PClassActor *PClassActor::GetReplacement(bool lookskill)
{
FName skillrepname;
if (lookskill && AllSkills.Size() > (unsigned)gameskill)
{
skillrepname = AllSkills[gameskill].GetReplacement(TypeName);
if (skillrepname != NAME_None && PClass::FindClass(skillrepname) == nullptr)
{
Printf("Warning: incorrect actor name in definition of skill %s: \n"
"class %s is replaced by non-existent class %s\n"
"Skill replacement will be ignored for this actor.\n",
AllSkills[gameskill].Name.GetChars(),
TypeName.GetChars(), skillrepname.GetChars());
AllSkills[gameskill].SetReplacement(TypeName, NAME_None);
AllSkills[gameskill].SetReplacedBy(skillrepname, NAME_None);
lookskill = false; skillrepname = NAME_None;
}
}
auto Replacement = ActorInfo()->Replacement;
if (Replacement == nullptr && (!lookskill || skillrepname == NAME_None))
{
return this;
}
// The Replacement field is temporarily NULLed to prevent
// potential infinite recursion.
ActorInfo()->Replacement = nullptr;
PClassActor *rep = Replacement;
// Handle skill-based replacement here. It has precedence on DECORATE replacement
// in that the skill replacement is applied first, followed by DECORATE replacement
// on the actor indicated by the skill replacement.
if (lookskill && (skillrepname != NAME_None))
{
rep = PClass::FindActor(skillrepname);
}
// Now handle DECORATE replacement chain
// Skill replacements are not recursive, contrarily to DECORATE replacements
rep = rep->GetReplacement(false);
// Reset the temporarily NULLed field
ActorInfo()->Replacement = Replacement;
return rep;
}
DEFINE_ACTION_FUNCTION(AActor, GetReplacement)
{
PARAM_PROLOGUE;
PARAM_POINTER(c, PClassActor);
ACTION_RETURN_POINTER(c->GetReplacement());
}
//==========================================================================
//
// PClassActor :: GetReplacee
//
//==========================================================================
PClassActor *PClassActor::GetReplacee(bool lookskill)
{
FName skillrepname;
if (lookskill && AllSkills.Size() > (unsigned)gameskill)
{
skillrepname = AllSkills[gameskill].GetReplacedBy(TypeName);
if (skillrepname != NAME_None && PClass::FindClass(skillrepname) == nullptr)
{
Printf("Warning: incorrect actor name in definition of skill %s: \n"
"non-existent class %s is replaced by class %s\n"
"Skill replacement will be ignored for this actor.\n",
AllSkills[gameskill].Name.GetChars(),
skillrepname.GetChars(), TypeName.GetChars());
AllSkills[gameskill].SetReplacedBy(TypeName, NAME_None);
AllSkills[gameskill].SetReplacement(skillrepname, NAME_None);
lookskill = false;
}
}
PClassActor *savedrep = ActorInfo()->Replacee;
if (savedrep == nullptr && (!lookskill || skillrepname == NAME_None))
{
return this;
}
// The Replacee field is temporarily NULLed to prevent
// potential infinite recursion.
ActorInfo()->Replacee = nullptr;
PClassActor *rep = savedrep;
if (lookskill && (skillrepname != NAME_None) && (PClass::FindClass(skillrepname) != nullptr))
{
rep = PClass::FindActor(skillrepname);
}
rep = rep->GetReplacee(false);
ActorInfo()->Replacee = savedrep;
return rep;
}
DEFINE_ACTION_FUNCTION(AActor, GetReplacee)
{
PARAM_PROLOGUE;
PARAM_POINTER(c, PClassActor);
ACTION_RETURN_POINTER(c->GetReplacee());
}
//==========================================================================
//
// PClassActor :: SetDamageFactor
//
//==========================================================================
void PClassActor::SetDamageFactor(FName type, double factor)
{
for (auto & p : ActorInfo()->DamageFactors)
{
if (p.first == type)
{
p.second = factor;
return;
}
}
ActorInfo()->DamageFactors.Push({ type, factor });
}
//==========================================================================
//
// PClassActor :: SetPainChance
//
//==========================================================================
void PClassActor::SetPainChance(FName type, int chance)
{
for (auto & p : ActorInfo()->PainChances)
{
if (p.first == type)
{
p.second = chance;
return;
}
}
if (chance >= 0)
{
ActorInfo()->PainChances.Push({ type, MIN(chance, 256) });
}
}
//==========================================================================
//
// DmgFactors :: CheckFactor
//
// Checks for the existance of a certain damage type. If that type does not
// exist, the damage factor for type 'None' will be returned, if present.
//
//==========================================================================
int DmgFactors::Apply(FName type, int damage)
{
double factor = -1.;
for (auto & p : *this)
{
if (p.first == type)
{
factor = p.second;
break;
}
if (p.first == NAME_None)
{
factor = p.second;
}
}
if (factor < 0.) return damage;
return int(damage * factor);
}
static void SummonActor (int command, int command2, FCommandLine argv)
{
if (CheckCheatmode ())
return;
if (argv.argc() > 1)
{
PClassActor *type = PClass::FindActor(argv[1]);
if (type == nullptr)
{
Printf ("Unknown actor '%s'\n", argv[1]);
return;
}
Net_WriteByte (argv.argc() > 2 ? command2 : command);
Net_WriteString (type->TypeName.GetChars());
if (argv.argc () > 2)
{
Net_WriteWord (atoi (argv[2])); // angle
Net_WriteWord ((argv.argc() > 3) ? atoi(argv[3]) : 0); // TID
Net_WriteByte ((argv.argc() > 4) ? atoi(argv[4]) : 0); // special
for (int i = 5; i < 10; i++)
{ // args[5]
Net_WriteLong((i < argv.argc()) ? atoi(argv[i]) : 0);
}
}
}
}
CCMD (summon)
{
SummonActor (DEM_SUMMON, DEM_SUMMON2, argv);
}
CCMD (summonfriend)
{
SummonActor (DEM_SUMMONFRIEND, DEM_SUMMONFRIEND2, argv);
}
CCMD (summonmbf)
{
SummonActor (DEM_SUMMONMBF, DEM_SUMMONFRIEND2, argv);
}
CCMD (summonfoe)
{
SummonActor (DEM_SUMMONFOE, DEM_SUMMONFOE2, argv);
}
// Damage type defaults / global settings
TMap<FName, DamageTypeDefinition> GlobalDamageDefinitions;
void DamageTypeDefinition::Apply(FName type)
{
GlobalDamageDefinitions[type] = *this;
}
DamageTypeDefinition *DamageTypeDefinition::Get(FName type)
{
return GlobalDamageDefinitions.CheckKey(type);
}
bool DamageTypeDefinition::IgnoreArmor(FName type)
{
DamageTypeDefinition *dtd = Get(type);
if (dtd) return dtd->NoArmor;
return false;
}
DEFINE_ACTION_FUNCTION(_DamageTypeDefinition, IgnoreArmor)
{
PARAM_PROLOGUE;
PARAM_NAME(type);
ACTION_RETURN_BOOL(DamageTypeDefinition::IgnoreArmor(type));
}
FString DamageTypeDefinition::GetObituary(FName type)
{
DamageTypeDefinition *dtd = Get(type);
if (dtd) return dtd->Obituary;
return "";
}
//==========================================================================
//
// DamageTypeDefinition :: ApplyMobjDamageFactor
//
// Calculates mobj damage based on original damage, defined damage factors
// and damage type.
//
// If the specific damage type is not defined, the damage factor for
// type 'None' will be used (with 1.0 as a default value).
//
// Globally declared damage types may override or multiply the damage
// factor when 'None' is used as a fallback in this function.
//
//==========================================================================
double DamageTypeDefinition::GetMobjDamageFactor(FName type, DmgFactors const * const factors)
{
double defaultfac = -1.;
if (factors)
{
// If the actor has named damage factors, look for a specific factor
for (auto & p : *factors)
{
if (p.first == type) return p.second; // type specific damage type
if (p.first == NAME_None) defaultfac = p.second;
}
// If this was nonspecific damage, don't fall back to nonspecific search
if (type == NAME_None) return 1.;
}
// If this was nonspecific damage, don't fall back to nonspecific search
else if (type == NAME_None)
{
return 1.;
}
else
{
// Normal is unsupplied / 1.0, so there's no difference between modifying and overriding
DamageTypeDefinition *dtd = Get(type);
return dtd ? dtd->DefaultFactor : 1.;
}
{
DamageTypeDefinition *dtd = Get(type);
// Here we are looking for modifications to untyped damage
// If the calling actor defines untyped damage factor, that is contained in "pdf".
if (defaultfac >= 0.) // normal damage available
{
if (dtd)
{
if (dtd->ReplaceFactor) return dtd->DefaultFactor; // use default instead of untyped factor
return defaultfac * dtd->DefaultFactor; // use default as modification of untyped factor
}
return defaultfac; // there was no default, so actor default is used
}
else if (dtd)
{
return dtd->DefaultFactor; // implicit untyped factor 1.0 does not need to be applied/replaced explicitly
}
}
return 1.;
}
int DamageTypeDefinition::ApplyMobjDamageFactor(int damage, FName type, DmgFactors const * const factors)
{
double factor = GetMobjDamageFactor(type, factors);
return int(damage * factor);
}
//==========================================================================
//
// Reads a damage definition
//
//==========================================================================
void FMapInfoParser::ParseDamageDefinition()
{
sc.MustGetString();
FName damageType = sc.String;
DamageTypeDefinition dtd;
ParseOpenBrace();
while (sc.MustGetAnyToken(), sc.TokenType != '}')
{
if (sc.Compare("FACTOR"))
{
sc.MustGetStringName("=");
sc.MustGetFloat();
dtd.DefaultFactor = sc.Float;
if (dtd.DefaultFactor == 0) dtd.ReplaceFactor = true;
}
else if (sc.Compare("OBITUARY"))
{
sc.MustGetStringName("=");
sc.MustGetString();
dtd.Obituary = sc.String;
}
else if (sc.Compare("REPLACEFACTOR"))
{
dtd.ReplaceFactor = true;
}
else if (sc.Compare("NOARMOR"))
{
dtd.NoArmor = true;
}
else
{
sc.ScriptError("Unexpected data (%s) in damagetype definition.", sc.String);
}
}
dtd.Apply(damageType);
}
| 26.383929 | 165 | 0.61373 | [
"object"
] |
e900ca7c618d277d68db68491a4f472c12e006b6 | 12,262 | cpp | C++ | level_zero/tools/test/unit_tests/sources/sysman/scheduler/linux/test_zes_scheduler.cpp | rscohn2/compute-runtime | c0b6e6852d1c3870b089de651c3dd27ca82b1431 | [
"MIT"
] | null | null | null | level_zero/tools/test/unit_tests/sources/sysman/scheduler/linux/test_zes_scheduler.cpp | rscohn2/compute-runtime | c0b6e6852d1c3870b089de651c3dd27ca82b1431 | [
"MIT"
] | null | null | null | level_zero/tools/test/unit_tests/sources/sysman/scheduler/linux/test_zes_scheduler.cpp | rscohn2/compute-runtime | c0b6e6852d1c3870b089de651c3dd27ca82b1431 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/test/unit_tests/sources/sysman/linux/mock_sysman_fixture.h"
#include "mock_sysfs_scheduler.h"
namespace L0 {
namespace ult {
constexpr uint32_t handleComponentCount = 1u;
constexpr uint64_t convertMilliToMicro = 1000u;
constexpr uint64_t defaultTimeoutMilliSecs = 650u;
constexpr uint64_t defaultTimesliceMilliSecs = 1u;
constexpr uint64_t defaultHeartbeatMilliSecs = 3000u;
constexpr uint64_t timeoutMilliSecs = 640u;
constexpr uint64_t timesliceMilliSecs = 1u;
constexpr uint64_t heartbeatMilliSecs = 2500u;
constexpr uint64_t expectedDefaultHeartbeatTimeoutMicroSecs = defaultHeartbeatMilliSecs * convertMilliToMicro;
constexpr uint64_t expectedDefaultTimeoutMicroSecs = defaultTimeoutMilliSecs * convertMilliToMicro;
constexpr uint64_t expectedDefaultTimesliceMicroSecs = defaultTimesliceMilliSecs * convertMilliToMicro;
constexpr uint64_t expectedHeartbeatTimeoutMicroSecs = heartbeatMilliSecs * convertMilliToMicro;
constexpr uint64_t expectedTimeoutMicroSecs = timeoutMilliSecs * convertMilliToMicro;
constexpr uint64_t expectedTimesliceMicroSecs = timesliceMilliSecs * convertMilliToMicro;
class SysmanDeviceSchedulerFixture : public SysmanDeviceFixture {
protected:
std::unique_ptr<Mock<SchedulerSysfsAccess>> pSysfsAccess;
SysfsAccess *pSysfsAccessOld = nullptr;
void SetUp() override {
SysmanDeviceFixture::SetUp();
pSysfsAccessOld = pLinuxSysmanImp->pSysfsAccess;
pSysfsAccess = std::make_unique<NiceMock<Mock<SchedulerSysfsAccess>>>();
pLinuxSysmanImp->pSysfsAccess = pSysfsAccess.get();
pSysfsAccess->setVal(defaultPreemptTimeoutMilliSecs, defaultTimeoutMilliSecs);
pSysfsAccess->setVal(defaultTimesliceDurationMilliSecs, defaultTimesliceMilliSecs);
pSysfsAccess->setVal(defaultHeartbeatIntervalMilliSecs, defaultHeartbeatMilliSecs);
pSysfsAccess->setVal(preemptTimeoutMilliSecs, timeoutMilliSecs);
pSysfsAccess->setVal(timesliceDurationMilliSecs, timesliceMilliSecs);
pSysfsAccess->setVal(heartbeatIntervalMilliSecs, heartbeatMilliSecs);
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getVal));
ON_CALL(*pSysfsAccess.get(), write(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::setVal));
ON_CALL(*pSysfsAccess.get(), canRead(_))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getCanReadStatus));
pSysmanDeviceImp->pSchedulerHandleContext->init();
}
void TearDown() override {
SysmanDeviceFixture::TearDown();
pLinuxSysmanImp->pSysfsAccess = pSysfsAccessOld;
}
std::vector<zes_sched_handle_t> get_sched_handles(uint32_t count) {
std::vector<zes_sched_handle_t> handles(count, nullptr);
EXPECT_EQ(zesDeviceEnumSchedulers(device->toHandle(), &count, handles.data()), ZE_RESULT_SUCCESS);
return handles;
}
zes_sched_mode_t fixtureGetCurrentMode(zes_sched_handle_t hScheduler) {
zes_sched_mode_t mode;
ze_result_t result = zesSchedulerGetCurrentMode(hScheduler, &mode);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
return mode;
}
zes_sched_timeout_properties_t fixtureGetTimeoutModeProperties(zes_sched_handle_t hScheduler, ze_bool_t getDefaults) {
zes_sched_timeout_properties_t config;
ze_result_t result = zesSchedulerGetTimeoutModeProperties(hScheduler, getDefaults, &config);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
return config;
}
zes_sched_timeslice_properties_t fixtureGetTimesliceModeProperties(zes_sched_handle_t hScheduler, ze_bool_t getDefaults) {
zes_sched_timeslice_properties_t config;
ze_result_t result = zesSchedulerGetTimesliceModeProperties(hScheduler, getDefaults, &config);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
return config;
}
};
TEST_F(SysmanDeviceSchedulerFixture, GivenComponentCountZeroWhenCallingzesDeviceEnumSchedulersAndSysfsCanReadReturnsErrorThenZeroCountIsReturned) {
ON_CALL(*pSysfsAccess.get(), canRead(_))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getCanReadStatusReturnError));
auto pSchedulerHandleContextTest = std::make_unique<SchedulerHandleContext>(pOsSysman);
pSchedulerHandleContextTest->init();
EXPECT_EQ(0u, static_cast<uint32_t>(pSchedulerHandleContextTest->handleList.size()));
}
TEST_F(SysmanDeviceSchedulerFixture, GivenComponentCountZeroWhenCallingzesDeviceEnumSchedulersThenNonZeroCountIsReturnedAndVerifyCallSucceeds) {
uint32_t count = 0;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesDeviceEnumSchedulers(device->toHandle(), &count, NULL));
EXPECT_EQ(count, handleComponentCount);
uint32_t testcount = count + 1;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesDeviceEnumSchedulers(device->toHandle(), &testcount, NULL));
EXPECT_EQ(testcount, count);
count = 0;
std::vector<zes_sched_handle_t> handles(count, nullptr);
EXPECT_EQ(zesDeviceEnumSchedulers(device->toHandle(), &count, handles.data()), ZE_RESULT_SUCCESS);
EXPECT_EQ(count, handleComponentCount);
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetCurrentModeThenVerifyzesSchedulerGetCurrentModeCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
auto mode = fixtureGetCurrentMode(handle);
EXPECT_EQ(mode, ZES_SCHED_MODE_TIMESLICE);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimeoutModePropertiesThenVerifyzesSchedulerGetTimeoutModePropertiesCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
auto config = fixtureGetTimeoutModeProperties(handle, false);
EXPECT_EQ(config.watchdogTimeout, expectedHeartbeatTimeoutMicroSecs);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimeoutModePropertiesWithDefaultsThenVerifyzesSchedulerGetTimeoutModePropertiesCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
auto config = fixtureGetTimeoutModeProperties(handle, true);
EXPECT_EQ(config.watchdogTimeout, expectedDefaultHeartbeatTimeoutMicroSecs);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimesliceModePropertiesThenVerifyzesSchedulerGetTimesliceModePropertiesCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
auto config = fixtureGetTimesliceModeProperties(handle, false);
EXPECT_EQ(config.interval, expectedTimesliceMicroSecs);
EXPECT_EQ(config.yieldTimeout, expectedTimeoutMicroSecs);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimesliceModePropertiesWithDefaultsThenVerifyzesSchedulerGetTimesliceModePropertiesCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
auto config = fixtureGetTimesliceModeProperties(handle, true);
EXPECT_EQ(config.interval, expectedDefaultTimesliceMicroSecs);
EXPECT_EQ(config.yieldTimeout, expectedDefaultTimeoutMicroSecs);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerSetTimeoutModeThenVerifyzesSchedulerSetTimeoutModeCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
ze_bool_t needReboot;
zes_sched_timeout_properties_t setConfig;
setConfig.watchdogTimeout = 10000u;
ze_result_t result = zesSchedulerSetTimeoutMode(handle, &setConfig, &needReboot);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
EXPECT_FALSE(needReboot);
auto getConfig = fixtureGetTimeoutModeProperties(handle, false);
EXPECT_EQ(getConfig.watchdogTimeout, setConfig.watchdogTimeout);
auto mode = fixtureGetCurrentMode(handle);
EXPECT_EQ(mode, ZES_SCHED_MODE_TIMEOUT);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerSetTimesliceModeThenVerifyzesSchedulerSetTimesliceModeCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
ze_bool_t needReboot;
zes_sched_timeslice_properties_t setConfig;
setConfig.interval = 1000u;
setConfig.yieldTimeout = 1000u;
ze_result_t result = zesSchedulerSetTimesliceMode(handle, &setConfig, &needReboot);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
EXPECT_FALSE(needReboot);
auto getConfig = fixtureGetTimesliceModeProperties(handle, false);
EXPECT_EQ(getConfig.interval, setConfig.interval);
EXPECT_EQ(getConfig.yieldTimeout, setConfig.yieldTimeout);
auto mode = fixtureGetCurrentMode(handle);
EXPECT_EQ(mode, ZES_SCHED_MODE_TIMESLICE);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerSetExclusiveModeThenVerifyzesSchedulerSetExclusiveModeCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
ze_bool_t needReboot;
ze_result_t result = zesSchedulerSetExclusiveMode(handle, &needReboot);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
EXPECT_FALSE(needReboot);
auto mode = fixtureGetCurrentMode(handle);
EXPECT_EQ(mode, ZES_SCHED_MODE_EXCLUSIVE);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetCurrentModeWhenSysfsNodeIsAbsentThenFailureIsReturned) {
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getValForError));
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
zes_sched_mode_t mode;
ze_result_t result = zesSchedulerGetCurrentMode(handle, &mode);
EXPECT_EQ(ZE_RESULT_ERROR_NOT_AVAILABLE, result);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimeoutModePropertiesWithDefaultsWhenSysfsNodeIsAbsentThenFailureIsReturned) {
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getValForError));
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
zes_sched_timeout_properties_t config;
ze_result_t result = zesSchedulerGetTimeoutModeProperties(handle, true, &config);
EXPECT_EQ(ZE_RESULT_ERROR_NOT_AVAILABLE, result);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetTimesliceModePropertiesWithDefaultsWhenSysfsNodeIsAbsentThenFailureIsReturned) {
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<SchedulerSysfsAccess>::getValForError));
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
zes_sched_timeslice_properties_t config;
ze_result_t result = zesSchedulerGetTimesliceModeProperties(handle, true, &config);
EXPECT_EQ(ZE_RESULT_ERROR_NOT_AVAILABLE, result);
}
}
TEST_F(SysmanDeviceSchedulerFixture, GivenValidDeviceHandleWhenCallingzesSchedulerGetPropertiesThenVerifyzesSchedulerGetPropertiesCallSucceeds) {
auto handles = get_sched_handles(handleComponentCount);
for (auto handle : handles) {
zes_sched_properties_t properties = {};
ze_result_t result = zesSchedulerGetProperties(handle, &properties);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
EXPECT_TRUE(properties.canControl);
EXPECT_EQ(properties.engines, ZES_ENGINE_TYPE_FLAG_COMPUTE);
EXPECT_EQ(properties.supportedModes, static_cast<uint32_t>((1 << ZES_SCHED_MODE_TIMEOUT) | (1 << ZES_SCHED_MODE_TIMESLICE) | (1 << ZES_SCHED_MODE_EXCLUSIVE)));
}
}
} // namespace ult
} // namespace L0 | 49.643725 | 183 | 0.779318 | [
"vector"
] |
e90289cb8fa6517bb95069fa4110992cb8d155c6 | 8,501 | cpp | C++ | TemporalTreeMaps/modules/temporaltreemaps/src/processors/treeordercomputationgreedy.cpp | marcus1337/InviwoTemporalTreeMapsMOD | 0d6a235ac2aa1d106de227b6d8513eb8fc91295e | [
"MIT"
] | null | null | null | TemporalTreeMaps/modules/temporaltreemaps/src/processors/treeordercomputationgreedy.cpp | marcus1337/InviwoTemporalTreeMapsMOD | 0d6a235ac2aa1d106de227b6d8513eb8fc91295e | [
"MIT"
] | null | null | null | TemporalTreeMaps/modules/temporaltreemaps/src/processors/treeordercomputationgreedy.cpp | marcus1337/InviwoTemporalTreeMapsMOD | 0d6a235ac2aa1d106de227b6d8513eb8fc91295e | [
"MIT"
] | null | null | null | /*********************************************************************
* Author : Tino Weinkauf and Wiebke Koepp
* Init : Thursday, March 29, 2018 - 15:00:03
*
* Project : KTH Inviwo Modules
*
* License : Follows the Inviwo BSD license model
*********************************************************************
*/
#include <modules/temporaltreemaps/processors/treeordercomputationgreedy.h>
#include <modules/temporaltreemaps/processors/treeordercomputationheuristic.h>
namespace inviwo
{
namespace kth
{
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TemporalTreeOrderComputationGreedy::processorInfo_
{
"org.inviwo.TemporalTreeOrderComputationGreedy", // Class identifier
"Tree Order Computation Greedy", // Display name
"Temporal Tree", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo TemporalTreeOrderComputationGreedy::getProcessorInfo() const
{
return processorInfo_;
}
TemporalTreeOrderComputationGreedy::TemporalTreeOrderComputationGreedy() :TemporalTreeOrderOptimization()
{
/* Constrols */
propRestart.onChange([&]()
{
if (!initialized)
{
initializeResources();
}
else
{
restart();
}
updateOutput();
});
propSingleStep.onChange([&]()
{
if (!initialized) initializeResources();
performanceTimer.Reset();
singleStep();
propTimeForLastAction.set(performanceTimer.ElapsedTimeAndReset());
updateOutput();
});
runTimer.setCallback([this]()
{
if (!initialized) initializeResources();
singleStep();
// Stop timer and performance timer when we have converged
if (isConverged())
{
propTimeForLastAction.set(performanceTimer.ElapsedTimeAndReset());
runTimer.stop();
propRunStepWise.setDisplayName("Run Stepwise");
}
updateOutput();
});
propRunUntilConvergence.onChange([&]()
{
if (!initialized || currentState.iteration != 0) initializeResources();
restart();
performanceTimer.Reset();
runUntilConvergence();
propTimeForLastAction.set(performanceTimer.ElapsedTimeAndReset());
if (propSaveLog) {
saveLog();
}
updateOutput();
});
logPrefix = "greedy";
}
void TemporalTreeOrderComputationGreedy::resolveConstraint()
{
// best solution Ids, constraint first,
std::vector<std::pair<size_t, size_t>> bestIds;
double bestValue = std::numeric_limits<double>::max();
for (auto& constraintId : unfulfilledConstraints)
{
Constraint& constraint = constraints[constraintId];
size_t minOrder;
size_t maxOrder;
TemporalTree::TTreeOrder conflictingLeaves;
TemporalTree::TTreeOrder nonConflictingAndConstraintLeaves;
TemporalTreeOrderComputationHeuristic::findConflictingLeaves(pInputTree, constraint, currentState.order, minOrder, maxOrder, conflictingLeaves, nonConflictingAndConstraintLeaves);
TemporalTree::TTreeOrder temporaryOrder;
ConstraintsStatistic temporaryStatistics;
for (int numConflictBefore(int(conflictingLeaves.size())); numConflictBefore >= 0; numConflictBefore--)
{
TemporalTreeOrderComputationHeuristic::buildNewOrder(temporaryOrder, currentState.order, numConflictBefore, conflictingLeaves, nonConflictingAndConstraintLeaves, minOrder, maxOrder);
double newValue = evaluateOrder(temporaryOrder, &temporaryStatistics);
// The new value is the same as best
if (std::abs(bestValue - newValue) < std::numeric_limits<double>::epsilon())
{
bestIds.emplace_back(constraintId, numConflictBefore);
}
// The new value is better than the best so far
else if (newValue < bestValue)
{
bestIds.clear();
bestIds.emplace_back(constraintId, numConflictBefore);
bestValue = newValue;
}
}
}
std::uniform_int_distribution<int> chooseSolution (0, static_cast<int>(bestIds.size()-1));
size_t solutionId = chooseSolution(randomGen);
std::pair<size_t, size_t> solution = bestIds[solutionId];
size_t minOrder;
size_t maxOrder;
TemporalTree::TTreeOrder conflictingLeaves;
TemporalTree::TTreeOrder nonConflictingAndConstraintLeaves;
TemporalTreeOrderComputationHeuristic::findConflictingLeaves(pInputTree, constraints[solution.first], currentState.order, minOrder, maxOrder, conflictingLeaves, nonConflictingAndConstraintLeaves);
TemporalTree::TTreeOrder temporaryOrder;
TemporalTreeOrderComputationHeuristic::buildNewOrder(temporaryOrder, currentState.order, solution.second, conflictingLeaves, nonConflictingAndConstraintLeaves, minOrder, maxOrder);
currentState.order = temporaryOrder;
currentState.statistic.clear();
currentState.value = evaluateOrder(currentState.order, ¤tState.statistic);
}
void TemporalTreeOrderComputationGreedy::initializeResources()
{
TemporalTreeOrderOptimization::initializeResources();
initialized = true;
restart();
}
void TemporalTreeOrderComputationGreedy::restart()
{
TemporalTreeOrderOptimization::restart();
prepareNextStep();
bestState = currentState;
logStep();
}
bool TemporalTreeOrderComputationGreedy::isConverged()
{
// the iteration number is an index starting at 0, the max is a number >= -1
if (currentState.iteration > propIterationsMax - 1)
{
LogProcessorInfo("Converged by reaching maximum number of iterations.");
return true;
}
if (std::abs(currentState.value) < std::numeric_limits<float>::epsilon())
{
LogProcessorInfo("Converged by reaching a global optimum.");
return true;
}
if (unfulfilledConstraints.size() == 0)
{
LogProcessorInfo("Converged by no more constraints to fulfill");
return true;
}
return false;
}
void TemporalTreeOrderComputationGreedy::singleStep()
{
// Go through the queue until we have reached the maximum iterations or found a constraint to resolve
if (!isConverged())
{
resolveConstraint();
currentState.iteration++;
logStep();
if (currentState.value < bestState.value)
{
bestState = currentState;
}
prepareNextStep();
}
}
void TemporalTreeOrderComputationGreedy::runUntilConvergence()
{
while (!isConverged())
{
resolveConstraint();
currentState.iteration++;
logStep();
if (currentState.value < bestState.value)
{
propTimeUntilBest.set(performanceTimer.ElapsedTime());
bestState = currentState;
}
prepareNextStep();
}
}
void TemporalTreeOrderComputationGreedy::prepareNextStep()
{
unfulfilledConstraints.clear();
size_t constraintId(0);
for (auto& constraint : constraints)
{
if (!constraint.fulfilled)
{
unfulfilledConstraints.push_back(constraintId);
}
constraintId++;
}
}
void TemporalTreeOrderComputationGreedy::logStep()
{
TemporalTreeOrderOptimization::logStep();
}
void TemporalTreeOrderComputationGreedy::initializeLog()
{
TemporalTreeOrderOptimization::initializeLog();
}
void TemporalTreeOrderComputationGreedy::logProperties()
{
const std::vector<std::string> colHeaders{
propSeedOrder.getDisplayName(),
propSeedOptimization.getDisplayName(),
propIterationsMax.getDisplayName(),
propWeightByTypeOnly.getDisplayName(),
propWeightTypeOnly.getDisplayName(),
propBestIteration.getDisplayName(),
propObjectiveValue.getDisplayName(),
propTimeUntilBest.getDisplayName(),
propTimeForLastAction.getDisplayName() };
const std::vector<std::string> exampleRow{
std::to_string(propSeedOrder),
std::to_string(propSeedOptimization),
std::to_string(propIterationsMax),
std::to_string(propWeightByTypeOnly),
std::to_string(propWeightTypeOnly),
std::to_string(bestState.iteration),
std::to_string(bestState.value),
std::to_string(propTimeUntilBest),
std::to_string(propTimeForLastAction) };
optimizationSettings = createDataFrame({ exampleRow }, colHeaders);
optimizationSettings->addRow(exampleRow);
}
void TemporalTreeOrderComputationGreedy::process()
{
// Do nothing
}
} // namespace
} // namespace
| 29.723776 | 200 | 0.684272 | [
"vector",
"model"
] |
e905a76705b3319d0eff0427d82a05a7005e28a5 | 3,539 | cpp | C++ | src/conv/raw/raw-g.cpp | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/conv/raw/raw-g.cpp | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/conv/raw/raw-g.cpp | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* R A W - G . C P P
* BRL-CAD
*
* Copyright (c) 2012-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* 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 file; see the file named COPYING for more
* information.
*/
/** @file raw-g.cpp
*
* RAW geometry file to BRL-CAD converter:
* main function
*
* Origin -
* IABG mbH (Germany)
*/
#include "common.h"
#include <cassert>
#include "RegionList.h"
static std::vector<std::string> readLine(std::istream& is)
{
std::vector<std::string> ret;
std::string temp;
for (;;) {
if (!is)
break;
char a;
is.get(a);
if (a == '\n') {
if (temp.size() > 0) {
ret.push_back(temp);
temp.clear();
}
break;
}
if ((a == ' ') || (a == '\t') || (a == '\r')) {
if (temp.size() > 0) {
ret.push_back(temp);
temp.clear();
}
}
else
temp += a;
}
return ret;
}
static inline void
getPoint(const std::string &x, const std::string &y, const std::string &z, point_t& point) {
point[X] = toValue(x.c_str());
point[Y] = toValue(y.c_str());
point[Z] = toValue(z.c_str());
}
int main(int argc,
char* argv[])
{
int ret = 0;
RegionList regions;
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " <RAW file> <BRL-CAD file>" << std::endl;
ret = 1;
}
else {
std::ifstream is(argv[1]);
if (!is.is_open()) {
std::cout << "Error reading RAW file" << std::endl;
ret = 1;
}
else {
struct rt_wdb* wdbp = wdb_fopen(argv[2]);
std::string title = "Converted from ";
title += argv[1];
mk_id(wdbp, title.c_str());
std::vector<std::string> nameLine = readLine(is);
while (is && !is.eof()) {
if (nameLine.size() == 0) {
nameLine = readLine(is);
continue;
}
std::cout << "Read: " << nameLine[0].c_str() << '\n';
assert(nameLine[0].size() > 0);
Bot& bot = regions.addRegion(nameLine[0]);
if (nameLine.size() > 1) {
size_t thicknessIndex = nameLine[1].find("thickf=");
if (thicknessIndex != std::string::npos) {
std::string thickf = nameLine[1].substr(thicknessIndex + 7);
if (thickf.size() > 0) {
fastf_t val = toValue(thickf.c_str());
bot.setThickness(val);
} else {
std::cout << "Missing thickness in " << nameLine[0].c_str() << '\n';
}
}
}
std::vector<std::string> triangleLine = readLine(is);
while (is && (triangleLine.size() == 9)) {
point_t p;
getPoint(triangleLine[0], triangleLine[1], triangleLine[2], p);
size_t a = bot.addPoint(p);
getPoint(triangleLine[3], triangleLine[4], triangleLine[5], p);
size_t b = bot.addPoint(p);
getPoint(triangleLine[6], triangleLine[7], triangleLine[8], p);
size_t c = bot.addPoint(p);
bot.addTriangle(a, b, c);
triangleLine = readLine(is);
}
nameLine = triangleLine;
}
regions.create(wdbp);
wdb_close(wdbp);
}
}
regions.printStat();
return ret;
}
| 22.11875 | 92 | 0.584628 | [
"cad",
"geometry",
"vector"
] |
e905b5bfc66edd1e8fc1e2c06502c0596aba7a42 | 10,385 | cpp | C++ | Source/ThirdParty/Assimp/code/FBXAnimation.cpp | dev-plvlml/Urho3D | 1420410edd585bf6d566229e824b381680372004 | [
"MIT"
] | 9 | 2020-06-09T20:43:35.000Z | 2022-02-23T17:45:44.000Z | Source/ThirdParty/Assimp/code/FBXAnimation.cpp | dev-plvlml/Urho3D | 1420410edd585bf6d566229e824b381680372004 | [
"MIT"
] | 4 | 2020-12-13T18:27:41.000Z | 2021-03-22T19:12:57.000Z | Source/ThirdParty/Assimp/code/FBXAnimation.cpp | dev-plvlml/Urho3D | 1420410edd585bf6d566229e824b381680372004 | [
"MIT"
] | 6 | 2021-04-11T22:04:13.000Z | 2021-11-23T22:58:39.000Z | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
----------------------------------------------------------------------
*/
/** @file FBXAnimation.cpp
* @brief Assimp::FBX::AnimationCurve, Assimp::FBX::AnimationCurveNode,
* Assimp::FBX::AnimationLayer, Assimp::FBX::AnimationStack
*/
#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
#include "FBXParser.h"
#include "FBXDocument.h"
#include "FBXImporter.h"
#include "FBXDocumentUtil.h"
namespace Assimp {
namespace FBX {
using namespace Util;
// ------------------------------------------------------------------------------------------------
AnimationCurve::AnimationCurve(uint64_t id, const Element& element, const std::string& name, const Document& /*doc*/)
: Object(id, element, name)
{
const Scope& sc = GetRequiredScope(element);
const Element& KeyTime = GetRequiredElement(sc,"KeyTime");
const Element& KeyValueFloat = GetRequiredElement(sc,"KeyValueFloat");
ParseVectorDataArray(keys, KeyTime);
ParseVectorDataArray(values, KeyValueFloat);
if(keys.size() != values.size()) {
DOMError("the number of key times does not match the number of keyframe values",&KeyTime);
}
// check if the key times are well-ordered
if(!std::equal(keys.begin(), keys.end() - 1, keys.begin() + 1, std::less<KeyTimeList::value_type>())) {
DOMError("the keyframes are not in ascending order",&KeyTime);
}
const Element* KeyAttrDataFloat = sc["KeyAttrDataFloat"];
if(KeyAttrDataFloat) {
ParseVectorDataArray(attributes, *KeyAttrDataFloat);
}
const Element* KeyAttrFlags = sc["KeyAttrFlags"];
if(KeyAttrFlags) {
ParseVectorDataArray(flags, *KeyAttrFlags);
}
}
// ------------------------------------------------------------------------------------------------
AnimationCurve::~AnimationCurve()
{
}
// ------------------------------------------------------------------------------------------------
AnimationCurveNode::AnimationCurveNode(uint64_t id, const Element& element, const std::string& name, const Document& doc,
const char* const * target_prop_whitelist /*= NULL*/, size_t whitelist_size /*= 0*/)
: Object(id, element, name)
, target()
, doc(doc)
{
const Scope& sc = GetRequiredScope(element);
// find target node
const char* whitelist[] = {"Model","NodeAttribute"};
const std::vector<const Connection*>& conns = doc.GetConnectionsBySourceSequenced(ID(),whitelist,2);
for(const Connection* con : conns) {
// link should go for a property
if (!con->PropertyName().length()) {
continue;
}
if(target_prop_whitelist) {
const char* const s = con->PropertyName().c_str();
bool ok = false;
for (size_t i = 0; i < whitelist_size; ++i) {
if (!strcmp(s, target_prop_whitelist[i])) {
ok = true;
break;
}
}
if (!ok) {
throw std::range_error("AnimationCurveNode target property is not in whitelist");
}
}
const Object* const ob = con->DestinationObject();
if(!ob) {
DOMWarning("failed to read destination object for AnimationCurveNode->Model link, ignoring",&element);
continue;
}
// XXX support constraints as DOM class
//ai_assert(dynamic_cast<const Model*>(ob) || dynamic_cast<const NodeAttribute*>(ob));
target = ob;
if(!target) {
continue;
}
prop = con->PropertyName();
break;
}
if(!target) {
DOMWarning("failed to resolve target Model/NodeAttribute/Constraint for AnimationCurveNode",&element);
}
props = GetPropertyTable(doc,"AnimationCurveNode.FbxAnimCurveNode",element,sc,false);
}
// ------------------------------------------------------------------------------------------------
AnimationCurveNode::~AnimationCurveNode()
{
}
// ------------------------------------------------------------------------------------------------
const AnimationCurveMap& AnimationCurveNode::Curves() const
{
if(curves.empty()) {
// resolve attached animation curves
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurve");
for(const Connection* con : conns) {
// link should go for a property
if (!con->PropertyName().length()) {
continue;
}
const Object* const ob = con->SourceObject();
if(!ob) {
DOMWarning("failed to read source object for AnimationCurve->AnimationCurveNode link, ignoring",&element);
continue;
}
const AnimationCurve* const anim = dynamic_cast<const AnimationCurve*>(ob);
if(!anim) {
DOMWarning("source object for ->AnimationCurveNode link is not an AnimationCurve",&element);
continue;
}
curves[con->PropertyName()] = anim;
}
}
return curves;
}
// ------------------------------------------------------------------------------------------------
AnimationLayer::AnimationLayer(uint64_t id, const Element& element, const std::string& name, const Document& doc)
: Object(id, element, name)
, doc(doc)
{
const Scope& sc = GetRequiredScope(element);
// note: the props table here bears little importance and is usually absent
props = GetPropertyTable(doc,"AnimationLayer.FbxAnimLayer",element,sc, true);
}
// ------------------------------------------------------------------------------------------------
AnimationLayer::~AnimationLayer()
{
}
// ------------------------------------------------------------------------------------------------
AnimationCurveNodeList AnimationLayer::Nodes(const char* const * target_prop_whitelist /*= NULL*/,
size_t whitelist_size /*= 0*/) const
{
AnimationCurveNodeList nodes;
// resolve attached animation nodes
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurveNode");
nodes.reserve(conns.size());
for(const Connection* con : conns) {
// link should not go to a property
if (con->PropertyName().length()) {
continue;
}
const Object* const ob = con->SourceObject();
if(!ob) {
DOMWarning("failed to read source object for AnimationCurveNode->AnimationLayer link, ignoring",&element);
continue;
}
const AnimationCurveNode* const anim = dynamic_cast<const AnimationCurveNode*>(ob);
if(!anim) {
DOMWarning("source object for ->AnimationLayer link is not an AnimationCurveNode",&element);
continue;
}
if(target_prop_whitelist) {
const char* s = anim->TargetProperty().c_str();
bool ok = false;
for (size_t i = 0; i < whitelist_size; ++i) {
if (!strcmp(s, target_prop_whitelist[i])) {
ok = true;
break;
}
}
if(!ok) {
continue;
}
}
nodes.push_back(anim);
}
return nodes; // pray for NRVO
}
// ------------------------------------------------------------------------------------------------
AnimationStack::AnimationStack(uint64_t id, const Element& element, const std::string& name, const Document& doc)
: Object(id, element, name)
{
const Scope& sc = GetRequiredScope(element);
// note: we don't currently use any of these properties so we shouldn't bother if it is missing
props = GetPropertyTable(doc,"AnimationStack.FbxAnimStack",element,sc, true);
// resolve attached animation layers
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationLayer");
layers.reserve(conns.size());
for(const Connection* con : conns) {
// link should not go to a property
if (con->PropertyName().length()) {
continue;
}
const Object* const ob = con->SourceObject();
if(!ob) {
DOMWarning("failed to read source object for AnimationLayer->AnimationStack link, ignoring",&element);
continue;
}
const AnimationLayer* const anim = dynamic_cast<const AnimationLayer*>(ob);
if(!anim) {
DOMWarning("source object for ->AnimationStack link is not an AnimationLayer",&element);
continue;
}
layers.push_back(anim);
}
}
// ------------------------------------------------------------------------------------------------
AnimationStack::~AnimationStack()
{
}
} //!FBX
} //!Assimp
#endif
| 33.285256 | 122 | 0.579104 | [
"object",
"vector",
"model"
] |
e906acd61ad75a643e900810eb3c593c3b1d90a4 | 7,974 | cpp | C++ | src/core/SkWriteBuffer.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 3 | 2020-08-06T00:31:13.000Z | 2021-07-29T07:28:17.000Z | src/core/SkWriteBuffer.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 3 | 2020-04-26T17:03:31.000Z | 2020-04-28T14:55:33.000Z | src/core/SkWriteBuffer.cpp | pospx/external_skia | 7a135275c9fc2a4b3cbdcf9a96e7102724752234 | [
"BSD-3-Clause"
] | 57 | 2016-12-29T02:00:25.000Z | 2021-11-16T01:22:50.000Z | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkWriteBuffer.h"
#include "SkBitmap.h"
#include "SkData.h"
#include "SkImagePriv.h"
#include "SkPaintPriv.h"
#include "SkPtrRecorder.h"
#include "SkStream.h"
#include "SkTo.h"
#include "SkTypeface.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
SkBinaryWriteBuffer::SkBinaryWriteBuffer()
: fFactorySet(nullptr)
, fTFSet(nullptr) {
}
SkBinaryWriteBuffer::SkBinaryWriteBuffer(void* storage, size_t storageSize)
: fFactorySet(nullptr)
, fTFSet(nullptr)
, fWriter(storage, storageSize)
{}
SkBinaryWriteBuffer::~SkBinaryWriteBuffer() {}
bool SkBinaryWriteBuffer::usingInitialStorage() const {
return fWriter.usingInitialStorage();
}
void SkBinaryWriteBuffer::writeByteArray(const void* data, size_t size) {
fWriter.write32(SkToU32(size));
fWriter.writePad(data, size);
}
void SkBinaryWriteBuffer::writeBool(bool value) {
fWriter.writeBool(value);
}
void SkBinaryWriteBuffer::writeScalar(SkScalar value) {
fWriter.writeScalar(value);
}
void SkBinaryWriteBuffer::writeScalarArray(const SkScalar* value, uint32_t count) {
fWriter.write32(count);
fWriter.write(value, count * sizeof(SkScalar));
}
void SkBinaryWriteBuffer::writeInt(int32_t value) {
fWriter.write32(value);
}
void SkBinaryWriteBuffer::writeIntArray(const int32_t* value, uint32_t count) {
fWriter.write32(count);
fWriter.write(value, count * sizeof(int32_t));
}
void SkBinaryWriteBuffer::writeUInt(uint32_t value) {
fWriter.write32(value);
}
void SkBinaryWriteBuffer::writeString(const char* value) {
fWriter.writeString(value);
}
void SkBinaryWriteBuffer::writeColor(SkColor color) {
fWriter.write32(color);
}
void SkBinaryWriteBuffer::writeColorArray(const SkColor* color, uint32_t count) {
fWriter.write32(count);
fWriter.write(color, count * sizeof(SkColor));
}
void SkBinaryWriteBuffer::writeColor4f(const SkColor4f& color) {
fWriter.write(&color, sizeof(SkColor4f));
}
void SkBinaryWriteBuffer::writeColor4fArray(const SkColor4f* color, uint32_t count) {
fWriter.write32(count);
fWriter.write(color, count * sizeof(SkColor4f));
}
void SkBinaryWriteBuffer::writePoint(const SkPoint& point) {
fWriter.writeScalar(point.fX);
fWriter.writeScalar(point.fY);
}
void SkBinaryWriteBuffer::writePoint3(const SkPoint3& point) {
this->writePad32(&point, sizeof(SkPoint3));
}
void SkBinaryWriteBuffer::writePointArray(const SkPoint* point, uint32_t count) {
fWriter.write32(count);
fWriter.write(point, count * sizeof(SkPoint));
}
void SkBinaryWriteBuffer::writeMatrix(const SkMatrix& matrix) {
fWriter.writeMatrix(matrix);
}
void SkBinaryWriteBuffer::writeIRect(const SkIRect& rect) {
fWriter.write(&rect, sizeof(SkIRect));
}
void SkBinaryWriteBuffer::writeRect(const SkRect& rect) {
fWriter.writeRect(rect);
}
void SkBinaryWriteBuffer::writeRegion(const SkRegion& region) {
fWriter.writeRegion(region);
}
void SkBinaryWriteBuffer::writePath(const SkPath& path) {
fWriter.writePath(path);
}
size_t SkBinaryWriteBuffer::writeStream(SkStream* stream, size_t length) {
fWriter.write32(SkToU32(length));
size_t bytesWritten = fWriter.readFromStream(stream, length);
if (bytesWritten < length) {
fWriter.reservePad(length - bytesWritten);
}
return bytesWritten;
}
bool SkBinaryWriteBuffer::writeToStream(SkWStream* stream) const {
return fWriter.writeToStream(stream);
}
/* Format:
* (subset) bounds
* size (31bits)
* data [ encoded, with raw width/height ]
*/
void SkBinaryWriteBuffer::writeImage(const SkImage* image) {
const SkIRect bounds = SkImage_getSubset(image);
this->writeIRect(bounds);
sk_sp<SkData> data;
if (fProcs.fImageProc) {
data = fProcs.fImageProc(const_cast<SkImage*>(image), fProcs.fImageCtx);
}
if (!data) {
data = image->encodeToData();
}
size_t size = data ? data->size() : 0;
if (!SkTFitsIn<int32_t>(size)) {
size = 0; // too big to store
}
this->write32(SkToS32(size)); // writing 0 signals failure
if (size) {
this->writePad32(data->data(), size);
}
}
void SkBinaryWriteBuffer::writeTypeface(SkTypeface* obj) {
// Write 32 bits (signed)
// 0 -- default font
// >0 -- index
// <0 -- custom (serial procs)
if (obj == nullptr) {
fWriter.write32(0);
} else if (fProcs.fTypefaceProc) {
auto data = fProcs.fTypefaceProc(obj, fProcs.fTypefaceCtx);
if (data) {
size_t size = data->size();
if (!SkTFitsIn<int32_t>(size)) {
size = 0; // fall back to default font
}
int32_t ssize = SkToS32(size);
fWriter.write32(-ssize); // negative to signal custom
if (size) {
this->writePad32(data->data(), size);
}
return;
}
// no data means fall through for std behavior
}
fWriter.write32(fTFSet ? fTFSet->add(obj) : 0);
}
void SkBinaryWriteBuffer::writePaint(const SkPaint& paint) {
SkPaintPriv::Flatten(paint, *this);
}
void SkBinaryWriteBuffer::setFactoryRecorder(sk_sp<SkFactorySet> rec) {
fFactorySet = std::move(rec);
}
void SkBinaryWriteBuffer::setTypefaceRecorder(sk_sp<SkRefCntSet> rec) {
fTFSet = std::move(rec);
}
void SkBinaryWriteBuffer::writeFlattenable(const SkFlattenable* flattenable) {
if (nullptr == flattenable) {
this->write32(0);
return;
}
/*
* We can write 1 of 2 versions of the flattenable:
* 1. index into fFactorySet : This assumes the writer will later
* resolve the function-ptrs into strings for its reader. SkPicture
* does exactly this, by writing a table of names (matching the indices)
* up front in its serialized form.
* 2. string name of the flattenable or index into fFlattenableDict: We
* store the string to allow the reader to specify its own factories
* after write time. In order to improve compression, if we have
* already written the string, we write its index instead.
*/
SkFlattenable::Factory factory = flattenable->getFactory();
SkASSERT(factory);
if (fFactorySet) {
this->write32(fFactorySet->add(factory));
} else {
if (uint32_t* indexPtr = fFlattenableDict.find(factory)) {
// We will write the index as a 32-bit int. We want the first byte
// that we send to be zero - this will act as a sentinel that we
// have an index (not a string). This means that we will send the
// the index shifted left by 8. The remaining 24-bits should be
// plenty to store the index. Note that this strategy depends on
// being little endian.
SkASSERT(0 == *indexPtr >> 24);
this->write32(*indexPtr << 8);
} else {
const char* name = flattenable->getTypeName();
SkASSERT(name);
// Otherwise write the string. Clients should not use the empty
// string as a name, or we will have a problem.
SkASSERT(0 != strcmp("", name));
this->writeString(name);
// Add key to dictionary.
fFlattenableDict.set(factory, fFlattenableDict.count() + 1);
}
}
// make room for the size of the flattened object
(void)fWriter.reserve(sizeof(uint32_t));
// record the current size, so we can subtract after the object writes.
size_t offset = fWriter.bytesWritten();
// now flatten the object
flattenable->flatten(*this);
size_t objSize = fWriter.bytesWritten() - offset;
// record the obj's size
fWriter.overwriteTAt(offset - sizeof(uint32_t), SkToU32(objSize));
}
| 30.551724 | 99 | 0.658515 | [
"object"
] |
e911877f9569f6df2456ad9e80f3aa7ab82651f3 | 49,661 | hpp | C++ | 3rdparty/stlsoft/include/winstl/registry/reg_key_sequence.hpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | 3rdparty/stlsoft/include/winstl/registry/reg_key_sequence.hpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | 3rdparty/stlsoft/include/winstl/registry/reg_key_sequence.hpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | /* /////////////////////////////////////////////////////////////////////////
* File: winstl/registry/reg_key_sequence.hpp
*
* Purpose: Contains the basic_reg_key_sequence class template, and ANSI
* and Unicode specialisations thereof.
*
* Notes: The original implementation of the class had the iterator
* and value_type as nested classes. Unfortunately, Visual C++ 5 &
* 6 both had either compilation or linking problems so these are
* regretably now implemented as independent classes.
*
* Thanks: To Allan McLellan, for pointing out some inadequacies in the
* basic_reg_key_sequence class interface.
*
* Created: 19th January 2002
* Updated: 10th August 2009
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2002-2009, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software nor the names of
* any 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.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file winstl/registry/reg_key_sequence.hpp
*
* \brief [C++ only] Definition of the winstl::basic_reg_key_sequence
* class template
* (\ref group__library__windows_registry "Windows Registry" Library).
*/
#ifndef WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE
#define WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define WINSTL_VER_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE_MAJOR 3
# define WINSTL_VER_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE_MINOR 9
# define WINSTL_VER_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE_REVISION 1
# define WINSTL_VER_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE_EDIT 131
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Includes
*/
#ifndef WINSTL_INCL_WINSTL_H_WINSTL
# include <winstl/winstl.h>
#endif /* !WINSTL_INCL_WINSTL_H_WINSTL */
#ifndef WINSTL_INCL_WINSTL_REGISTRY_HPP_REGFWD
# include <winstl/registry/regfwd.hpp>
#endif /* !WINSTL_INCL_WINSTL_REGISTRY_HPP_REGFWD */
#ifndef WINSTL_INCL_WINSTL_REGISTRY_UTIL_HPP_DEFS
# include <winstl/registry/util/defs.hpp>
#endif /* !WINSTL_INCL_WINSTL_REGISTRY_UTIL_HPP_DEFS */
#ifndef WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_TRAITS
# include <winstl/registry/reg_traits.hpp>
#endif /* !WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_TRAITS */
#ifndef WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_KEY
# include <winstl/registry/reg_key.hpp>
#endif /* !WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_KEY */
#ifndef WINSTL_INCL_WINSTL_REGISTRY_UTIL_HPP_SHARED_HANDLES
# include <winstl/registry/util/shared_handles.hpp>
#endif /* !WINSTL_INCL_WINSTL_REGISTRY_UTIL_HPP_SHARED_HANDLES */
#ifndef STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER
# include <stlsoft/memory/auto_buffer.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER */
#ifndef WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR
# include <winstl/memory/processheap_allocator.hpp>
#endif /* !WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR */
#ifndef STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER
# include <stlsoft/util/std/iterator_helper.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER */
#ifndef STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS
# include <stlsoft/collections/util/collections.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS */
#ifndef STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_REF_PTR
# include <stlsoft/smartptr/ref_ptr.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_REF_PTR */
#ifndef STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE
# include <stlsoft/smartptr/scoped_handle.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE */
/* /////////////////////////////////////////////////////////////////////////
* Namespace
*/
#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::winstl */
namespace winstl
{
# else
/* Define stlsoft::winstl_project */
namespace stlsoft
{
namespace winstl_project
{
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */
/* ////////////////////////////////////////////////////////////////////// */
// class basic_reg_key_sequence
/** \brief Presents an STL-like sequence interface over the sub-keys of a given registry key
*
* \ingroup group__library__windows_registry
*
* \param C The character type
* \param T The traits type. On translators that support default template arguments this defaults to reg_traits<C>
* \param A The allocator type. On translators that support default template arguments this defaults to processheap_allocator<C>
*/
template< ss_typename_param_k C
#ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT
, ss_typename_param_k T = reg_traits<C>
, ss_typename_param_k A = processheap_allocator<C>
#else /* ? STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */
, ss_typename_param_k T /* = reg_traits<C> */
, ss_typename_param_k A /* = processheap_allocator<C> */
#endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */
>
class basic_reg_key_sequence
: public stlsoft_ns_qual(stl_collection_tag)
{
/// \name Member Types
/// @{
public:
/// \brief The character type
typedef C char_type;
/// \brief The traits type
typedef T traits_type;
/// \brief The allocator type
typedef A allocator_type;
/// \brief The current parameterisation of the type
typedef basic_reg_key_sequence<C, T, A> class_type;
/// \brief The key type
typedef basic_reg_key<C, T, A> key_type;
/// \brief The value type
typedef key_type value_type;
/// \brief The size type
typedef ss_typename_type_k traits_type::size_type size_type;
/// \brief The reg key type
typedef basic_reg_key<C, T, A> reg_key_type;
/// \brief The mutating (non-const) iterator type
typedef basic_reg_key_sequence_iterator<C, T, value_type, A> iterator;
/// \brief The non-mutating (const) iterator type
///
/// \note This is retained for backwards compatibility
typedef iterator const_iterator;
/// \brief The reference type
typedef key_type& reference;
/// \brief The non-mutable (const) reference type
typedef key_type const& const_reference;
/// \brief The hkey type
#if defined(STLSOFT_COMPILER_IS_MSVC) && \
_MSC_VER == 1100
/* WSCB: VC5 has an unresolved external linker error if use traits_type::hkey_type */
typedef HKEY hkey_type;
#else /* ? compiler */
typedef ss_typename_type_k traits_type::hkey_type hkey_type;
#endif /* compiler */
/// \brief The difference type
typedef ws_ptrdiff_t difference_type;
/// \brief The non-mutating (const) reverse iterator type
#if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT)
typedef stlsoft_ns_qual(reverse_bidirectional_iterator_base) < iterator
, value_type
, value_type // By-Value Temporary reference category
, void // By-Value Temporary reference category
, difference_type
> reverse_iterator;
#endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */
/// \brief The Boolean type
typedef ws_bool_t bool_type;
private:
/// \brief The results type of the Registry API
typedef ss_typename_type_k traits_type::result_type result_type;
private:
typedef stlsoft_ns_qual(auto_buffer_old)< char_type
, allocator_type
, CCH_REG_API_AUTO_BUFFER
> buffer_type_;
public:
typedef hkey_type resource_type;
/// @}
/// \name Construction
/// @{
public:
/// \brief Creates an instance which provides access to the sub-keys of the named sub-key of \c hkey
///
/// \param hkey A registry key handle representing the parent of \c sub_key_name
/// \param sub_key_name The name of the sub-key whose sub-keys will be enumerated. If sub_key_name is NULL or the empty string, then
/// the sub-keys of \c hkey will be enumerated
/// \param accessMask The security access mask with which the key (hkey + sub_key_name) will be opened. Defaults to KEY_READ.
///
/// \note If accessMask contains KEY_NOTIFY, this method will construct a sequence whose iterators monitor for external iterator
/// invalidation. Use the alternative (four-parameter) constructor form to explicitly suppress monitoring.
basic_reg_key_sequence( hkey_type hkey
, char_type const *sub_key_name
, REGSAM accessMask = KEY_READ);
/// \brief Creates an instance which provides access to the sub-keys of the named sub-key of \c hkey
///
/// \param hkey A registry key handle representing the parent of \c sub_key_name
/// \param sub_key_name The name of the sub-key whose sub-keys will be enumerated. If sub_key_name is NULL or the empty string, then
/// the sub-keys of \c hkey will be enumerated
/// \param accessMask The security access mask with which the key (hkey + sub_key_name) will be opened. Defaults to KEY_READ
/// \param bMonitorExternalInvalidation If non-zero, the iterators will monitor for external iterator invalidation, throwing
/// an instance of registry_exception (or a derived class) when any sub-keys are added or removed
///
/// \note The bMonitorExternalInvalidation parameter overrides the accessMask parameter. i.e. if bMonitorExternalInvalidation is
/// non-zero then accessMask is combined with KEY_NOTIFY. If not, then KEY_NOTIFY is stripped from accessMask.
basic_reg_key_sequence( hkey_type hkey
, char_type const *sub_key_name
, REGSAM accessMask
, bool_type bMonitorExternalInvalidation);
/// \brief Creates an instance which provides access to the sub-keys of of \c key
///
/// \param key A registry key handle representing the parent of \c sub_key_name
///
/// \note If the key's access mask contains KEY_NOTIFY, this method will construct a sequence whose iterators monitor for external iterator
/// invalidation. Use the alternative (three-parameter) constructor form to explicitly suppress monitoring.
ss_explicit_k basic_reg_key_sequence(reg_key_type const& key);
/// \brief Creates an instance which provides access to the sub-keys of of \c key
///
/// \param key A registry key handle representing the parent of \c sub_key_name
/// \param accessMask The security access mask with which the key will be used. Defaults to KEY_READ
///
/// \note If accessMask contains KEY_NOTIFY, this method will construct a sequence whose iterators monitor for external iterator
/// invalidation. Use the alternative (three-parameter) constructor form to explicitly suppress monitoring.
basic_reg_key_sequence( reg_key_type const &key
, REGSAM accessMask);
/// \brief Creates an instance which provides access to the sub-keys of of \c key
///
/// \param key A registry key handle representing the parent of \c sub_key_name
/// \param accessMask The security access mask with which the key will be used. Defaults to KEY_READ
/// \param bMonitorExternalInvalidation If non-zero, the iterators will monitor for external iterator invalidation, throwing
/// an instance of registry_exception (or a derived class) when any sub-keys are added or removed
///
/// \note The bMonitorExternalInvalidation parameter overrides the accessMask parameter. i.e. if bMonitorExternalInvalidation is
/// non-zero then accessMask is combined with KEY_NOTIFY. If not, then KEY_NOTIFY is stripped from accessMask.
basic_reg_key_sequence( reg_key_type const &key
, REGSAM accessMask
, bool_type bMonitorExternalInvalidation);
/// \brief Destructor
~basic_reg_key_sequence() stlsoft_throw_0();
/// @}
/// \name Iteration
/// @{
public:
/// \brief Begins the iteration
///
/// \return An iterator representing the start of the sequence
iterator begin();
/// \brief Ends the iteration
///
/// \return An iterator representing the end of the sequence
iterator end();
#if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT)
/// \brief Begins the reverse iteration
///
/// \return An iterator representing the start of the reverse sequence
reverse_iterator rbegin();
/// \brief Ends the reverse iteration
///
/// \return An iterator representing the end of the reverse sequence
reverse_iterator rend();
#endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */
/// @}
/// \name Attributes
/// @{
public:
/// \brief Returns the number of sub-keys
///
/// \note This gives a result valid only at the epoch of the call. A
/// subsequent call may return a different result.
size_type current_size() const;
/// \brief Returns the number of sub-keys
///
/// \deprecated This is equivalent to current_size()
size_type size() const;
/// \brief Evalulates whether there are no sub-keys
ws_bool_t empty() const;
/// \brief The key handle
hkey_type get_key_handle() const;
/// \brief The key handle
hkey_type get() const;
/// @}
/// \name Implementation
/// @{
private:
registry_util::shared_handle *create_shared_handle_(result_type &res);
static REGSAM validate_access_mask_(REGSAM accessMask, bool_type bMonitorExternalInvalidation);
static hkey_type dup_key_(hkey_type hkey, REGSAM accessMask/* , result_type *result */);
/// @}
/// \name Members
/// @{
private:
hkey_type m_hkey;
const REGSAM m_accessMask;
const bool_type m_bMonitorExternalInvalidation;
/// @}
/// \name Not to be implemented
/// @{
private:
basic_reg_key_sequence(class_type const&);
class_type& operator =(class_type const&);
/// @}
};
/* Typedefs to commonly encountered types. */
/** \brief Specialisation of the basic_reg_key_sequence template for the ANSI character type \c char
*
* \ingroup group__library__windows_registry
*/
typedef basic_reg_key_sequence<ws_char_a_t, reg_traits<ws_char_a_t>, processheap_allocator<ws_char_a_t> > reg_key_sequence_a;
/** \brief Specialisation of the basic_reg_key_sequence template for the Unicode character type \c wchar_t
*
* \ingroup group__library__windows_registry
*/
typedef basic_reg_key_sequence<ws_char_w_t, reg_traits<ws_char_w_t>, processheap_allocator<ws_char_w_t> > reg_key_sequence_w;
/** \brief Specialisation of the basic_reg_key_sequence template for the Win32 character type \c TCHAR
*
* \ingroup group__library__windows_registry
*/
typedef basic_reg_key_sequence<TCHAR, reg_traits<TCHAR>, processheap_allocator<TCHAR> > reg_key_sequence;
// class basic_reg_key_sequence_iterator
/** \brief Iterator for the basic_reg_key_sequence class
*
* \ingroup group__library__windows_registry
*
* \param C The character type
* \param T The traits type
* \param V The value type
* \param A The allocator type
*/
template< ss_typename_param_k C
, ss_typename_param_k T
, ss_typename_param_k V
, ss_typename_param_k A
>
class basic_reg_key_sequence_iterator
: public stlsoft_ns_qual(iterator_base)<winstl_ns_qual_std(bidirectional_iterator_tag)
, V
, ws_ptrdiff_t
, void // By-Value Temporary reference
, V // By-Value Temporary reference
>
{
/// \name Member Types
/// @{
public:
/// \brief The character type
typedef C char_type;
/// \brief The traits type
typedef T traits_type;
/// \brief The value type
typedef V value_type;
/// \brief The allocator type
typedef A allocator_type;
/// \brief The current parameterisation of the type
typedef basic_reg_key_sequence_iterator<C, T, V, A> class_type;
/// \brief The size type
typedef ss_typename_type_k traits_type::size_type size_type;
/// \brief The difference type
typedef ss_typename_type_k traits_type::difference_type difference_type;
/// \brief The string type
typedef ss_typename_type_k traits_type::string_type string_type;
/// \brief The index type
typedef ws_sint32_t index_type;
/// \brief The hkey type
typedef ss_typename_type_k traits_type::hkey_type hkey_type;
private:
/// \brief The results type of the Registry API
typedef ss_typename_type_k traits_type::result_type result_type;
/// \brief The Boolean type
typedef ws_bool_t bool_type;
private:
typedef stlsoft_ns_qual(auto_buffer_old)< char_type
, allocator_type
, CCH_REG_API_AUTO_BUFFER
> buffer_type_;
/// @}
/// \name Construction
/// @{
private:
friend class basic_reg_key_sequence<C, T, A>;
/// \note Eats the key, rather than taking a copy
basic_reg_key_sequence_iterator(registry_util::shared_handle *handle, char_type const* name, size_type cchName, index_type index, REGSAM accessMask)
: m_handle(handle)
, m_index(index)
, m_name(name, cchName)
, m_accessMask(accessMask)
{
WINSTL_ASSERT(NULL != m_handle);
m_handle->test_reset_and_throw();
m_handle->AddRef();
}
public:
/// \brief Default constructor
basic_reg_key_sequence_iterator();
/// \brief Copy constructor
basic_reg_key_sequence_iterator(class_type const& rhs);
/// \brief Destructor
~basic_reg_key_sequence_iterator() stlsoft_throw_0();
/// \brief Copy assignment operator
class_type& operator =(class_type const& rhs);
/// @}
/// \name Accessors
/// @{
public:
string_type const &get_key_name() const;
/// @}
/// \name Operators
/// @{
public:
/// \brief Pre-increment operator
class_type& operator ++();
/// \brief Pre-decrement operator
class_type& operator --();
/// \brief Post-increment operator
const class_type operator ++(int);
/// \brief Post-decrement operator
const class_type operator --(int);
/// \brief Dereference to return the value representing the current position
const value_type operator *() const;
/// \brief Evaluates whether \c this and \c rhs are equivalent
ws_bool_t equal(class_type const& rhs) const;
/// \brief Evaluates whether \c this and \c rhs are equivalent
ws_bool_t operator ==(class_type const& rhs) const;
/// \brief Evaluates whether \c this and \c rhs are not equivalent
ws_bool_t operator !=(class_type const& rhs) const;
/// @}
/// \name Implementation
/// @{
private:
static index_type sentinel_() stlsoft_throw_0();
/// @}
/// \name Members
/// @{
private:
registry_util::shared_handle *m_handle; // Shared context for registry key and event object
index_type m_index; // Current iteration index
string_type m_name; // The value name
REGSAM m_accessMask; // Security access mask
/// @}
};
////////////////////////////////////////////////////////////////////////////
// Unit-testing
#ifdef STLSOFT_UNITTEST
# include "./unittest/reg_key_sequence_unittest_.h"
#endif /* STLSOFT_UNITTEST */
////////////////////////////////////////////////////////////////////////////
// Implementation
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
// basic_reg_key_sequence
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline registry_util::shared_handle *basic_reg_key_sequence<C, T, A>::create_shared_handle_(result_type &res)
{
// 1. Duplicate the registry handle
//
// 2. create the shared_handle
hkey_type hkey2 = traits_type::key_dup(m_hkey, m_accessMask, &res);
if(NULL == hkey2)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not duplicate key";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(key_not_duplicated_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
; // This will fall through to the end() call at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
// Pop it in a scoped handle for RAII
scoped_handle<HKEY> sh(hkey2, ::RegCloseKey);
registry_util::shared_handle *handle = registry_util::create_shared_handle(hkey2, m_bMonitorExternalInvalidation, REG_NOTIFY_CHANGE_NAME);
if(NULL == handle)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not create shared enumeration context";
DWORD err = ::GetLastError();
if(ERROR_ACCESS_DENIED == err)
{
STLSOFT_THROW_X(access_denied_exception(message, err));
}
else
{
STLSOFT_THROW_X(registry_exception(message, err));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
; // This will fall through to the end() call at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
sh.detach();
return handle;
}
}
return NULL;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline /* static */ REGSAM basic_reg_key_sequence<C, T, A>::validate_access_mask_(REGSAM accessMask, ss_typename_type_k basic_reg_key_sequence<C, T, A>::bool_type bMonitorExternalInvalidation)
{
if(bMonitorExternalInvalidation)
{
return accessMask | KEY_NOTIFY;
}
else
{
return accessMask & ~(KEY_NOTIFY);
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline /* static */ ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::hkey_type basic_reg_key_sequence<C, T, A>::dup_key_(ss_typename_type_k basic_reg_key_sequence<C, T, A>::hkey_type hkey, REGSAM accessMask/* , ss_typename_type_k basic_reg_key_sequence<C, T, A>::result_type *result */)
{
result_type res;
HKEY hkeyDup = traits_type::key_dup(hkey, accessMask, &res);
if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not duplicate key";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(key_not_duplicated_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
hkeyDup = NULL;
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
return hkeyDup;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::basic_reg_key_sequence( ss_typename_type_k basic_reg_key_sequence<C, T, A>::hkey_type hkey
, ss_typename_type_k basic_reg_key_sequence<C, T, A>::char_type const* sub_key_name
, REGSAM accessMask /* = KEY_READ */)
: m_hkey(NULL)
, m_accessMask(accessMask)
, m_bMonitorExternalInvalidation(0 != (KEY_NOTIFY & accessMask))
{
result_type res;
if(ERROR_SUCCESS != (res = traits_type::reg_open_key(hkey, sub_key_name, &m_hkey, accessMask)))
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not open key";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_hkey = NULL;
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::basic_reg_key_sequence( ss_typename_type_k basic_reg_key_sequence<C, T, A>::hkey_type hkey
, ss_typename_type_k basic_reg_key_sequence<C, T, A>::char_type const* sub_key_name
, REGSAM accessMask
, ss_typename_type_k basic_reg_key_sequence<C, T, A>::bool_type bMonitorExternalInvalidation)
: m_hkey(NULL)
, m_accessMask(validate_access_mask_(accessMask, bMonitorExternalInvalidation))
, m_bMonitorExternalInvalidation(bMonitorExternalInvalidation)
{
result_type res;
if(ERROR_SUCCESS != (res = traits_type::reg_open_key(hkey, sub_key_name, &m_hkey, accessMask)))
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not open key";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_hkey = NULL;
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::basic_reg_key_sequence(ss_typename_type_k basic_reg_key_sequence<C, T, A>::reg_key_type const& key)
: m_hkey(dup_key_(key.m_hkey, key.get_access_mask()))
, m_accessMask(key.get_access_mask())
, m_bMonitorExternalInvalidation(0 != (KEY_NOTIFY & key.get_access_mask()))
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
if(NULL == m_hkey)
{
STLSOFT_THROW_X(registry_exception("Failed to take duplicate of key", ::GetLastError()));
}
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::basic_reg_key_sequence( ss_typename_type_k basic_reg_key_sequence<C, T, A>::reg_key_type const &key
, REGSAM accessMask)
: m_hkey(dup_key_(key.m_hkey, accessMask))
, m_accessMask(accessMask)
, m_bMonitorExternalInvalidation(0 != (KEY_NOTIFY & accessMask))
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
if(NULL == m_hkey)
{
STLSOFT_THROW_X(registry_exception("Failed to take duplicate of key", ::GetLastError()));
}
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::basic_reg_key_sequence( ss_typename_type_k basic_reg_key_sequence<C, T, A>::reg_key_type const &key
, REGSAM accessMask
, bool_type bMonitorExternalInvalidation)
: m_hkey(dup_key_(key.m_hkey, validate_access_mask_(accessMask, bMonitorExternalInvalidation)))
, m_accessMask(validate_access_mask_(accessMask, bMonitorExternalInvalidation))
, m_bMonitorExternalInvalidation(bMonitorExternalInvalidation)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
if(NULL == m_hkey)
{
STLSOFT_THROW_X(registry_exception("Failed to take duplicate of key", ::GetLastError()));
}
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline basic_reg_key_sequence<C, T, A>::~basic_reg_key_sequence() stlsoft_throw_0()
{
if(m_hkey != NULL)
{
::RegCloseKey(m_hkey);
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::iterator basic_reg_key_sequence<C, T, A>::begin()
{
// 1. Check that there are some items
//
// 2. Duplicate the registry key handle & Create the shared handle
//
// 4. Loop to get the full name
//
// 5. Create the iterator and return
// 1. Check that there are some items
// Grab enough for the first item
size_type cchName = 0;
ws_uint32_t numEntries = 0;
result_type res = traits_type::reg_query_info(m_hkey, NULL, NULL, &numEntries, &cchName, NULL, NULL, NULL, NULL, NULL, NULL);
if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not elicit sub-key information";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
; // This will fall through to the end() call at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
if(0 != numEntries)
{
// 2. Duplicate the registry key handle & create the shared handle
registry_util::shared_handle *handle = create_shared_handle_(res);
ws_sint32_t index = 0;
if(NULL == handle)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not create shared enumeration context";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
; // This will fall through to the end() call at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
ref_ptr<registry_util::shared_handle> ref(handle, false); // Eat the reference here. The iterator will take another
// 4. Loop to get the full name
buffer_type_ buffer(++cchName); // This is increased so that the call to reg_enum_key is likely to succeed
for(; !buffer.empty(); ) // Need to loop because sub-keys can change, when we're not monitoring
{
cchName = buffer.size();
res = traits_type::reg_enum_key(m_hkey, 0, &buffer[0], &cchName);
if(ERROR_MORE_DATA == res)
{
if(!buffer.resize(2 * buffer.size())) // Throws, or returns false
{
cchName = 0;
index = const_iterator::sentinel_();
break;
}
continue; // "Let's go round again"
}
else if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not enumerate sub-keys";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
cchName = 0;
index = const_iterator::sentinel_();
break; // This will fall through to the end() call at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
break;
}
}
// 5. Create the iterator and return
return iterator(handle, buffer.data(), cchName, index, m_accessMask);
}
}
}
return end();
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::iterator basic_reg_key_sequence<C, T, A>::end()
{
result_type res;
registry_util::shared_handle *handle = create_shared_handle_(res);
ref_ptr<registry_util::shared_handle> ref(handle, false); // Eat the reference here. The iterator will take another
ws_sint32_t index = const_iterator::sentinel_();
if(NULL == handle)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
STLSOFT_THROW_X(registry_exception("Failed to take duplicate of key", res));
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
index = 0; // This will fall through to the constructor at the end of the function
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
return iterator(handle, NULL, 0, index, m_accessMask);
}
#if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT)
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::reverse_iterator basic_reg_key_sequence<C, T, A>::rbegin()
{
return reverse_iterator(end());
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::reverse_iterator basic_reg_key_sequence<C, T, A>::rend()
{
return reverse_iterator(begin());
}
#endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::size_type basic_reg_key_sequence<C, T, A>::size() const
{
return current_size();
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::size_type basic_reg_key_sequence<C, T, A>::current_size() const
{
ws_uint32_t numEntries;
result_type res = traits_type::reg_query_info(m_hkey, NULL, NULL, &numEntries, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not elicit number of sub-keys";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
numEntries = 0;
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
return static_cast<size_type>(numEntries);
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ws_bool_t basic_reg_key_sequence<C, T, A>::empty() const
{
return 0 == size();
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::hkey_type basic_reg_key_sequence<C, T, A>::get_key_handle() const
{
return m_hkey;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence<C, T, A>::hkey_type basic_reg_key_sequence<C, T, A>::get() const
{
return get_key_handle();
}
// basic_reg_key_sequence_iterator
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline /* static */ ss_typename_type_ret_k basic_reg_key_sequence_iterator<C, T, V, A>::index_type basic_reg_key_sequence_iterator<C, T, V, A>::sentinel_() stlsoft_throw_0()
{
return 0x7fffffff;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline basic_reg_key_sequence_iterator<C, T, V, A>::basic_reg_key_sequence_iterator()
: m_handle(NULL)
, m_index(sentinel_())
, m_name()
, m_accessMask(KEY_READ)
{}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline basic_reg_key_sequence_iterator<C, T, V, A>::basic_reg_key_sequence_iterator(class_type const& rhs)
: m_handle(rhs.m_handle)
, m_index(rhs.m_index)
, m_name(rhs.m_name)
, m_accessMask(rhs.m_accessMask)
{
if(NULL != m_handle)
{
m_handle->AddRef();
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type& basic_reg_key_sequence_iterator<C, T, V, A>::operator =(ss_typename_type_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type const& rhs)
{
registry_util::shared_handle *this_handle;
m_index = rhs.m_index;
m_name = rhs.m_name;
this_handle = m_handle;
m_handle = rhs.m_handle;
m_accessMask = rhs.m_accessMask;
if(NULL != m_handle)
{
m_handle->AddRef();
}
if(NULL != this_handle)
{
this_handle->Release();
}
return *this;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline basic_reg_key_sequence_iterator<C, T, V, A>::~basic_reg_key_sequence_iterator() stlsoft_throw_0()
{
if(NULL != m_handle)
{
m_handle->Release();
}
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline const ss_typename_type_k basic_reg_key_sequence_iterator<C, T, V, A>::string_type &basic_reg_key_sequence_iterator<C, T, V, A>::get_key_name() const
{
return m_name;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type& basic_reg_key_sequence_iterator<C, T, V, A>::operator ++()
{
WINSTL_MESSAGE_ASSERT("Attempting to increment an invalid iterator!", NULL != m_handle);
WINSTL_MESSAGE_ASSERT("Attempting to increment an invalid iterator!", sentinel_() != m_index);
// Grab enough for the first item
size_type cchName = 0;
result_type res = traits_type::reg_query_info(m_handle->m_hkey, NULL, NULL, NULL, &cchName, NULL, NULL, NULL, NULL, NULL, NULL);
if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not elicit sub-key information";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index = sentinel_();
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
buffer_type_ buffer(++cchName); // This is increased so that the call to reg_enum_key is likely to succeed
for(; !buffer.empty(); buffer.resize(2 * buffer.size())) // Need to loop because sub-keys can change, when we're not monitoring
{
cchName = buffer.size();
res = traits_type::reg_enum_key(m_handle->m_hkey, static_cast<ws_dword_t>(1 + m_index), &buffer[0], &cchName);
if(ERROR_MORE_DATA == res)
{
continue; // "Let's go round again"
}
else if(ERROR_NO_MORE_ITEMS == res)
{
m_index = sentinel_();
break;
}
else if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not enumerate sub-keys";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index = sentinel_();
break;
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
m_name.assign(buffer.data(), cchName);
++m_index;
break;
}
}
}
m_handle->test_reset_and_throw();
return *this;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ss_typename_type_ret_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type& basic_reg_key_sequence_iterator<C, T, V, A>::operator --()
{
WINSTL_MESSAGE_ASSERT("Attempting to decrement an invalid iterator", NULL != m_handle);
// Grab enough for the first item
size_type cchName = 0;
ws_uint32_t numEntries = 0;
result_type res = traits_type::reg_query_info(m_handle->m_hkey, NULL, NULL, &numEntries, &cchName, NULL, NULL, NULL, NULL, NULL, NULL);
if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not elicit sub-key information";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index = sentinel_();
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
buffer_type_ buffer(++cchName); // This is increased so that the call to reg_enum_key is likely to succeed
ws_dword_t index;
// If the iterator is currently at the "end()", ...
if(m_index == sentinel_())
{
// ... then set the index to be one past the end
index = numEntries - 1;
}
else
{
// ... otherwise just go back one from current
index = m_index - 1;
}
for(; !buffer.empty(); buffer.resize(2 * buffer.size())) // Need to loop because sub-keys can change, when we're not monitoring
{
cchName = buffer.size();
res = traits_type::reg_enum_key(m_handle->m_hkey, index, &buffer[0], &cchName);
if(ERROR_MORE_DATA == res)
{
continue; // "Let's go round again"
}
else if(ERROR_SUCCESS != res)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
static const char message[] = "could not elicit sub-key information";
if(ERROR_ACCESS_DENIED == res)
{
STLSOFT_THROW_X(access_denied_exception(message, res));
}
else
{
STLSOFT_THROW_X(registry_exception(message, res));
}
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index = sentinel_();
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
m_name.assign(buffer.data(), cchName);
m_index = index;
break;
}
}
}
m_handle->test_reset_and_throw();
return *this;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline const ss_typename_type_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type basic_reg_key_sequence_iterator<C, T, V, A>::operator ++(int)
{
class_type ret(*this);
operator ++();
return ret;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline const ss_typename_type_k basic_reg_key_sequence_iterator<C, T, V, A>::class_type basic_reg_key_sequence_iterator<C, T, V, A>::operator --(int)
{
class_type ret(*this);
operator --();
return ret;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline const ss_typename_type_k basic_reg_key_sequence_iterator<C, T, V, A>::value_type basic_reg_key_sequence_iterator<C, T, V, A>::operator *() const
{
WINSTL_MESSAGE_ASSERT("Attempting to dereference an invalid iterator", NULL != m_handle);
m_handle->test_reset_and_throw();
return value_type(m_handle->m_hkey, m_name, m_accessMask);
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ws_bool_t basic_reg_key_sequence_iterator<C, T, V, A>::equal(class_type const& rhs) const
{
return m_index == rhs.m_index;
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ws_bool_t basic_reg_key_sequence_iterator<C, T, V, A>::operator ==(class_type const& rhs) const
{
return equal(rhs);
}
template <ss_typename_param_k C, ss_typename_param_k T, ss_typename_param_k V, ss_typename_param_k A>
inline ws_bool_t basic_reg_key_sequence_iterator<C, T, V, A>::operator !=(class_type const& rhs) const
{
return !equal(rhs);
}
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* ////////////////////////////////////////////////////////////////////// */
#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} // namespace winstl
# else
} // namespace winstl_project
} // namespace stlsoft
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* WINSTL_INCL_WINSTL_REGISTRY_HPP_REG_KEY_SEQUENCE */
/* ///////////////////////////// end of file //////////////////////////// */
| 40.440554 | 293 | 0.630374 | [
"object"
] |
e911d2f75d361c3f0b01992defc6168bd07c1745 | 4,565 | cpp | C++ | Qor/Scene.cpp | flipcoder/qor | 7a2ebf667be4c913fbc7daf5e0b07a4c1723389d | [
"MIT"
] | 84 | 2015-03-30T14:29:29.000Z | 2022-01-28T12:29:25.000Z | Qor/Scene.cpp | flipcoder/qor | 7a2ebf667be4c913fbc7daf5e0b07a4c1723389d | [
"MIT"
] | 5 | 2016-01-22T18:54:35.000Z | 2021-07-24T10:21:12.000Z | Qor/Scene.cpp | flipcoder/qor | 7a2ebf667be4c913fbc7daf5e0b07a4c1723389d | [
"MIT"
] | 22 | 2015-08-06T05:32:29.000Z | 2022-03-05T13:20:46.000Z | #include "Scene.h"
#include "Mesh.h"
#include "Sound.h"
#include "Light.h"
#include "Material.h"
#include "Particle.h"
#include "kit/meta/meta.h"
using namespace std;
Scene :: Scene(const string& fn, ResourceCache* cache):
//Resource(fn),
m_pConfig(make_shared<Meta>(fn)),
m_Filename(fn),
m_pCache(cache),
m_pRoot(make_shared<Node>())
//m_pData(make_shared<Meta>(fn))
{
load();
}
void Scene :: iterate_data(const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("data: %s: %s", name % type);
try{
if(type == "mesh")
m_pCache->cache_cast<Mesh::Data>(m_Filename + ":" + doc->at<string>("name"));
else if(type == "material")
m_pCache->cache_cast<Material>(doc->at<string>("image"));
}catch(const Error& e){
}catch(const std::exception& e){
WARNING(e.what());
}
}
glm::mat4 Scene :: deserialize_matrix(const std::shared_ptr<Meta>& mat)
{
//if(not mat->empty())
return glm::mat4(
mat->at<double>(0),
mat->at<double>(1),
mat->at<double>(2),
mat->at<double>(3),
mat->at<double>(4),
mat->at<double>(5),
mat->at<double>(6),
mat->at<double>(7),
mat->at<double>(8),
mat->at<double>(9),
mat->at<double>(10),
mat->at<double>(11),
mat->at<double>(12),
mat->at<double>(13),
mat->at<double>(14),
mat->at<double>(15)
);
//else
// return glm::mat4(1.0f);
}
void Scene :: deserialize_node(std::shared_ptr<Node>& node, const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
node->name(name);
auto mat = doc->at<shared_ptr<Meta>>("matrix");
*node->matrix() = deserialize_matrix(mat);
}
void Scene :: iterate_node(const std::shared_ptr<Node>& parent, const std::shared_ptr<Meta>& doc)
{
shared_ptr<Node> node;
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("node: %s: %s", name % type);
//int light_count = 0;
// based on node type, create the node
if(type == "empty")
node = make_shared<Node>();
else if(type == "mesh")
{
//LOGf("mesh fn %s name %s", m_Filename % name);
auto data = doc->at<string>("data", string());
//if(name.find(":") != string::npos)
// return;
if(not data.empty())
node = make_shared<Mesh>(m_Filename + ":" + data, m_pCache);
}
#ifndef QOR_NO_AUDIO
else if(type == "sound")
{
string fn = doc->at<string>("sound", string());
if(not fn.empty()){
//LOGf("sound: %s", fn);
auto snd = make_shared<Sound>(fn, m_pCache);
node = snd;
}else{
//WARNINGf("Object %s has no sound file.");
}
}
#endif
else if(type == "light")
{
auto light = make_shared<Light>(doc);
node = light;
}
if(not node)
node = make_shared<Node>();
try{
deserialize_node(node, doc);
//LOGf("matrix %s", Matrix::to_string(*node->matrix()));
parent->add(node);
node->pend();
}catch(const out_of_range&){}
try{
for(auto& e: *doc->meta("nodes"))
{
try{
iterate_node(node, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}catch(const out_of_range&){}
}
void Scene :: load()
{
auto grav = m_pConfig->meta("gravity", make_shared<Meta>(
MetaFormat::JSON, "[0.0, -9.8, 0.0]"
));
m_Gravity = glm::vec3(
grav->at<double>(0),
grav->at<double>(1),
grav->at<double>(2)
);
auto fog = m_pConfig->meta("fog", make_shared<Meta>(
MetaFormat::JSON, "[0.0, 0.0, 0.0, 0.0]"
));
m_Fog = Color(
(float)fog->at<double>(0),
(float)fog->at<double>(1),
(float)fog->at<double>(2),
(float)fog->at<double>(3)
);
//for(auto& e: *m_pConfig->meta("data"))
//{
// try{
// iterate_data(e.as<std::shared_ptr<Meta>>());
// }catch(const boost::bad_any_cast&){}
//}
//m_pRoot = make_shared<Node>();
for(auto& e: *m_pConfig->meta("nodes"))
{
try{
iterate_node(m_pRoot, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}
| 27.5 | 97 | 0.521577 | [
"mesh",
"object"
] |
e91207ecc26092441aad3b0618848ef1611fe444 | 8,271 | hpp | C++ | src/AI_Image_Processing_Unit2/deployment_tools/ngraph/include/ngraph/type/bfloat16.hpp | bijoumd78/httpServer | 5ae284e2f03a5a5795b3e09b6f1e8b07d5e1a3ed | [
"MIT"
] | 1 | 2021-04-22T07:28:03.000Z | 2021-04-22T07:28:03.000Z | src/AI_Image_Processing_Unit2/deployment_tools/ngraph/include/ngraph/type/bfloat16.hpp | bijoumd78/httpServer | 5ae284e2f03a5a5795b3e09b6f1e8b07d5e1a3ed | [
"MIT"
] | 105 | 2020-06-04T00:23:29.000Z | 2022-02-21T13:04:33.000Z | ngraph/core/include/ngraph/type/bfloat16.hpp | v-Golubev/openvino | 26936d1fbb025c503ee43fe74593ee9d7862ab15 | [
"Apache-2.0"
] | 3 | 2021-04-25T06:52:41.000Z | 2021-05-07T02:01:44.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <cmath>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "ngraph/ngraph_visibility.hpp"
#define ROUND_MODE_TO_NEAREST_EVEN
namespace ngraph
{
class NGRAPH_API bfloat16
{
public:
constexpr bfloat16()
: m_value{0}
{
}
bfloat16(float value)
: m_value
{
#if defined ROUND_MODE_TO_NEAREST
round_to_nearest(value)
#elif defined ROUND_MODE_TO_NEAREST_EVEN
round_to_nearest_even(value)
#elif defined ROUND_MODE_TRUNCATE
truncate(value)
#else
#error \
"ROUNDING_MODE must be one of ROUND_MODE_TO_NEAREST, ROUND_MODE_TO_NEAREST_EVEN, or ROUND_MODE_TRUNCATE"
#endif
}
{
}
template <typename I>
explicit bfloat16(I value)
: m_value{bfloat16{static_cast<float>(value)}.m_value}
{
}
std::string to_string() const;
size_t size() const;
template <typename T>
bool operator==(const T& other) const;
template <typename T>
bool operator!=(const T& other) const
{
return !(*this == other);
}
template <typename T>
bool operator<(const T& other) const;
template <typename T>
bool operator<=(const T& other) const;
template <typename T>
bool operator>(const T& other) const;
template <typename T>
bool operator>=(const T& other) const;
template <typename T>
bfloat16 operator+(const T& other) const;
template <typename T>
bfloat16 operator+=(const T& other);
template <typename T>
bfloat16 operator-(const T& other) const;
template <typename T>
bfloat16 operator-=(const T& other);
template <typename T>
bfloat16 operator*(const T& other) const;
template <typename T>
bfloat16 operator*=(const T& other);
template <typename T>
bfloat16 operator/(const T& other) const;
template <typename T>
bfloat16 operator/=(const T& other);
operator float() const;
static std::vector<float> to_float_vector(const std::vector<bfloat16>&);
static std::vector<bfloat16> from_float_vector(const std::vector<float>&);
static constexpr bfloat16 from_bits(uint16_t bits) { return bfloat16(bits, true); }
uint16_t to_bits() const;
friend std::ostream& operator<<(std::ostream& out, const bfloat16& obj)
{
out << static_cast<float>(obj);
return out;
}
#define cu32(x) (F32(x).i)
static uint16_t round_to_nearest_even(float x)
{
return static_cast<uint16_t>((cu32(x) + ((cu32(x) & 0x00010000) >> 1)) >> 16);
}
static uint16_t round_to_nearest(float x)
{
return static_cast<uint16_t>((cu32(x) + 0x8000) >> 16);
}
static uint16_t truncate(float x) { return static_cast<uint16_t>((cu32(x)) >> 16); }
private:
constexpr bfloat16(uint16_t x, bool)
: m_value{x}
{
}
union F32 {
F32(float val)
: f{val}
{
}
F32(uint32_t val)
: i{val}
{
}
float f;
uint32_t i;
};
uint16_t m_value;
};
template <typename T>
bool bfloat16::operator==(const T& other) const
{
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
return (static_cast<float>(*this) == static_cast<float>(other));
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
template <typename T>
bool bfloat16::operator<(const T& other) const
{
return (static_cast<float>(*this) < static_cast<float>(other));
}
template <typename T>
bool bfloat16::operator<=(const T& other) const
{
return (static_cast<float>(*this) <= static_cast<float>(other));
}
template <typename T>
bool bfloat16::operator>(const T& other) const
{
return (static_cast<float>(*this) > static_cast<float>(other));
}
template <typename T>
bool bfloat16::operator>=(const T& other) const
{
return (static_cast<float>(*this) >= static_cast<float>(other));
}
template <typename T>
bfloat16 bfloat16::operator+(const T& other) const
{
return {static_cast<float>(*this) + static_cast<float>(other)};
}
template <typename T>
bfloat16 bfloat16::operator+=(const T& other)
{
return *this = *this + other;
}
template <typename T>
bfloat16 bfloat16::operator-(const T& other) const
{
return {static_cast<float>(*this) - static_cast<float>(other)};
}
template <typename T>
bfloat16 bfloat16::operator-=(const T& other)
{
return *this = *this - other;
}
template <typename T>
bfloat16 bfloat16::operator*(const T& other) const
{
return {static_cast<float>(*this) * static_cast<float>(other)};
}
template <typename T>
bfloat16 bfloat16::operator*=(const T& other)
{
return *this = *this * other;
}
template <typename T>
bfloat16 bfloat16::operator/(const T& other) const
{
return {static_cast<float>(*this) / static_cast<float>(other)};
}
template <typename T>
bfloat16 bfloat16::operator/=(const T& other)
{
return *this = *this / other;
}
} // namespace ngraph
namespace std
{
template <>
class numeric_limits<ngraph::bfloat16>
{
public:
static constexpr bool is_specialized = true;
static constexpr ngraph::bfloat16 min() noexcept
{
return ngraph::bfloat16::from_bits(0x007F);
}
static constexpr ngraph::bfloat16 max() noexcept
{
return ngraph::bfloat16::from_bits(0x7F7F);
}
static constexpr ngraph::bfloat16 lowest() noexcept
{
return ngraph::bfloat16::from_bits(0xFF7F);
}
static constexpr int digits = 7;
static constexpr int digits10 = 2;
static constexpr bool is_signed = true;
static constexpr bool is_integer = false;
static constexpr bool is_exact = false;
static constexpr int radix = 2;
static constexpr ngraph::bfloat16 epsilon() noexcept
{
return ngraph::bfloat16::from_bits(0x3C00);
}
static constexpr ngraph::bfloat16 round_error() noexcept
{
return ngraph::bfloat16::from_bits(0x3F00);
}
static constexpr int min_exponent = -125;
static constexpr int min_exponent10 = -37;
static constexpr int max_exponent = 128;
static constexpr int max_exponent10 = 38;
static constexpr bool has_infinity = true;
static constexpr bool has_quiet_NaN = true;
static constexpr bool has_signaling_NaN = true;
static constexpr float_denorm_style has_denorm = denorm_absent;
static constexpr bool has_denorm_loss = false;
static constexpr ngraph::bfloat16 infinity() noexcept
{
return ngraph::bfloat16::from_bits(0x7F80);
}
static constexpr ngraph::bfloat16 quiet_NaN() noexcept
{
return ngraph::bfloat16::from_bits(0x7FC0);
}
static constexpr ngraph::bfloat16 signaling_NaN() noexcept
{
return ngraph::bfloat16::from_bits(0x7FC0);
}
static constexpr ngraph::bfloat16 denorm_min() noexcept
{
return ngraph::bfloat16::from_bits(0);
}
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = false;
static constexpr bool is_modulo = false;
static constexpr bool traps = false;
static constexpr bool tinyness_before = false;
static constexpr float_round_style round_style = round_to_nearest;
};
} // namespace std
| 29.329787 | 108 | 0.594003 | [
"vector"
] |
e912ff701c3a1beb038aef2501e29bee0503f71a | 5,933 | cpp | C++ | SVGWriter.cpp | sebastian-knopp/OpenSVGWriter | a73005976ec67cd7f073214e9e45d4150b30de66 | [
"Unlicense"
] | 1 | 2021-02-18T17:50:49.000Z | 2021-02-18T17:50:49.000Z | SVGWriter.cpp | sebastian-knopp/OpenSVGWriter | a73005976ec67cd7f073214e9e45d4150b30de66 | [
"Unlicense"
] | null | null | null | SVGWriter.cpp | sebastian-knopp/OpenSVGWriter | a73005976ec67cd7f073214e9e45d4150b30de66 | [
"Unlicense"
] | null | null | null | #include "SVGWriter.h"
#include <iostream>
#include <algorithm>
#include <tuple>
SVGWriter::SVGWriter(const std::string& a_filename,
const int a_targetSize,
const int a_borderWidth)
: m_targetSize(a_targetSize)
, m_borderWidth(a_borderWidth)
, m_ofs(a_filename)
{
}
SVGWriter::~SVGWriter()
{
const double dblWidth = m_max.m_x - m_min.m_x;
double dblHeight = m_max.m_y - m_min.m_y;
double scaleFactor = static_cast<double>(m_targetSize) / std::max(dblWidth, dblHeight);
auto getScaledValue = [scaleFactor, this] (const double a_value)
{
return static_cast<int>(scaleFactor * a_value);
};
auto getScaledXValue = [scaleFactor, this] (const double a_value)
{
return static_cast<int>(scaleFactor * (a_value - m_min.m_x)) + m_borderWidth;
};
auto getScaledYValue = [scaleFactor, this] (const double a_value)
{
return static_cast<int>(scaleFactor * (a_value - m_min.m_y)) + m_borderWidth;
};
const int width = getScaledXValue(m_max.m_x) + m_borderWidth;
const int height = getScaledYValue(m_max.m_y) + m_borderWidth;
m_ofs << "<!DOCTYPE html>\n"
<< "<html>\n"
<< "<body>\n"
<< "<svg height=\"" << height << "\" width=\"" << width << "\">\n";
for (const DrawCommand& command : m_commands)
{
m_ofs << " ";
switch (command.m_type)
{
case CommandType::Circle:
m_ofs << "<circle "
<< "cx=\"" << (getScaledXValue(command.m_fromCoord.m_x)) << "\" "
<< "cy=\"" << (getScaledYValue(command.m_fromCoord.m_y)) << "\" "
<< "r=\"" << command.m_size << "\" stroke=\"black\" stroke-width=\"0\" "
<< "fill=\"" << getColorString(command.m_color) << "\" />\n";
break;
case CommandType::Line:
m_ofs << "<line "
<< "x1=\"" << getScaledXValue(command.m_fromCoord.m_x) << "\" "
<< "y1=\"" << getScaledYValue(command.m_fromCoord.m_y) << "\" "
<< "x2=\"" << getScaledXValue(command.m_toCoord.m_x) << "\" "
<< "y2=\"" << getScaledYValue(command.m_toCoord.m_y) << "\" "
<< " style=\"stroke:" << getColorString(command.m_color) << ";stroke-width:2\" />\n";
break;
case CommandType::Text:
m_ofs << "<text "
<< "x=\"" << getScaledXValue(command.m_fromCoord.m_x) << "\" "
<< "y=\"" << getScaledYValue(command.m_fromCoord.m_y) << "\" "
<< "font-size=\"" << command.m_size << "\" "
<< "font-family=\"arial\">" << command.m_text << "</text>\n";
break;
case CommandType::Rectangle:
m_ofs << "<rect "
<< "x=\"" << getScaledXValue(command.m_fromCoord.m_x) << "\" "
<< "y=\"" << getScaledYValue(command.m_fromCoord.m_y) << "\" "
<< "width=\"" << getScaledValue(command.m_toCoord.m_x - command.m_fromCoord.m_x) << "\" "
<< "height=\"" << getScaledValue(command.m_toCoord.m_y - command.m_fromCoord.m_y) << "\" "
<< "style=\"";
if (command.m_size == 0)
m_ofs << " fill:" << getColorString(command.m_color);
else
m_ofs << " stroke:" << getColorString(command.m_color) << ";"
<< " stroke-width:" << command.m_size << ";fill-opacity:0.0\" ";
m_ofs << "\" />\n";
break;
}
}
m_ofs << "</svg>\n"
<< "</body>\n"
<< "</html>\n";
}
void SVGWriter::drawCircle(double a_x, double a_y, int a_colorIndex, int a_diameter)
{
const Coordinate c { a_x, a_y };
updateMinMax(c);
m_commands.push_back(DrawCommand { CommandType::Circle, c, c, a_colorIndex, a_diameter, "" });
}
void SVGWriter::drawLine(double a_fromX, double a_fromY, double a_toX, double a_toY, int a_colorIndex)
{
const Coordinate from { a_fromX, a_fromY };
updateMinMax(from);
const Coordinate to { a_toX, a_toY };
updateMinMax(to);
m_commands.push_back(DrawCommand { CommandType::Line, from, to, a_colorIndex, 0, "" });
}
void SVGWriter::drawRectangle(double a_fromX, double a_fromY, double a_toX, double a_toY, int a_colorIndex, int a_borderWidth)
{
std::tie(a_fromX, a_toX) = std::make_tuple(std::min(a_fromX, a_toX), std::max(a_fromX, a_toX));
std::tie(a_fromY, a_toY) = std::make_tuple(std::min(a_fromY, a_toY), std::max(a_fromY, a_toY));
const Coordinate from { a_fromX, a_fromY };
updateMinMax(from);
const Coordinate to { a_toX, a_toY };
updateMinMax(to);
m_commands.push_back(DrawCommand { CommandType::Rectangle, from, to, a_colorIndex, a_borderWidth, "" });
}
void SVGWriter::drawText(double a_x, double a_y, const std::string& a_text, int a_fontSize)
{
const Coordinate c { a_x, a_y };
updateMinMax(c);
m_commands.push_back(DrawCommand { CommandType::Text, c, c, 0, a_fontSize, a_text });
}
const std::string& SVGWriter::getColorString(int a_colorIndex)
{
static const std::vector<std::string> colors = {
"white"
"black",
"yellowgreen",
"lightskyblue",
"hotpink",
"mediumpurple",
"goldenrod",
"gold",
"red",
"darkcyan"
};
return colors[a_colorIndex % colors.size()];
}
void SVGWriter::updateMinMax(const SVGWriter::Coordinate& a_coord)
{
m_min.m_x = std::min(a_coord.m_x, m_min.m_x);
m_min.m_y = std::min(a_coord.m_y, m_min.m_y);
m_max.m_x = std::max(a_coord.m_x, m_max.m_x);
m_max.m_y = std::max(a_coord.m_y, m_max.m_y);
}
| 33.710227 | 127 | 0.544413 | [
"vector"
] |
e9147f131de27ab94eb1817dc6504efda69980ad | 4,541 | cpp | C++ | src/But/Container/UnorderedArray_speed.manual.cpp | el-bart/but | eee2e7e34dde415f4c87461f75c2bab38fc56407 | [
"BSD-3-Clause"
] | 27 | 2016-01-12T19:30:57.000Z | 2022-01-27T15:52:39.000Z | src/But/Container/UnorderedArray_speed.manual.cpp | el-bart/but | eee2e7e34dde415f4c87461f75c2bab38fc56407 | [
"BSD-3-Clause"
] | 4 | 2017-04-10T16:30:22.000Z | 2019-04-24T21:02:55.000Z | src/But/Container/UnorderedArray_speed.manual.cpp | el-bart/but | eee2e7e34dde415f4c87461f75c2bab38fc56407 | [
"BSD-3-Clause"
] | 2 | 2016-12-09T17:09:59.000Z | 2019-07-16T00:19:31.000Z | #include <set>
#include <list>
#include <deque>
#include <chrono>
#include <string>
#include <random>
#include <vector>
#include <iomanip>
#include <typeinfo>
#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <cinttypes>
#include <But/assert.hpp>
#include <But/Container/UnorderedArray.hpp>
using std::cout;
using std::cerr;
using std::endl;
using DataField = int;
struct UnorderedArrayAdapter
{
using Container = But::Container::UnorderedArray<DataField>;
void add(DataField i) { c_.add(i); }
Container::const_iterator find(const DataField q) { return std::find( begin(c_), end(c_), q ); }
void reserve(const Container::size_type n) { c_.reserve(n); }
Container c_;
};
struct VectorAdapter
{
using Container = std::vector<DataField>;
void add(DataField i) { c_.push_back(i); }
Container::const_iterator find(const DataField q) { return std::find( begin(c_), end(c_), q ); }
void reserve(const Container::size_type n) { c_.reserve(n); }
Container c_;
};
struct SetAdapter
{
using Container = std::set<DataField>;
void add(DataField i) { c_.insert(i); }
Container::const_iterator find(const DataField q) { return c_.find(q); }
void reserve(const Container::size_type /*n*/) { /* not applicable */ }
Container c_;
};
struct UnorderedSetAdapter
{
using Container = std::unordered_set<DataField>;
void add(DataField i) { c_.insert(i); }
Container::const_iterator find(const DataField q) { return c_.find(q); }
void reserve(const Container::size_type n) { c_.reserve(n); }
Container c_;
};
struct DequeAdapter
{
using Container = std::deque<DataField>;
void add(DataField i) { c_.push_back(i); }
Container::const_iterator find(const DataField q) { return std::find( begin(c_), end(c_), q ); }
void reserve(const Container::size_type /*n*/) { /* not applicable */ }
Container c_;
};
struct ListAdapter
{
using Container = std::list<DataField>;
void add(DataField i) { c_.push_back(i); }
Container::const_iterator find(const DataField q) { return std::find( begin(c_), end(c_), q ); }
void reserve(const Container::size_type /*n*/) { /* not applicable */ }
Container c_;
};
auto randomize(std::vector<DataField> c, const DataField seed)
{
std::mt19937 gen(seed);
std::shuffle( begin(c), end(c), gen );
return c;
}
auto generateUniqueValues(unsigned size)
{
const auto seed = 42;
std::mt19937 gen(seed);
std::uniform_int_distribution<DataField> dist;
std::vector<DataField> out;
out.reserve(size);
for(auto i=0u; i<size; ++i)
{
while(true)
{
const auto next = dist(gen);
const auto it = std::lower_bound( begin(out), end(out), next );
if(*it == next)
continue;
out.insert(it, next);
break;
}
}
BUT_ASSERT( out.size() == size );
BUT_ASSERT( std::is_sorted( begin(out), end(out) ) );
return randomize( std::move(out), seed+1 );
}
template<typename Adapter>
void testAlgorithm(std::vector<DataField> const& values, std::vector<DataField> const& queries)
{
Adapter data;
data.reserve( values.size() );
for(const auto e: values)
data.add(e);
for(const auto q: queries)
{
const auto it = data.find(q);
BUT_ASSERT( it != end(data.c_) );
data.c_.erase(it);
}
}
template<typename Adapter>
void measure(std::vector<DataField> const& values, std::vector<DataField> const& queries)
{
cerr << "measuring " << typeid(Adapter).name() << "..." << endl;
using Clock = std::chrono::high_resolution_clock;
const auto start = Clock::now();
testAlgorithm<Adapter>(values, queries);
const auto stop = Clock::now();
const auto diff = stop - start;
cerr.width(10);
cerr.fill(' ');
cerr << std::chrono::duration_cast<std::chrono::microseconds>(diff).count() << u8"[µs]" << endl;
}
int main(int argc, char** argv)
{
try
{
if(argc!=1+1)
{
cerr << argv[0] << " <size>" << endl;
return 1;
}
cerr << "preparing data..." << endl;
const auto max = std::stoul(argv[1]);
const auto values = generateUniqueValues(max);
const auto queries = randomize(values, 13);
cerr << "testing..." << endl;
measure<UnorderedArrayAdapter>(values, queries);
measure<VectorAdapter>(values, queries);
measure<SetAdapter>(values, queries);
measure<UnorderedSetAdapter>(values, queries);
measure<DequeAdapter>(values, queries);
measure<ListAdapter>(values, queries);
}
catch(std::exception const& ex)
{
cerr << argv[0] << " ERROR: " << ex.what() << endl;
return 2;
}
}
| 24.545946 | 98 | 0.658665 | [
"vector"
] |
e915c2002c31bfd395b82bff4f1ecd6a643ffd76 | 6,397 | cpp | C++ | src/common/Read.cpp | 0xC0000054/gmic-8bf | 10a91b07d8da33b787d5fc62ffcb3684c29c9671 | [
"MIT"
] | 36 | 2020-11-30T02:02:52.000Z | 2022-03-30T07:02:50.000Z | src/common/Read.cpp | 0xC0000054/gmic-8bf | 10a91b07d8da33b787d5fc62ffcb3684c29c9671 | [
"MIT"
] | 14 | 2020-12-02T16:52:56.000Z | 2022-03-11T17:42:43.000Z | src/common/Read.cpp | 0xC0000054/gmic-8bf | 10a91b07d8da33b787d5fc62ffcb3684c29c9671 | [
"MIT"
] | 3 | 2021-02-11T16:29:17.000Z | 2022-03-02T07:11:42.000Z | ////////////////////////////////////////////////////////////////////////
//
// This file is part of gmic-8bf, a filter plug-in module that
// interfaces with G'MIC-Qt.
//
// Copyright (c) 2020, 2021 Nicholas Hayes
//
// This file is licensed under the MIT License.
// See LICENSE.txt for complete licensing and attribution information.
//
////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GmicPlugin.h"
#include "GmicIOSettings.h"
#include "FolderBrowser.h"
#include "ImageSaveDialog.h"
#include "Gmic8bfImageReader.h"
#include "GmicQtParameters.h"
#include "PngWriter.h"
#include "resource.h"
#include "Utilities.h"
#include <algorithm>
#include <memory>
#include <vector>
#include <wil\result.h>
#include <setjmp.h>
#include <png.h>
namespace
{
std::vector<boost::filesystem::path> GetOutputFiles(const boost::filesystem::path& outputDir)
{
std::vector<boost::filesystem::path> filePaths;
for (auto& file : boost::filesystem::directory_iterator(outputDir))
{
filePaths.push_back(file.path());
}
return filePaths;
}
bool TryGetDefaultOutputFolder(const GmicIOSettings& settings, boost::filesystem::path& defaultOutputFolder)
{
bool result = false;
const boost::filesystem::path& savedOutputPath = settings.GetDefaultOutputPath();
if (!savedOutputPath.empty())
{
try
{
defaultOutputFolder = savedOutputPath;
result = true;
}
catch (...)
{
// Ignore any errors, the folder picker or save dialog will be shown.
}
}
return result;
}
OSErr GetOutputFolder(
FilterRecordPtr filterRecord,
const GmicIOSettings& settings,
boost::filesystem::path& outputFolder)
{
if (TryGetDefaultOutputFolder(settings, outputFolder))
{
return noErr;
}
else
{
return GetGmicOutputFolder(filterRecord, outputFolder);
}
}
OSErr GetResizedImageOutputPath(
const FilterRecordPtr filterRecord,
const GmicIOSettings& settings,
const boost::filesystem::path& originalFileName,
boost::filesystem::path& outputFileName)
{
bool haveFilePathFromDefaultFolder = false;
boost::filesystem::path defaultFolderPath;
if (TryGetDefaultOutputFolder(settings, defaultFolderPath))
{
try
{
boost::filesystem::path temp = defaultFolderPath;
temp /= originalFileName;
outputFileName = temp;
haveFilePathFromDefaultFolder = true;
}
catch (...)
{
// Ignore any errors, the save dialog will be shown.
}
}
if(haveFilePathFromDefaultFolder)
{
boost::filesystem::create_directories(defaultFolderPath);
return noErr;
}
else
{
return GetNewImageFileName(filterRecord, originalFileName, outputFileName);
}
}
}
OSErr ReadGmicOutput(
const boost::filesystem::path& outputDir,
const boost::filesystem::path& gmicParametersFilePath,
bool fullUIWasShown,
FilterRecord* filterRecord,
const GmicIOSettings& settings)
{
PrintFunctionName();
OSErr err = noErr;
try
{
std::vector<boost::filesystem::path> filePaths = GetOutputFiles(outputDir);
if (filePaths.empty())
{
throw std::runtime_error("G'MIC did not produce any output images.");
}
else
{
const char* const outputFileExtension = ".png";
if (filePaths.size() == 1)
{
const boost::filesystem::path& filePath = filePaths[0];
const VPoint& documentSize = GetImageSize(filterRecord);
bool imageSizeMatchesDocument = ImageSizeMatchesDocument(filePath, documentSize);
if (imageSizeMatchesDocument)
{
CopyImageToActiveLayer(filePath, filterRecord);
}
else
{
boost::filesystem::path outputFilePath;
OSErrException::ThrowIfError(GetResizedImageOutputPath(
filterRecord,
settings,
filePath.filename().replace_extension(outputFileExtension),
outputFilePath));
ConvertGmic8bfImageToPng(filterRecord, filePath, outputFilePath);
}
}
else
{
boost::filesystem::path outputFolder;
OSErrException::ThrowIfError(GetOutputFolder(filterRecord, settings, outputFolder));
boost::filesystem::create_directories(outputFolder);
for (size_t i = 0; i < filePaths.size(); i++)
{
const boost::filesystem::path& inputFilePath = filePaths[i];
boost::filesystem::path outputFilePath = outputFolder;
outputFilePath /= inputFilePath.filename().replace_extension(outputFileExtension);
ConvertGmic8bfImageToPng(filterRecord, inputFilePath, outputFilePath);
}
}
if (fullUIWasShown)
{
GmicQtParameters parameters(gmicParametersFilePath);
if (parameters.IsValid())
{
parameters.SaveToDescriptor(filterRecord);
}
}
}
}
catch (const std::bad_alloc&)
{
err = memFullErr;
}
catch (const OSErrException& e)
{
err = e.GetErrorCode();
}
catch (const std::exception& e)
{
err = ShowErrorMessage(e.what(), filterRecord, readErr);
}
catch (...)
{
err = ShowErrorMessage("An unspecified error occurred when processing the G'MIC-Qt output.", filterRecord, readErr);
}
// Do not set the FilterRecord data pointers to NULL, some hosts
// (e.g. XnView) will crash if they are set to NULL by a plug-in.
SetOutputRect(filterRecord, 0, 0, 0, 0);
SetMaskRect(filterRecord, 0, 0, 0, 0);
return err;
}
| 29.077273 | 124 | 0.562607 | [
"vector"
] |
e91875b5aa5886c1031b8c94de8adb614f6f9513 | 2,133 | cpp | C++ | tools/converter/source/optimizer/merge/ConstantFolding.cpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 2 | 2020-12-15T13:56:31.000Z | 2022-01-26T03:20:28.000Z | tools/converter/source/optimizer/merge/ConstantFolding.cpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | null | null | null | tools/converter/source/optimizer/merge/ConstantFolding.cpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1 | 2021-11-24T06:26:27.000Z | 2021-11-24T06:26:27.000Z | //
// FoldConstant.cpp
// MNNConverter
//
// Created by MNN on 2020/07/09.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "../TemplateMerge.hpp"
#include "MNN/expr/ExprCreator.hpp"
#include "MNN_generated.h"
#include "MergeHelpers.hpp"
namespace MNN {
namespace Express {
class ConstantFolding {
public:
ConstantFolding();
};
ConstantFolding::ConstantFolding() {
auto match = [](EXPRP expr) -> bool {
if (!expr->get()) {
return false;
}
// There's no nodes to be fold if it has no inputs.
if (!expr->inputs().size()) {
return false;
}
for (const VARP& input : expr->inputs()) {
const Op* input_op = input->expr().first->get();
if ((input_op && input_op->type() != OpType_Const) ||
(!input_op && input->expr().first->inputType() != VARP::CONSTANT)) {
return false;
}
}
return true /*matched*/;
};
auto fold = [this](EXPRP expr) -> bool {
std::vector<VARP> outputs = helpers::OutputVars(expr);
if (outputs.size() == 1) {
VARP output;
if (outputs.size() == 0) {
output = Variable::create(expr);
} else {
output = outputs.at(0);
}
auto output_info = output->getInfo();
if (!output_info) {
return false;
}
const void* output_data = output->readMap<void>();
VARP const_var = _Const(output_data, output_info->dim, output_info->order, output_info->type);
const_var->setName(expr->name());
EXPRP constant = const_var->expr().first;
constant->setName(expr->name());
Expr::replace(expr, constant);
} else {
// TODO(): Support multiple outputs.
return false;
}
return true /*modified*/;
};
TemplateMerge::getInstance("Merge").insertTemplate("ConstantFolding", match, fold);
}
static ConstantFolding g_constant_folding;
} // namespace Express
} // namespace MNN
| 29.219178 | 115 | 0.54196 | [
"vector"
] |
e91f6f376ca1748768bd845d8257c9de5d45bd5f | 5,975 | cpp | C++ | PhysX_3.4/Source/LowLevelParticles/src/PtBodyTransformVault.cpp | gongyiling/PhysX-3.4 | 99bc1c62880cf626f9926781e76a528b5276c68b | [
"Unlicense"
] | 1,863 | 2018-12-03T13:06:03.000Z | 2022-03-29T07:12:37.000Z | PhysX_3.4/Source/LowLevelParticles/src/PtBodyTransformVault.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 71 | 2018-12-03T19:48:39.000Z | 2022-01-11T09:30:52.000Z | PhysX_3.4/Source/LowLevelParticles/src/PtBodyTransformVault.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 265 | 2018-12-03T14:30:03.000Z | 2022-03-25T20:57:01.000Z | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PtBodyTransformVault.h"
#if PX_USE_PARTICLE_SYSTEM_API
#include "foundation/PxMemory.h"
#include "PxvGeometry.h"
#include "PxvDynamics.h"
#include "PsHash.h"
#include "PsFoundation.h"
using namespace physx;
using namespace Pt;
BodyTransformVault::BodyTransformVault() : mBody2WorldPool("body2WorldPool", 256), mBodyCount(0)
{
// Make sure the hash size is a power of 2
PX_ASSERT((((PT_BODY_TRANSFORM_HASH_SIZE - 1) ^ PT_BODY_TRANSFORM_HASH_SIZE) + 1) ==
(2 * PT_BODY_TRANSFORM_HASH_SIZE));
PxMemSet(mBody2WorldHash, 0, PT_BODY_TRANSFORM_HASH_SIZE * sizeof(Body2World*));
}
BodyTransformVault::~BodyTransformVault()
{
}
PX_FORCE_INLINE PxU32 BodyTransformVault::getHashIndex(const PxsBodyCore& body) const
{
PxU32 index = Ps::hash(&body);
return (index & (PT_BODY_TRANSFORM_HASH_SIZE - 1)); // Modulo hash size
}
void BodyTransformVault::addBody(const PxsBodyCore& body)
{
Body2World* entry;
Body2World* dummy;
bool hasEntry = findEntry(body, entry, dummy);
if(!hasEntry)
{
Body2World* newEntry;
if(entry)
{
// No entry for the given body but the hash entry has other bodies
// --> create new entry, link into list
newEntry = createEntry(body);
entry->next = newEntry;
}
else
{
// No entry for the given body and no hash entry --> create new entry
PxU32 hashIndex = getHashIndex(body);
newEntry = createEntry(body);
mBody2WorldHash[hashIndex] = newEntry;
}
newEntry->refCount = 1;
mBodyCount++;
}
else
{
entry->refCount++;
}
}
void BodyTransformVault::removeBody(const PxsBodyCore& body)
{
Body2World* entry;
Body2World* prevEntry;
bool hasEntry = findEntry(body, entry, prevEntry);
PX_ASSERT(hasEntry);
PX_UNUSED(hasEntry);
if(entry->refCount == 1)
{
if(prevEntry)
{
prevEntry->next = entry->next;
}
else
{
// Shape entry was first in list
PxU32 hashIndex = getHashIndex(body);
mBody2WorldHash[hashIndex] = entry->next;
}
mBody2WorldPool.destroy(entry);
PX_ASSERT(mBodyCount > 0);
mBodyCount--;
}
else
{
entry->refCount--;
}
}
void BodyTransformVault::teleportBody(const PxsBodyCore& body)
{
Body2World* entry;
Body2World* dummy;
bool hasEntry = findEntry(body, entry, dummy);
PX_ASSERT(hasEntry);
PX_ASSERT(entry);
PX_UNUSED(hasEntry);
PX_CHECK_AND_RETURN(body.body2World.isValid(), "BodyTransformVault::teleportBody: body.body2World is not valid.");
entry->b2w = body.body2World;
}
const PxTransform* BodyTransformVault::getTransform(const PxsBodyCore& body) const
{
Body2World* entry;
Body2World* dummy;
bool hasEntry = findEntry(body, entry, dummy);
// PX_ASSERT(hasEntry);
// PX_UNUSED(hasEntry);
// PX_ASSERT(entry);
return hasEntry ? &entry->b2w : NULL;
}
void BodyTransformVault::update()
{
if(mBodyCount)
{
for(PxU32 i = 0; i < PT_BODY_TRANSFORM_HASH_SIZE; i++)
{
Body2World* entry = mBody2WorldHash[i];
while(entry)
{
PX_ASSERT(entry->body);
entry->b2w = entry->body->body2World;
entry = entry->next;
}
}
}
}
BodyTransformVault::Body2World* BodyTransformVault::createEntry(const PxsBodyCore& body)
{
Body2World* entry = mBody2WorldPool.construct();
if(entry)
{
entry->b2w = body.body2World;
entry->next = NULL;
entry->body = &body;
}
return entry;
}
bool BodyTransformVault::isInVaultInternal(const PxsBodyCore& body) const
{
PxU32 hashIndex = getHashIndex(body);
if(mBody2WorldHash[hashIndex])
{
Body2World* curEntry = mBody2WorldHash[hashIndex];
while(curEntry->next)
{
if(curEntry->body == &body)
break;
curEntry = curEntry->next;
}
if(curEntry->body == &body)
return true;
}
return false;
}
bool BodyTransformVault::findEntry(const PxsBodyCore& body, Body2World*& entry, Body2World*& prevEntry) const
{
PxU32 hashIndex = getHashIndex(body);
prevEntry = NULL;
bool hasEntry = false;
if(mBody2WorldHash[hashIndex])
{
Body2World* curEntry = mBody2WorldHash[hashIndex];
while(curEntry->next)
{
if(curEntry->body == &body)
break;
prevEntry = curEntry;
curEntry = curEntry->next;
}
entry = curEntry;
if(curEntry->body == &body)
{
// An entry already exists for the given body
hasEntry = true;
}
}
else
{
entry = NULL;
}
return hasEntry;
}
#endif // PX_USE_PARTICLE_SYSTEM_API
| 24.690083 | 115 | 0.721506 | [
"shape"
] |
11e66063425c759817e53bc27cdcee8aa6b33357 | 5,907 | cpp | C++ | frameworks/surface/test/unittest/buffer_client_producer_remote_test.cpp | chaoyangcui/graphic_standard | 514f1889a0f394b9366917b71677f14749664d9d | [
"Apache-2.0"
] | null | null | null | frameworks/surface/test/unittest/buffer_client_producer_remote_test.cpp | chaoyangcui/graphic_standard | 514f1889a0f394b9366917b71677f14749664d9d | [
"Apache-2.0"
] | null | null | null | frameworks/surface/test/unittest/buffer_client_producer_remote_test.cpp | chaoyangcui/graphic_standard | 514f1889a0f394b9366917b71677f14749664d9d | [
"Apache-2.0"
] | 1 | 2021-09-13T12:08:05.000Z | 2021-09-13T12:08:05.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "buffer_client_producer_remote_test.h"
#include <vector>
#include <sys/wait.h>
#include <unistd.h>
#include "buffer_client_producer.h"
#include "buffer_consumer_listener.h"
#include "buffer_queue_producer.h"
namespace OHOS {
void BufferClientProducerRemoteTest::SetUpTestCase()
{
pipe(pipeFd);
pid = fork();
if (pid < 0) {
exit(1);
}
if (pid == 0) {
sptr<BufferQueue> bq = new BufferQueue("test");
ASSERT_NE(bq, nullptr);
sptr<BufferQueueProducer> bqp = new BufferQueueProducer(bq);
ASSERT_NE(bqp, nullptr);
bq->Init();
sptr<IBufferConsumerListener> listener = new BufferConsumerListener();
bq->RegisterConsumerListener(listener);
auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sam->AddSystemAbility(systemAbilityID, bqp);
char buf[10] = "start";
write(pipeFd[1], buf, sizeof(buf));
sleep(0);
read(pipeFd[0], buf, sizeof(buf));
sam->RemoveSystemAbility(systemAbilityID);
exit(0);
} else {
char buf[10];
read(pipeFd[0], buf, sizeof(buf));
auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
robj = sam->GetSystemAbility(systemAbilityID);
bp = iface_cast<IBufferProducer>(robj);
}
}
void BufferClientProducerRemoteTest::TearDownTestCase()
{
bp = nullptr;
robj = nullptr;
char buf[10] = "over";
write(pipeFd[1], buf, sizeof(buf));
waitpid(pid, nullptr, 0);
}
namespace {
HWTEST_F(BufferClientProducerRemoteTest, IsProxy, testing::ext::TestSize.Level0)
{
ASSERT_TRUE(robj->IsProxyObject());
}
HWTEST_F(BufferClientProducerRemoteTest, QueueSize, testing::ext::TestSize.Level0)
{
ASSERT_EQ(bp->GetQueueSize(), (uint32_t)SURFACE_DEFAULT_QUEUE_SIZE);
SurfaceError ret = bp->SetQueueSize(2);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->SetQueueSize(SURFACE_MAX_QUEUE_SIZE + 1);
ASSERT_NE(ret, SURFACE_ERROR_OK);
ASSERT_EQ(bp->GetQueueSize(), 2u);
}
HWTEST_F(BufferClientProducerRemoteTest, ReqCan, testing::ext::TestSize.Level0)
{
IBufferProducer::RequestBufferReturnValue retval;
SurfaceError ret = bp->RequestBuffer(requestConfig, bedata, retval);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ASSERT_NE(retval.buffer, nullptr);
ret = bp->CancelBuffer(retval.sequence, bedata);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
}
HWTEST_F(BufferClientProducerRemoteTest, ReqCanCan, testing::ext::TestSize.Level0)
{
IBufferProducer::RequestBufferReturnValue retval;
SurfaceError ret = bp->RequestBuffer(requestConfig, bedata, retval);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ASSERT_EQ(retval.buffer, nullptr);
ret = bp->CancelBuffer(retval.sequence, bedata);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->CancelBuffer(retval.sequence, bedata);
ASSERT_NE(ret, SURFACE_ERROR_OK);
}
HWTEST_F(BufferClientProducerRemoteTest, ReqReqReqCanCan, testing::ext::TestSize.Level0)
{
IBufferProducer::RequestBufferReturnValue retval1;
IBufferProducer::RequestBufferReturnValue retval2;
IBufferProducer::RequestBufferReturnValue retval3;
SurfaceError ret;
ret = bp->RequestBuffer(requestConfig, bedata, retval1);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ASSERT_EQ(retval1.buffer, nullptr);
ret = bp->RequestBuffer(requestConfig, bedata, retval2);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ASSERT_NE(retval2.buffer, nullptr);
ret = bp->RequestBuffer(requestConfig, bedata, retval3);
ASSERT_NE(ret, SURFACE_ERROR_OK);
ASSERT_EQ(retval3.buffer, nullptr);
ret = bp->CancelBuffer(retval1.sequence, bedata);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->CancelBuffer(retval2.sequence, bedata);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->CancelBuffer(retval3.sequence, bedata);
ASSERT_NE(ret, SURFACE_ERROR_OK);
}
HWTEST_F(BufferClientProducerRemoteTest, SetQueueSizeDeleting, testing::ext::TestSize.Level0)
{
SurfaceError ret = bp->SetQueueSize(1);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
IBufferProducer::RequestBufferReturnValue retval;
ret = bp->RequestBuffer(requestConfig, bedata, retval);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ASSERT_EQ(retval.buffer, nullptr);
ret = bp->CancelBuffer(retval.sequence, bedata);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->SetQueueSize(2);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
}
HWTEST_F(BufferClientProducerRemoteTest, ReqFlu, testing::ext::TestSize.Level0)
{
IBufferProducer::RequestBufferReturnValue retval;
SurfaceError ret = bp->RequestBuffer(requestConfig, bedata, retval);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->FlushBuffer(retval.sequence, bedata, -1, flushConfig);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
}
HWTEST_F(BufferClientProducerRemoteTest, ReqFluFlu, testing::ext::TestSize.Level0)
{
IBufferProducer::RequestBufferReturnValue retval;
SurfaceError ret = bp->RequestBuffer(requestConfig, bedata, retval);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->FlushBuffer(retval.sequence, bedata, -1, flushConfig);
ASSERT_EQ(ret, SURFACE_ERROR_OK);
ret = bp->FlushBuffer(retval.sequence, bedata, -1, flushConfig);
ASSERT_NE(ret, SURFACE_ERROR_OK);
}
}
} // namespace OHOS
| 30.137755 | 93 | 0.717962 | [
"vector"
] |
11e9a0dc35d3a81d71d402017aad39ae81c860c8 | 11,787 | cpp | C++ | test/test_fcl_generate_bvh_model_deferred_finalize.cpp | haraisao/fcl | 6d008b63b801a2c85435c4ae959c28d7538ad270 | [
"BSD-3-Clause"
] | 921 | 2015-01-27T15:11:44.000Z | 2022-03-29T08:39:06.000Z | test/test_fcl_generate_bvh_model_deferred_finalize.cpp | sthagen/fcl | df2702ca5e703dec98ebd725782ce13862e87fc8 | [
"BSD-3-Clause"
] | 474 | 2015-01-28T08:08:18.000Z | 2022-03-30T13:40:49.000Z | test/test_fcl_generate_bvh_model_deferred_finalize.cpp | sthagen/fcl | df2702ca5e703dec98ebd725782ce13862e87fc8 | [
"BSD-3-Clause"
] | 370 | 2015-01-05T07:49:25.000Z | 2022-03-27T12:41:28.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, Open Source Robotics Foundation
* 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 Open Source Robotics Foundation 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.
*/
/** @author Nico van Duijn */
#include <gtest/gtest.h>
#include "fcl/config.h"
#include "fcl/geometry/geometric_shape_to_BVH_model.h"
#include "test_fcl_utility.h"
#include <iostream>
using namespace fcl;
/**
@description This file tests functionality in generateBVHModel(). Specifically,
it tests that a BVHModel can be either finalized after adding a
geometric primitive, or left "open" in order to add further
shapes at a later time. This functionality is tested without any
regard to proper functionality or special cases in the conversion from
geometric primitive to BVHModel.
**/
/**
@details This function tests adding geometric primitives to an empty model.
It checks proper functionality of those simply by
verifying the return value, the number of vertices, triangles and the state of the model.
In the process, the provided model will always be BVH_BUILD_STATE_BEGUN afterwards
**/
template<typename BV, typename ShapeType>
void checkAddToEmptyModel(BVHModel<BV>& model, const ShapeType& shape)
{
using S = typename BV::S;
uint8_t n = 32; // Hard-coded mesh-resolution. Not testing corner cases where n=0 or such
int ret;
// Make sure we are given an empty model
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_EMPTY);
uint8_t num_vertices = model.num_vertices;
uint8_t num_tris = model.num_tris;
GTEST_ASSERT_EQ(num_vertices, 0);
GTEST_ASSERT_EQ(num_tris, 0);
// Add the shape to the model and count vertices and triangles to make sure it has been created
ret = generateBVHModel(model, shape, Transform3<S>::Identity(), n, FinalizeModel::DONT);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_GT(model.num_vertices, num_vertices);
EXPECT_GT(model.num_tris, num_tris);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
}
// Specialization for boxes
template<typename BV>
void checkAddToEmptyModel(BVHModel<BV>& model, const Box<typename BV::S>& shape)
{
using S = typename BV::S;
int ret;
// Make sure we are given an empty model
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_EMPTY);
GTEST_ASSERT_EQ(model.num_vertices, 0);
GTEST_ASSERT_EQ(model.num_tris, 0);
// Add the shape to the model and count vertices and triangles to make sure it has been created
ret = generateBVHModel(model, shape, Transform3<S>::Identity(), FinalizeModel::DONT);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_EQ(model.num_vertices, 8);
EXPECT_EQ(model.num_tris, 12);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
}
/**
@details This function tests adding geometric primitives to an unfinalized model.
It checks proper functionality by verifying the return value,
the number of vertices, triangles and the state of the model.
After execution, the provided model will always be BVH_BUILD_STATE_BEGUN.
**/
template<typename BV, typename ShapeType>
void checkAddToUnfinalizedModel(BVHModel<BV>& model, const ShapeType& shape)
{
using S = typename BV::S;
const uint8_t n = 32;
int ret;
// Make sure we are given a model that is already begun
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
uint8_t num_vertices = model.num_vertices;
uint8_t num_tris = model.num_tris;
// Add the shape to the model and count vertices and triangles to make sure it has been created
ret = generateBVHModel(model, shape, Transform3<S>(Translation3<S>(Vector3<S>(2.0, 2.0, 2.0))), n, FinalizeModel::DONT);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_GT(model.num_vertices, num_vertices);
EXPECT_GT(model.num_tris, num_tris);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
}
// Specialization for boxes
template<typename BV>
void checkAddToUnfinalizedModel(BVHModel<BV>& model, const Box<typename BV::S>& shape)
{
using S = typename BV::S;
int ret;
// Make sure we are given a model that is already begun
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
uint8_t num_vertices = model.num_vertices;
uint8_t num_tris = model.num_tris;
// Add the shape to the model and count vertices and triangles to make sure it has been created
ret = generateBVHModel(model, shape, Transform3<S>(Translation3<S>(Vector3<S>(2.0, 2.0, 2.0))), FinalizeModel::DONT);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_EQ(model.num_vertices, num_vertices + 8);
EXPECT_EQ(model.num_tris, num_tris + 12);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
}
/**
@details This function tests adding primitives to a previously begun model
It checks proper functionality by checking the return value,
the number of vertices and triangles and the state of the model
after execution. After this call, the model is finalized.
**/
template<typename BV, typename ShapeType>
void checkAddAndFinalizeModel(BVHModel<BV>& model, const ShapeType& shape){
using S = typename BV::S;
const uint8_t n = 32;
int ret;
// Make sure we are given a model that is already begun
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
uint8_t num_vertices = model.num_vertices;
uint8_t num_tris = model.num_tris;
// Add another instance of the shape and make sure it was added to the model by counting vertices and tris
ret = generateBVHModel(model, shape, Transform3<S>(Translation3<S>(Vector3<S>(2.0, 2.0, 2.0))), n, FinalizeModel::DO);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_GT(model.num_vertices, num_vertices);
EXPECT_GT(model.num_tris, num_tris);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_PROCESSED);
}
// Specialization for boxes
template<typename BV>
void checkAddAndFinalizeModel(BVHModel<BV>& model, const Box<typename BV::S>& shape){
using S = typename BV::S;
int ret;
// Make sure we are given a model that is already begun
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_BEGUN);
uint8_t num_vertices = model.num_vertices;
uint8_t num_tris = model.num_tris;
// Add another instance of the shape and make sure it was added to the model by counting vertices and tris
ret = generateBVHModel(model, shape, Transform3<S>(Translation3<S>(Vector3<S>(3.0, 3.0, 3.0))), FinalizeModel::DO);
GTEST_ASSERT_EQ(ret, BVH_OK);
EXPECT_EQ(model.num_vertices, num_vertices + 8);
EXPECT_EQ(model.num_tris, num_tris + 12);
EXPECT_EQ(model.build_state, BVH_BUILD_STATE_PROCESSED);
}
/**
@details This function tests that adding geometric primitives to a finalized model indeed
returns the BVH error we would expect.
**/
template<typename BV, typename ShapeType>
void checkAddToFinalizedModel(BVHModel<BV>& model, const ShapeType& shape)
{
using S = typename BV::S;
const uint8_t n = 32;
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_PROCESSED);
auto ret = generateBVHModel(model, shape, Transform3<S>::Identity(), n, FinalizeModel::DONT);
EXPECT_EQ(ret, BVH_ERR_BUILD_OUT_OF_SEQUENCE);
}
// Specialization for boxes
template<typename BV>
void checkAddToFinalizedModel(BVHModel<BV>& model, const Box<typename BV::S>& shape)
{
using S = typename BV::S;
GTEST_ASSERT_EQ(model.build_state, BVH_BUILD_STATE_PROCESSED);
auto ret = generateBVHModel(model, shape, Transform3<S>::Identity(), FinalizeModel::DONT);
EXPECT_EQ(ret, BVH_ERR_BUILD_OUT_OF_SEQUENCE);
}
template<typename BV>
void testBVHModelFromBox()
{
using S = typename BV::S;
const S a = 1.0;
const S b = 1.0;
const S c = 1.0;
std::shared_ptr<BVHModel<BV>> model(new BVHModel<BV>);
Box<S> box(a, b, c);
checkAddToEmptyModel(*model, box);
checkAddToUnfinalizedModel(*model, box);
checkAddAndFinalizeModel(*model, box);
checkAddToFinalizedModel(*model, box);
}
template<typename BV>
void testBVHModelFromSphere()
{
using S = typename BV::S;
const S r = 1.0;
Sphere<S> sphere(r);
std::shared_ptr<BVHModel<BV>> model(new BVHModel<BV>);
checkAddToEmptyModel(*model, sphere);
checkAddToUnfinalizedModel(*model, sphere);
checkAddAndFinalizeModel(*model, sphere);
checkAddToFinalizedModel(*model, sphere);
}
template<typename BV>
void testBVHModelFromEllipsoid()
{
using S = typename BV::S;
const S a = 1.0;
const S b = 1.0;
const S c = 1.0;
Ellipsoid<S> ellipsoid(a, b, c);
std::shared_ptr<BVHModel<BV>> model(new BVHModel<BV>);
checkAddToEmptyModel(*model, ellipsoid);
checkAddToUnfinalizedModel(*model, ellipsoid);
checkAddAndFinalizeModel(*model, ellipsoid);
checkAddToFinalizedModel(*model, ellipsoid);
}
template<typename BV>
void testBVHModelFromCylinder()
{
using S = typename BV::S;
const S r = 1.0;
const S h = 1.0;
Cylinder<S> cylinder(r, h);
std::shared_ptr<BVHModel<BV>> model(new BVHModel<BV>);
checkAddToEmptyModel(*model, cylinder);
checkAddToUnfinalizedModel(*model, cylinder);
checkAddAndFinalizeModel(*model, cylinder);
checkAddToFinalizedModel(*model, cylinder);
}
template<typename BV>
void testBVHModelFromCone()
{
using S = typename BV::S;
const S r = 1.0;
const S h = 1.0;
Cone<S> cone(r, h);
std::shared_ptr<BVHModel<BV>> model(new BVHModel<BV>);
checkAddToEmptyModel(*model, cone);
checkAddToUnfinalizedModel(*model, cone);
checkAddAndFinalizeModel(*model, cone);
checkAddToFinalizedModel(*model, cone);
}
template<typename BV>
void testBVHModelFromPrimitives()
{
testBVHModelFromBox<BV>();
testBVHModelFromSphere<BV>();
testBVHModelFromEllipsoid<BV>();
testBVHModelFromCylinder<BV>();
testBVHModelFromCone<BV>();
}
GTEST_TEST(FCL_GENERATE_BVH_MODELS, generating_bvh_models_from_primitives)
{
testBVHModelFromPrimitives<AABB<double>>();
testBVHModelFromPrimitives<OBB<double>>();
testBVHModelFromPrimitives<RSS<double>>();
testBVHModelFromPrimitives<kIOS<double>>();
testBVHModelFromPrimitives<OBBRSS<double>>();
testBVHModelFromPrimitives<KDOP<double, 16> >();
testBVHModelFromPrimitives<KDOP<double, 18> >();
testBVHModelFromPrimitives<KDOP<double, 24> >();
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.503012 | 122 | 0.735556 | [
"mesh",
"geometry",
"shape",
"model"
] |
11ee9127fcbe96595832c08ef6ce8e4f0f28e2d8 | 2,024 | cc | C++ | examples/escher/waterfall/scenes/demo_scene.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | examples/escher/waterfall/scenes/demo_scene.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | examples/escher/waterfall/scenes/demo_scene.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia 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 "garnet/examples/escher/waterfall/scenes/demo_scene.h"
#include "lib/escher/geometry/tessellation.h"
#include "lib/escher/geometry/transform.h"
#include "lib/escher/geometry/types.h"
#include "lib/escher/material/material.h"
#include "lib/escher/scene/model.h"
#include "lib/escher/scene/stage.h"
#include "lib/escher/shape/modifier_wobble.h"
#include "lib/escher/util/stopwatch.h"
#include "lib/escher/vk/image.h"
#include "lib/escher/vk/vulkan_context.h"
using escher::MeshAttribute;
using escher::MeshSpec;
using escher::Object;
using escher::ShapeModifier;
using escher::TexturePtr;
using escher::Transform;
using escher::vec2;
using escher::vec3;
DemoScene::DemoScene(Demo* demo) : Scene(demo) {}
void DemoScene::Init(escher::Stage* stage) {
TexturePtr checkerboard = escher()->NewTexture(
escher()->NewCheckerboardImage(16, 16), vk::Filter::eNearest);
purple_ = fxl::MakeRefCounted<escher::Material>();
purple_->SetTexture(checkerboard);
purple_->set_color(vec3(0.588f, 0.239f, 0.729f));
}
DemoScene::~DemoScene() {}
escher::Model* DemoScene::Update(const escher::Stopwatch& stopwatch,
uint64_t frame_count, escher::Stage* stage,
escher::PaperRenderer2* renderer) {
stage->set_clear_color(vec3(0.f, 0.f, 0.f));
float current_time_sec = stopwatch.GetElapsedSeconds();
float t = sin(current_time_sec);
vec3 rect_scale(abs(800.f * t), abs(800.f * t), 1);
Transform transform(vec3(112.f + 100 * t, 112.f, 8.f), rect_scale,
current_time_sec * 0.5, vec3(0, 0, 1), vec3(0.5, 0.5, 0));
Object rectangle(Object::NewRect(transform, purple_));
std::vector<Object> objects{rectangle};
model_ = std::unique_ptr<escher::Model>(new escher::Model(objects));
model_->set_time(stopwatch.GetElapsedSeconds());
return model_.get();
}
| 36.142857 | 80 | 0.705534 | [
"geometry",
"object",
"shape",
"vector",
"model",
"transform"
] |
11f0eb2b0848e5f76b028a48d4387589411b864e | 20,634 | cpp | C++ | third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "bindings/core/v8/V8Initializer.h"
#include "third_party/node/src/node_webkit.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/RejectedPromises.h"
#include "bindings/core/v8/RetainedDOMInfo.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/ScriptWrappableVisitor.h"
#include "bindings/core/v8/SourceLocation.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMException.h"
#include "bindings/core/v8/V8ErrorEvent.h"
#include "bindings/core/v8/V8ErrorHandler.h"
#include "bindings/core/v8/V8GCController.h"
#include "bindings/core/v8/V8History.h"
#include "bindings/core/v8/V8IdleTaskRunner.h"
#include "bindings/core/v8/V8Location.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8PrivateProperty.h"
#include "bindings/core/v8/V8Window.h"
#include "bindings/core/v8/WorkerOrWorkletScriptController.h"
#include "core/dom/Document.h"
#include "core/fetch/AccessControlStatus.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/inspector/MainThreadDebugger.h"
#include "core/workers/WorkerGlobalScope.h"
#include "platform/EventDispatchForbiddenScope.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/tracing/TraceEvent.h"
#include "public/platform/Platform.h"
#include "public/platform/WebScheduler.h"
#include "public/platform/WebThread.h"
#include "wtf/AddressSanitizer.h"
#include "wtf/PtrUtil.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
#include "wtf/typed_arrays/ArrayBufferContents.h"
#include <memory>
#include <v8-debug.h>
#include <v8-profiler.h>
extern VoidHookFn g_promise_reject_callback_fn;
namespace blink {
static Frame* findFrame(v8::Isolate* isolate,
v8::Local<v8::Object> host,
v8::Local<v8::Value> data) {
const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
if (V8Window::wrapperTypeInfo.equals(type)) {
v8::Local<v8::Object> windowWrapper =
V8Window::findInstanceInPrototypeChain(host, isolate);
if (windowWrapper.IsEmpty())
return 0;
return V8Window::toImpl(windowWrapper)->frame();
}
if (V8History::wrapperTypeInfo.equals(type))
return V8History::toImpl(host)->frame();
if (V8Location::wrapperTypeInfo.equals(type))
return V8Location::toImpl(host)->frame();
// This function can handle only those types listed above.
ASSERT_NOT_REACHED();
return 0;
}
static void reportFatalErrorInMainThread(const char* location,
const char* message) {
int memoryUsageMB = Platform::current()->actualMemoryUsageMB();
DVLOG(1) << "V8 error: " << message << " (" << location
<< "). Current memory usage: " << memoryUsageMB << " MB";
CRASH();
}
static void reportOOMErrorInMainThread(const char* location, bool isJsHeap) {
int memoryUsageMB = Platform::current()->actualMemoryUsageMB();
DVLOG(1) << "V8 " << (isJsHeap ? "javascript" : "process") << " OOM: ("
<< location << "). Current memory usage: " << memoryUsageMB
<< " MB";
OOM_CRASH();
}
static String extractMessageForConsole(v8::Isolate* isolate,
v8::Local<v8::Value> data) {
if (V8DOMWrapper::isWrapper(isolate, data)) {
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(data);
const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
DOMException* exception = V8DOMException::toImpl(obj);
if (exception && !exception->messageForConsole().isEmpty())
return exception->toStringForConsole();
}
}
return emptyString();
}
void V8Initializer::messageHandlerInMainThread(v8::Local<v8::Message> message,
v8::Local<v8::Value> data) {
ASSERT(isMainThread());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
if (isolate->GetEnteredContext().IsEmpty())
return;
// If called during context initialization, there will be no entered context.
ScriptState* scriptState = ScriptState::current(isolate);
if (!scriptState->contextIsValid())
return;
ExecutionContext* context = scriptState->getExecutionContext();
std::unique_ptr<SourceLocation> location =
SourceLocation::fromMessage(isolate, message, context);
AccessControlStatus accessControlStatus = NotSharableCrossOrigin;
if (message->IsOpaque())
accessControlStatus = OpaqueResource;
else if (message->IsSharedCrossOrigin())
accessControlStatus = SharableCrossOrigin;
ErrorEvent* event =
ErrorEvent::create(toCoreStringWithNullCheck(message->Get()),
std::move(location), &scriptState->world());
String messageForConsole = extractMessageForConsole(isolate, data);
if (!messageForConsole.isEmpty())
event->setUnsanitizedMessage("Uncaught " + messageForConsole);
// This method might be called while we're creating a new context. In this
// case, we avoid storing the exception object, as we can't create a wrapper
// during context creation.
// FIXME: Can we even get here during initialization now that we bail out when
// GetEntered returns an empty handle?
if (context->isDocument()) {
LocalFrame* frame = toDocument(context)->frame();
if (frame && frame->script().existingWindowProxy(scriptState->world())) {
V8ErrorHandler::storeExceptionOnErrorEventWrapper(
scriptState, event, data, scriptState->context()->Global());
}
}
if (scriptState->world().isPrivateScriptIsolatedWorld()) {
// We allow a private script to dispatch error events even in a
// EventDispatchForbiddenScope scope. Without having this ability, it's
// hard to debug the private script because syntax errors in the private
// script are not reported to console (the private script just crashes
// silently). Allowing error events in private scripts is safe because
// error events don't propagate to other isolated worlds (which means that
// the error events won't fire any event listeners in user's scripts).
EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents;
context->dispatchErrorEvent(event, accessControlStatus);
} else {
context->dispatchErrorEvent(event, accessControlStatus);
}
}
namespace {
static RejectedPromises& rejectedPromisesOnMainThread() {
ASSERT(isMainThread());
DEFINE_STATIC_LOCAL(RefPtr<RejectedPromises>, rejectedPromises,
(RejectedPromises::create()));
return *rejectedPromises;
}
} // namespace
void V8Initializer::reportRejectedPromisesOnMainThread() {
rejectedPromisesOnMainThread().processQueue();
}
static void promiseRejectHandler(v8::PromiseRejectMessage data,
RejectedPromises& rejectedPromises,
ScriptState* scriptState) {
if (data.GetEvent() == v8::kPromiseHandlerAddedAfterReject) {
rejectedPromises.handlerAdded(data);
return;
}
ASSERT(data.GetEvent() == v8::kPromiseRejectWithNoHandler);
v8::Local<v8::Promise> promise = data.GetPromise();
v8::Isolate* isolate = promise->GetIsolate();
ExecutionContext* context = scriptState->getExecutionContext();
#if 0 //FIXME (#4577)
LocalDOMWindow* window = currentDOMWindow(isolate);
if (window->frame()->isNodeJS() && g_promise_reject_callback_fn)
g_promise_reject_callback_fn(&data);
#endif
v8::Local<v8::Value> exception = data.GetValue();
if (V8DOMWrapper::isWrapper(isolate, exception)) {
// Try to get the stack & location from a wrapped exception object (e.g.
// DOMException).
ASSERT(exception->IsObject());
auto privateError = V8PrivateProperty::getDOMExceptionError(isolate);
v8::Local<v8::Value> error = privateError.getOrUndefined(
scriptState->context(), exception.As<v8::Object>());
if (!error->IsUndefined())
exception = error;
}
String errorMessage;
AccessControlStatus corsStatus = NotSharableCrossOrigin;
std::unique_ptr<SourceLocation> location;
v8::Local<v8::Message> message =
v8::Exception::CreateMessage(isolate, exception);
if (!message.IsEmpty()) {
// message->Get() can be empty here. https://crbug.com/450330
errorMessage = toCoreStringWithNullCheck(message->Get());
location = SourceLocation::fromMessage(isolate, message, context);
if (message->IsSharedCrossOrigin())
corsStatus = SharableCrossOrigin;
} else {
location =
SourceLocation::create(context->url().getString(), 0, 0, nullptr);
}
String messageForConsole = extractMessageForConsole(isolate, data.GetValue());
if (!messageForConsole.isEmpty())
errorMessage = "Uncaught " + messageForConsole;
rejectedPromises.rejectedWithNoHandler(scriptState, data, errorMessage,
std::move(location), corsStatus);
}
static void promiseRejectHandlerInMainThread(v8::PromiseRejectMessage data) {
ASSERT(isMainThread());
v8::Local<v8::Promise> promise = data.GetPromise();
v8::Isolate* isolate = promise->GetIsolate();
// TODO(ikilpatrick): Remove this check, extensions tests that use
// extensions::ModuleSystemTest incorrectly don't have a valid script state.
LocalDOMWindow* window = currentDOMWindow(isolate);
if (!window || !window->isCurrentlyDisplayedInFrame())
return;
// Bail out if called during context initialization.
ScriptState* scriptState = ScriptState::current(isolate);
if (!scriptState->contextIsValid())
return;
promiseRejectHandler(data, rejectedPromisesOnMainThread(), scriptState);
}
static void promiseRejectHandlerInWorker(v8::PromiseRejectMessage data) {
v8::Local<v8::Promise> promise = data.GetPromise();
// Bail out if called during context initialization.
v8::Isolate* isolate = promise->GetIsolate();
ScriptState* scriptState = ScriptState::current(isolate);
if (!scriptState->contextIsValid())
return;
ExecutionContext* executionContext = scriptState->getExecutionContext();
if (!executionContext)
return;
ASSERT(executionContext->isWorkerGlobalScope());
WorkerOrWorkletScriptController* scriptController =
toWorkerGlobalScope(executionContext)->scriptController();
ASSERT(scriptController);
promiseRejectHandler(data, *scriptController->getRejectedPromises(),
scriptState);
}
static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Frame* target = findFrame(isolate, host, data);
if (!target)
return;
DOMWindow* targetWindow = target->domWindow();
// FIXME: We should modify V8 to pass in more contextual information (context,
// property, and object).
ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0,
isolate->GetCurrentContext()->Global(),
isolate);
exceptionState.throwSecurityError(
targetWindow->sanitizedCrossDomainAccessErrorMessage(
currentDOMWindow(isolate)),
targetWindow->crossDomainAccessErrorMessage(currentDOMWindow(isolate)));
}
static bool codeGenerationCheckCallbackInMainThread(
v8::Local<v8::Context> context) {
if (ExecutionContext* executionContext = toExecutionContext(context)) {
if (ContentSecurityPolicy* policy =
toDocument(executionContext)->contentSecurityPolicy())
return policy->allowEval(ScriptState::from(context),
ContentSecurityPolicy::SendReport,
ContentSecurityPolicy::WillThrowException);
}
return false;
}
static void initializeV8Common(v8::Isolate* isolate) {
isolate->AddGCPrologueCallback(V8GCController::gcPrologue);
isolate->AddGCEpilogueCallback(V8GCController::gcEpilogue);
if (RuntimeEnabledFeatures::traceWrappablesEnabled()) {
std::unique_ptr<ScriptWrappableVisitor> visitor(
new ScriptWrappableVisitor(isolate));
V8PerIsolateData::from(isolate)->setScriptWrappableVisitor(
std::move(visitor));
isolate->SetEmbedderHeapTracer(
V8PerIsolateData::from(isolate)->scriptWrappableVisitor());
}
v8::Debug::SetLiveEditEnabled(isolate, false);
isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
}
namespace {
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
// Allocate() methods return null to signal allocation failure to V8, which
// should respond by throwing a RangeError, per
// http://www.ecma-international.org/ecma-262/6.0/#sec-createbytedatablock.
void* Allocate(size_t size) override {
void* data;
WTF::ArrayBufferContents::allocateMemoryOrNull(
size, WTF::ArrayBufferContents::ZeroInitialize, data);
return data;
}
void* AllocateUninitialized(size_t size) override {
void* data;
WTF::ArrayBufferContents::allocateMemoryOrNull(
size, WTF::ArrayBufferContents::DontInitialize, data);
return data;
}
void Free(void* data, size_t size) override {
WTF::ArrayBufferContents::freeMemory(data, size);
}
};
} // namespace
static void adjustAmountOfExternalAllocatedMemory(int64_t diff) {
#if ENABLE(ASSERT)
DEFINE_THREAD_SAFE_STATIC_LOCAL(int64_t, processTotal, new int64_t(0));
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, new Mutex);
{
MutexLocker locker(mutex);
processTotal += diff;
DCHECK_GE(processTotal, 0) << "total amount = " << processTotal
<< ", diff = " << diff;
}
#endif
v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(diff);
}
void V8Initializer::initializeMainThread() {
ASSERT(isMainThread());
WTF::ArrayBufferContents::initialize(adjustAmountOfExternalAllocatedMemory);
DEFINE_STATIC_LOCAL(ArrayBufferAllocator, arrayBufferAllocator, ());
auto v8ExtrasMode = RuntimeEnabledFeatures::experimentalV8ExtrasEnabled()
? gin::IsolateHolder::kStableAndExperimentalV8Extras
: gin::IsolateHolder::kStableV8Extras;
gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
v8ExtrasMode, &arrayBufferAllocator);
v8::Isolate* isolate = V8PerIsolateData::initialize();
initializeV8Common(isolate);
isolate->SetOOMErrorHandler(reportOOMErrorInMainThread);
isolate->SetFatalErrorHandler(reportFatalErrorInMainThread);
isolate->AddMessageListener(messageHandlerInMainThread);
isolate->SetFailedAccessCheckCallbackFunction(
failedAccessCheckCallbackInMainThread);
isolate->SetAllowCodeGenerationFromStringsCallback(
codeGenerationCheckCallbackInMainThread);
if (RuntimeEnabledFeatures::v8IdleTasksEnabled()) {
WebScheduler* scheduler = Platform::current()->currentThread()->scheduler();
V8PerIsolateData::enableIdleTasks(isolate,
makeUnique<V8IdleTaskRunner>(scheduler));
}
isolate->SetPromiseRejectCallback(promiseRejectHandlerInMainThread);
if (v8::HeapProfiler* profiler = isolate->GetHeapProfiler())
profiler->SetWrapperClassInfoProvider(
WrapperTypeInfo::NodeClassId, &RetainedDOMInfo::createRetainedDOMInfo);
ASSERT(ThreadState::mainThreadState());
ThreadState::mainThreadState()->addInterruptor(
makeUnique<V8IsolateInterruptor>(isolate));
if (RuntimeEnabledFeatures::traceWrappablesEnabled()) {
ThreadState::mainThreadState()->registerTraceDOMWrappers(
isolate, V8GCController::traceDOMWrappers,
ScriptWrappableVisitor::invalidateDeadObjectsInMarkingDeque,
ScriptWrappableVisitor::performCleanup);
} else {
ThreadState::mainThreadState()->registerTraceDOMWrappers(
isolate, V8GCController::traceDOMWrappers, nullptr, nullptr);
}
V8PerIsolateData::from(isolate)->setThreadDebugger(
makeUnique<MainThreadDebugger>(isolate));
}
void V8Initializer::shutdownMainThread() {
ASSERT(isMainThread());
v8::Isolate* isolate = V8PerIsolateData::mainThreadIsolate();
V8PerIsolateData::willBeDestroyed(isolate);
V8PerIsolateData::destroy(isolate);
}
static void reportFatalErrorInWorker(const char* location,
const char* message) {
// FIXME: We temporarily deal with V8 internal error situations such as
// out-of-memory by crashing the worker.
CRASH();
}
static void messageHandlerInWorker(v8::Local<v8::Message> message,
v8::Local<v8::Value> data) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
V8PerIsolateData* perIsolateData = V8PerIsolateData::from(isolate);
// During the frame teardown, there may not be a valid context.
ScriptState* scriptState = ScriptState::current(isolate);
if (!scriptState->contextIsValid())
return;
// Exceptions that occur in error handler should be ignored since in that case
// WorkerGlobalScope::dispatchErrorEvent will send the exception to the worker
// object.
if (perIsolateData->isReportingException())
return;
perIsolateData->setReportingException(true);
ExecutionContext* context = scriptState->getExecutionContext();
std::unique_ptr<SourceLocation> location =
SourceLocation::fromMessage(isolate, message, context);
ErrorEvent* event =
ErrorEvent::create(toCoreStringWithNullCheck(message->Get()),
std::move(location), &scriptState->world());
AccessControlStatus corsStatus = message->IsSharedCrossOrigin()
? SharableCrossOrigin
: NotSharableCrossOrigin;
// If execution termination has been triggered as part of constructing
// the error event from the v8::Message, quietly leave.
if (!isolate->IsExecutionTerminating()) {
V8ErrorHandler::storeExceptionOnErrorEventWrapper(
scriptState, event, data, scriptState->context()->Global());
scriptState->getExecutionContext()->dispatchErrorEvent(event, corsStatus);
}
perIsolateData->setReportingException(false);
}
// Stack size for workers is limited to 500KB because default stack size for
// secondary threads is 512KB on Mac OS X. See GetDefaultThreadStackSize() in
// base/threading/platform_thread_mac.mm for details.
static const int kWorkerMaxStackSize = 500 * 1024;
// This function uses a local stack variable to determine the isolate's stack
// limit. AddressSanitizer may relocate that local variable to a fake stack,
// which may lead to problems during JavaScript execution. Therefore we disable
// AddressSanitizer for V8Initializer::initializeWorker().
NO_SANITIZE_ADDRESS
void V8Initializer::initializeWorker(v8::Isolate* isolate) {
initializeV8Common(isolate);
isolate->AddMessageListener(messageHandlerInWorker);
isolate->SetFatalErrorHandler(reportFatalErrorInWorker);
uint32_t here;
isolate->SetStackLimit(reinterpret_cast<uintptr_t>(&here) -
kWorkerMaxStackSize);
isolate->SetPromiseRejectCallback(promiseRejectHandlerInWorker);
}
} // namespace blink
| 39.228137 | 80 | 0.718571 | [
"object"
] |
11f15f11f8764cc8117ee61389dda3f82bc1f030 | 74,526 | cc | C++ | chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/options/chromeos/internet_options_handler.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 1 | 2020-11-04T07:27:33.000Z | 2020-11-04T07:27:33.000Z | // 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 "chrome/browser/ui/webui/options/chromeos/internet_options_handler.h"
#include <ctype.h>
#include <map>
#include <string>
#include <vector>
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "base/base64.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/i18n/time_formatting.h"
#include "base/json/json_writer.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/choose_mobile_network_dialog.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/cros_network_functions.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/onc_constants.h"
#include "chrome/browser/chromeos/enrollment_dialog_view.h"
#include "chrome/browser/chromeos/mobile_config.h"
#include "chrome/browser/chromeos/options/network_config_view.h"
#include "chrome/browser/chromeos/proxy_config_service_impl.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/sim_dialog_delegate.h"
#include "chrome/browser/chromeos/status/network_menu_icon.h"
#include "chrome/browser/net/pref_proxy_config_tracker.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/webui/web_ui_util.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/time_format.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/display.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/widget.h"
namespace {
// Keys for the network description dictionary passed to the web ui. Make sure
// to keep the strings in sync with what the JavaScript side uses.
const char kNetworkInfoKeyActivationState[] = "activation_state";
const char kNetworkInfoKeyConnectable[] = "connectable";
const char kNetworkInfoKeyConnected[] = "connected";
const char kNetworkInfoKeyConnecting[] = "connecting";
const char kNetworkInfoKeyIconURL[] = "iconURL";
const char kNetworkInfoKeyNeedsNewPlan[] = "needs_new_plan";
const char kNetworkInfoKeyNetworkName[] = "networkName";
const char kNetworkInfoKeyNetworkStatus[] = "networkStatus";
const char kNetworkInfoKeyNetworkType[] = "networkType";
const char kNetworkInfoKeyRemembered[] = "remembered";
const char kNetworkInfoKeyServicePath[] = "servicePath";
const char kNetworkInfoKeyPolicyManaged[] = "policyManaged";
// These are keys for getting IP information from the web ui.
const char kIpConfigAddress[] = "address";
const char kIpConfigPrefixLength[] = "prefixLength";
const char kIpConfigNetmask[] = "netmask";
const char kIpConfigGateway[] = "gateway";
const char kIpConfigNameServers[] = "nameServers";
const char kIpConfigAutoConfig[] = "ipAutoConfig";
// These are types of name server selections from the web ui.
const char kNameServerTypeAutomatic[] = "automatic";
const char kNameServerTypeGoogle[] = "google";
const char kNameServerTypeUser[] = "user";
// These are dictionary names used to send data to the web ui.
const char kDictionaryIpConfig[] = "ipconfig";
const char kDictionaryStaticIp[] = "staticIP";
const char kDictionarySavedIp[] = "savedIP";
// Google public name servers (DNS).
const char kGoogleNameServers[] = "8.8.4.4,8.8.8.8";
// Functions we call in JavaScript.
const char kRefreshNetworkDataFunction[] =
"options.network.NetworkList.refreshNetworkData";
const char kShowDetailedInfoFunction[] =
"options.internet.DetailsInternetPage.showDetailedInfo";
const char kUpdateCarrierFunction[] =
"options.internet.DetailsInternetPage.updateCarrier";
const char kUpdateCellularPlansFunction[] =
"options.internet.DetailsInternetPage.updateCellularPlans";
const char kUpdateSecurityTabFunction[] =
"options.internet.DetailsInternetPage.updateSecurityTab";
// These are used to register message handlers with JavaScript.
const char kBuyDataPlanMessage[] = "buyDataPlan";
const char kChangePinMessage[] = "changePin";
const char kDisableCellularMessage[] = "disableCellular";
const char kDisableWifiMessage[] = "disableWifi";
const char kDisableWimaxMessage[] = "disableWimax";
const char kEnableCellularMessage[] = "enableCellular";
const char kEnableWifiMessage[] = "enableWifi";
const char kEnableWimaxMessage[] = "enableWimax";
const char kNetworkCommandMessage[] = "networkCommand";
const char kRefreshCellularPlanMessage[] = "refreshCellularPlan";
const char kRefreshNetworksMessage[] = "refreshNetworks";
const char kSetApnMessage[] = "setApn";
const char kSetAutoConnectMessage[] = "setAutoConnect";
const char kSetCarrierMessage[] = "setCarrier";
const char kSetIPConfigMessage[] = "setIPConfig";
const char kSetPreferNetworkMessage[] = "setPreferNetwork";
const char kSetServerHostname[] = "setServerHostname";
const char kSetSimCardLockMessage[] = "setSimCardLock";
const char kShowMorePlanInfoMessage[] = "showMorePlanInfo";
// These are strings used to communicate with JavaScript.
const char kTagAccessLocked[] = "accessLocked";
const char kTagActivate[] = "activate";
const char kTagActivated[] = "activated";
const char kTagActivationState[] = "activationState";
const char kTagAddConnection[] = "add";
const char kTagAirplaneMode[] = "airplaneMode";
const char kTagApn[] = "apn";
const char kTagAutoConnect[] = "autoConnect";
const char kTagBssid[] = "bssid";
const char kTagCarrierSelectFlag[] = "showCarrierSelect";
const char kTagCarrierUrl[] = "carrierUrl";
const char kTagCellularAvailable[] = "cellularAvailable";
const char kTagCellularBusy[] = "cellularBusy";
const char kTagCellularEnabled[] = "cellularEnabled";
const char kTagCellularSupportsScan[] = "cellularSupportsScan";
const char kTagConnect[] = "connect";
const char kTagConnected[] = "connected";
const char kTagConnecting[] = "connecting";
const char kTagConnectionState[] = "connectionState";
const char kTagControlledBy[] = "controlledBy";
const char kTagDataRemaining[] = "dataRemaining";
const char kTagDeviceConnected[] = "deviceConnected";
const char kTagDisconnect[] = "disconnect";
const char kTagEncryption[] = "encryption";
const char kTagErrorState[] = "errorState";
const char kTagEsn[] = "esn";
const char kTagFirmwareRevision[] = "firmwareRevision";
const char kTagForget[] = "forget";
const char kTagFrequency[] = "frequency";
const char kTagGsm[] = "gsm";
const char kTagHardwareAddress[] = "hardwareAddress";
const char kTagHardwareRevision[] = "hardwareRevision";
const char kTagIdentity[] = "identity";
const char kTagImei[] = "imei";
const char kTagImsi[] = "imsi";
const char kTagLanguage[] = "language";
const char kTagLastGoodApn[] = "lastGoodApn";
const char kTagLocalizedName[] = "localizedName";
const char kTagManufacturer[] = "manufacturer";
const char kTagMdn[] = "mdn";
const char kTagMeid[] = "meid";
const char kTagMin[] = "min";
const char kTagModelId[] = "modelId";
const char kTagName[] = "name";
const char kTagNameServersGoogle[] = "nameServersGoogle";
const char kTagNameServerType[] = "nameServerType";
const char kTagNeedsPlan[] = "needsPlan";
const char kTagNetworkId[] = "networkId";
const char kTagNetworkName[] = "networkName";
const char kTagNetworkTechnology[] = "networkTechnology";
const char kTagOperatorCode[] = "operatorCode";
const char kTagOperatorName[] = "operatorName";
const char kTagOptions[] = "options";
const char kTagPassword[] = "password";
const char kTagPlanExpires[] = "planExpires";
const char kTagPlans[] = "plans";
const char kTagPlanSummary[] = "planSummary";
const char kTagPlanType[] = "planType";
const char kTagPolicy[] = "policy";
const char kTagPreferred[] = "preferred";
const char kTagPrlVersion[] = "prlVersion";
const char kTagProvider_type[] = "provider_type";
const char kTagProviderApnList[] = "providerApnList";
const char kTagRecommended[] = "recommended";
const char kTagRecommendedValue[] = "recommendedValue";
const char kTagRemembered[] = "remembered";
const char kTagRememberedList[] = "rememberedList";
const char kTagRestrictedPool[] = "restrictedPool";
const char kTagRoamingState[] = "roamingState";
const char kTagServerHostname[] = "serverHostname";
const char kTagService_name[] = "service_name";
const char kTagCarriers[] = "carriers";
const char kTagCurrentCarrierIndex[] = "currentCarrierIndex";
const char kTagServiceName[] = "serviceName";
const char kTagServicePath[] = "servicePath";
const char kTagShared[] = "shared";
const char kTagShowActivateButton[] = "showActivateButton";
const char kTagShowBuyButton[] = "showBuyButton";
const char kTagShowPreferred[] = "showPreferred";
const char kTagShowProxy[] = "showProxy";
const char kTagShowStaticIPConfig[] = "showStaticIPConfig";
const char kTagShowViewAccountButton[] = "showViewAccountButton";
const char kTagSimCardLockEnabled[] = "simCardLockEnabled";
const char kTagSsid[] = "ssid";
const char kTagStrength[] = "strength";
const char kTagSupportUrl[] = "supportUrl";
const char kTagTrue[] = "true";
const char kTagType[] = "type";
const char kTagUsername[] = "username";
const char kTagValue[] = "value";
const char kTagVpnList[] = "vpnList";
const char kTagWarning[] = "warning";
const char kTagWifiAvailable[] = "wifiAvailable";
const char kTagWifiBusy[] = "wifiBusy";
const char kTagWifiEnabled[] = "wifiEnabled";
const char kTagWimaxAvailable[] = "wimaxAvailable";
const char kTagWimaxBusy[] = "wimaxBusy";
const char kTagWimaxEnabled[] = "wimaxEnabled";
const char kTagWiredList[] = "wiredList";
const char kTagWirelessList[] = "wirelessList";
const char kToggleAirplaneModeMessage[] = "toggleAirplaneMode";
// A helper class for building network information dictionaries to be sent to
// the webui code.
class NetworkInfoDictionary {
public:
// Initializes the dictionary with default values.
explicit NetworkInfoDictionary(ui::ScaleFactor icon_scale_factor);
// Copies in service path, connect{ing|ed|able} flags and connection type from
// the provided network object. Also chooses an appropriate icon based on the
// network type.
NetworkInfoDictionary(const chromeos::Network* network,
ui::ScaleFactor icon_scale_factor);
// Initializes a remembered network entry, pulling information from the passed
// network object and the corresponding remembered network object. |network|
// may be NULL.
NetworkInfoDictionary(const chromeos::Network* network,
const chromeos::Network* remembered,
ui::ScaleFactor icon_scale_factor);
// Setters for filling in information.
void set_service_path(const std::string& service_path) {
service_path_ = service_path;
}
void set_icon(const gfx::ImageSkia& icon) {
gfx::ImageSkiaRep image_rep = icon.GetRepresentation(icon_scale_factor_);
icon_url_ = icon.isNull() ? "" : web_ui_util::GetBitmapDataUrl(
image_rep.sk_bitmap());
}
void set_name(const std::string& name) {
name_ = name;
}
void set_connecting(bool connecting) {
connecting_ = connecting;
}
void set_connected(bool connected) {
connected_ = connected;
}
void set_connectable(bool connectable) {
connectable_ = connectable;
}
void set_connection_type(chromeos::ConnectionType connection_type) {
connection_type_ = connection_type;
}
void set_remembered(bool remembered) {
remembered_ = remembered;
}
void set_shared(bool shared) {
shared_ = shared;
}
void set_activation_state(chromeos::ActivationState activation_state) {
activation_state_ = activation_state;
}
void set_needs_new_plan(bool needs_new_plan) {
needs_new_plan_ = needs_new_plan;
}
void set_policy_managed(bool policy_managed) {
policy_managed_ = policy_managed;
}
// Builds the DictionaryValue representation from the previously set
// parameters. Ownership of the returned pointer is transferred to the caller.
DictionaryValue* BuildDictionary();
private:
// Values to be filled into the dictionary.
std::string service_path_;
std::string icon_url_;
std::string name_;
bool connecting_;
bool connected_;
bool connectable_;
chromeos::ConnectionType connection_type_;
bool remembered_;
bool shared_;
chromeos::ActivationState activation_state_;
bool needs_new_plan_;
bool policy_managed_;
ui::ScaleFactor icon_scale_factor_;
DISALLOW_COPY_AND_ASSIGN(NetworkInfoDictionary);
};
NetworkInfoDictionary::NetworkInfoDictionary(
ui::ScaleFactor icon_scale_factor)
: icon_scale_factor_(icon_scale_factor) {
set_connecting(false);
set_connected(false);
set_connectable(false);
set_remembered(false);
set_shared(false);
set_activation_state(chromeos::ACTIVATION_STATE_UNKNOWN);
set_needs_new_plan(false);
set_policy_managed(false);
}
NetworkInfoDictionary::NetworkInfoDictionary(const chromeos::Network* network,
ui::ScaleFactor icon_scale_factor)
: icon_scale_factor_(icon_scale_factor) {
set_service_path(network->service_path());
set_icon(chromeos::NetworkMenuIcon::GetImage(network,
chromeos::NetworkMenuIcon::COLOR_DARK));
set_name(network->name());
set_connecting(network->connecting());
set_connected(network->connected());
set_connectable(network->connectable());
set_connection_type(network->type());
set_remembered(false);
set_shared(false);
set_needs_new_plan(false);
set_policy_managed(network->ui_data().is_managed());
}
NetworkInfoDictionary::NetworkInfoDictionary(
const chromeos::Network* network,
const chromeos::Network* remembered,
ui::ScaleFactor icon_scale_factor)
: icon_scale_factor_(icon_scale_factor) {
set_service_path(remembered->service_path());
set_icon(chromeos::NetworkMenuIcon::GetImage(
network ? network : remembered, chromeos::NetworkMenuIcon::COLOR_DARK));
set_name(remembered->name());
set_connecting(network ? network->connecting() : false);
set_connected(network ? network->connected() : false);
set_connectable(true);
set_connection_type(remembered->type());
set_remembered(true);
set_shared(remembered->profile_type() == chromeos::PROFILE_SHARED);
set_needs_new_plan(false);
set_policy_managed(remembered->ui_data().is_managed());
}
DictionaryValue* NetworkInfoDictionary::BuildDictionary() {
std::string status;
if (remembered_) {
if (shared_)
status = l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SHARED_NETWORK);
} else {
// 802.1X networks can be connected but not have saved credentials, and
// hence be "not configured". Give preference to the "connected" and
// "connecting" states. http://crosbug.com/14459
int connection_state = IDS_STATUSBAR_NETWORK_DEVICE_DISCONNECTED;
if (connected_)
connection_state = IDS_STATUSBAR_NETWORK_DEVICE_CONNECTED;
else if (connecting_)
connection_state = IDS_STATUSBAR_NETWORK_DEVICE_CONNECTING;
else if (!connectable_)
connection_state = IDS_STATUSBAR_NETWORK_DEVICE_NOT_CONFIGURED;
status = l10n_util::GetStringUTF8(connection_state);
if (connection_type_ == chromeos::TYPE_CELLULAR) {
if (needs_new_plan_) {
status = l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_NO_PLAN_LABEL);
} else if (activation_state_ != chromeos::ACTIVATION_STATE_ACTIVATED) {
status.append(" / ");
status.append(chromeos::CellularNetwork::ActivationStateToString(
activation_state_));
}
}
}
scoped_ptr<DictionaryValue> network_info(new DictionaryValue());
network_info->SetInteger(kNetworkInfoKeyActivationState,
static_cast<int>(activation_state_));
network_info->SetBoolean(kNetworkInfoKeyConnectable, connectable_);
network_info->SetBoolean(kNetworkInfoKeyConnected, connected_);
network_info->SetBoolean(kNetworkInfoKeyConnecting, connecting_);
network_info->SetString(kNetworkInfoKeyIconURL, icon_url_);
network_info->SetBoolean(kNetworkInfoKeyNeedsNewPlan, needs_new_plan_);
network_info->SetString(kNetworkInfoKeyNetworkName, name_);
network_info->SetString(kNetworkInfoKeyNetworkStatus, status);
network_info->SetInteger(kNetworkInfoKeyNetworkType,
static_cast<int>(connection_type_));
network_info->SetBoolean(kNetworkInfoKeyRemembered, remembered_);
network_info->SetString(kNetworkInfoKeyServicePath, service_path_);
network_info->SetBoolean(kNetworkInfoKeyPolicyManaged, policy_managed_);
return network_info.release();
}
// Pulls IP information out of a shill service properties dictionary. If
// |static_ip| is true, then it fetches "StaticIP.*" properties. If not, then it
// fetches "SavedIP.*" properties. Caller must take ownership of returned
// dictionary. If non-NULL, |ip_parameters_set| returns a count of the number
// of IP routing parameters that get set.
DictionaryValue* BuildIPInfoDictionary(const DictionaryValue& shill_properties,
bool static_ip,
int* routing_parameters_set) {
std::string address_key;
std::string prefix_len_key;
std::string gateway_key;
std::string name_servers_key;
if (static_ip) {
address_key = shill::kStaticIPAddressProperty;
prefix_len_key = shill::kStaticIPPrefixlenProperty;
gateway_key = shill::kStaticIPGatewayProperty;
name_servers_key = shill::kStaticIPNameServersProperty;
} else {
address_key = shill::kSavedIPAddressProperty;
prefix_len_key = shill::kSavedIPPrefixlenProperty;
gateway_key = shill::kSavedIPGatewayProperty;
name_servers_key = shill::kSavedIPNameServersProperty;
}
scoped_ptr<DictionaryValue> ip_info_dict(new DictionaryValue);
std::string address;
int routing_parameters = 0;
if (shill_properties.GetStringWithoutPathExpansion(address_key, &address)) {
ip_info_dict->SetString(kIpConfigAddress, address);
VLOG(2) << "Found " << address_key << ": " << address;
routing_parameters++;
}
int prefix_len = -1;
if (shill_properties.GetIntegerWithoutPathExpansion(
prefix_len_key, &prefix_len)) {
ip_info_dict->SetInteger(kIpConfigPrefixLength, prefix_len);
ip_info_dict->SetString(kIpConfigNetmask,
chromeos::CrosPrefixLengthToNetmask(prefix_len));
VLOG(2) << "Found " << prefix_len_key << ": "
<< prefix_len
<< " (" << chromeos::CrosPrefixLengthToNetmask(prefix_len) << ")";
routing_parameters++;
}
std::string gateway;
if (shill_properties.GetStringWithoutPathExpansion(gateway_key, &gateway)) {
ip_info_dict->SetString(kIpConfigGateway, gateway);
VLOG(2) << "Found " << gateway_key << ": " << gateway;
routing_parameters++;
}
if (routing_parameters_set)
*routing_parameters_set = routing_parameters;
std::string name_servers;
if (shill_properties.GetStringWithoutPathExpansion(
name_servers_key, &name_servers)) {
ip_info_dict->SetString(kIpConfigNameServers, name_servers);
VLOG(2) << "Found " << name_servers_key << ": " << name_servers;
}
return ip_info_dict.release();
}
static bool CanForgetNetworkType(int type) {
return type == chromeos::TYPE_WIFI ||
type == chromeos::TYPE_WIMAX ||
type == chromeos::TYPE_VPN;
}
static bool CanAddNetworkType(int type) {
return type == chromeos::TYPE_WIFI ||
type == chromeos::TYPE_VPN ||
type == chromeos::TYPE_CELLULAR;
}
// Decorate pref value as CoreOptionsHandler::CreateValueForPref() does and
// store it under |key| in |settings|. Takes ownership of |value|.
void SetValueDictionary(
DictionaryValue* settings,
const char* key,
base::Value* value,
const chromeos::NetworkPropertyUIData& ui_data) {
DictionaryValue* dict = new DictionaryValue();
// DictionaryValue::Set() takes ownership of |value|.
dict->Set(kTagValue, value);
const base::Value* recommended_value = ui_data.default_value();
if (ui_data.managed())
dict->SetString(kTagControlledBy, kTagPolicy);
else if (recommended_value && recommended_value->Equals(value))
dict->SetString(kTagControlledBy, kTagRecommended);
if (recommended_value)
dict->Set(kTagRecommendedValue, recommended_value->DeepCopy());
settings->Set(key, dict);
}
// Fills |dictionary| with the configuration details of |vpn|. |onc| is required
// for augmenting the policy-managed information.
void PopulateVPNDetails(
const chromeos::VirtualNetwork* vpn,
const base::DictionaryValue& onc,
DictionaryValue* dictionary) {
dictionary->SetString(kTagService_name, vpn->name());
bool remembered = (vpn->profile_type() != chromeos::PROFILE_NONE);
dictionary->SetBoolean(kTagRemembered, remembered);
dictionary->SetString(kTagProvider_type, vpn->GetProviderTypeString());
dictionary->SetString(kTagUsername, vpn->username());
chromeos::NetworkPropertyUIData hostname_ui_data;
hostname_ui_data.ParseOncProperty(
vpn->ui_data(), &onc,
base::StringPrintf("%s.%s",
chromeos::onc::kVPN,
chromeos::onc::vpn::kHost));
SetValueDictionary(dictionary, kTagServerHostname,
Value::CreateStringValue(vpn->server_hostname()),
hostname_ui_data);
}
// Given a list of supported carrier's by the device, return the index of
// the carrier the device is currently using.
int FindCurrentCarrierIndex(const base::ListValue* carriers,
const chromeos::NetworkDevice* device) {
DCHECK(carriers);
DCHECK(device);
bool gsm = (device->technology_family() == chromeos::TECHNOLOGY_FAMILY_GSM);
int index = 0;
for (base::ListValue::const_iterator it = carriers->begin();
it != carriers->end();
++it, ++index) {
std::string value;
if ((*it)->GetAsString(&value)) {
// For GSM devices the device name will be empty, so simply select
// the Generic UMTS carrier option if present.
if (gsm && (value == shill::kCarrierGenericUMTS)) {
return index;
} else {
// For other carriers, the service name will match the carrier name.
if (value == device->carrier())
return index;
}
}
}
return -1;
}
} // namespace
namespace options {
InternetOptionsHandler::InternetOptionsHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
registrar_.Add(this, chrome::NOTIFICATION_REQUIRE_PIN_SETTING_CHANGE_ENDED,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_ENTER_PIN_ENDED,
content::NotificationService::AllSources());
cros_ = chromeos::CrosLibrary::Get()->GetNetworkLibrary();
if (cros_) {
cros_->AddNetworkManagerObserver(this);
cros_->AddCellularDataPlanObserver(this);
MonitorNetworks();
}
}
InternetOptionsHandler::~InternetOptionsHandler() {
if (cros_) {
cros_->RemoveNetworkManagerObserver(this);
cros_->RemoveCellularDataPlanObserver(this);
cros_->RemoveObserverForAllNetworks(this);
}
}
void InternetOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
static OptionsStringResource resources[] = {
// Main settings page.
{ "ethernetTitle", IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET },
{ "wifiTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_WIFI_NETWORK },
// TODO(zelidrag): Change details title to Wimax once we get strings.
{ "wimaxTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_CELLULAR_NETWORK },
{ "cellularTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_CELLULAR_NETWORK },
{ "vpnTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_PRIVATE_NETWORK },
{ "airplaneModeTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_AIRPLANE_MODE },
{ "airplaneModeLabel", IDS_OPTIONS_SETTINGS_NETWORK_AIRPLANE_MODE_LABEL },
{ "networkNotConnected", IDS_OPTIONS_SETTINGS_NETWORK_NOT_CONNECTED },
{ "networkConnected", IDS_CHROMEOS_NETWORK_STATE_READY },
{ "joinOtherNetwork", IDS_OPTIONS_SETTINGS_NETWORK_OTHER },
{ "networkOffline", IDS_OPTIONS_SETTINGS_NETWORK_OFFLINE },
{ "networkDisabled", IDS_OPTIONS_SETTINGS_NETWORK_DISABLED },
{ "networkOnline", IDS_OPTIONS_SETTINGS_NETWORK_ONLINE },
{ "networkOptions", IDS_OPTIONS_SETTINGS_NETWORK_OPTIONS },
{ "turnOffWifi", IDS_OPTIONS_SETTINGS_NETWORK_DISABLE_WIFI },
{ "turnOffCellular", IDS_OPTIONS_SETTINGS_NETWORK_DISABLE_CELLULAR },
{ "disconnectNetwork", IDS_OPTIONS_SETTINGS_DISCONNECT },
{ "preferredNetworks", IDS_OPTIONS_SETTINGS_PREFERRED_NETWORKS_LABEL },
{ "preferredNetworksPage", IDS_OPTIONS_SETTINGS_PREFERRED_NETWORKS_TITLE },
{ "useSharedProxies", IDS_OPTIONS_SETTINGS_USE_SHARED_PROXIES },
{ "addConnectionTitle",
IDS_OPTIONS_SETTINGS_SECTION_TITLE_ADD_CONNECTION },
{ "addConnectionWifi", IDS_OPTIONS_SETTINGS_ADD_CONNECTION_WIFI },
{ "addConnectionVPN", IDS_STATUSBAR_NETWORK_ADD_VPN },
{ "otherCellularNetworks", IDS_OPTIONS_SETTINGS_OTHER_CELLULAR_NETWORKS },
{ "enableDataRoaming", IDS_OPTIONS_SETTINGS_ENABLE_DATA_ROAMING },
{ "disableDataRoaming", IDS_OPTIONS_SETTINGS_DISABLE_DATA_ROAMING },
{ "dataRoamingDisableToggleTooltip",
IDS_OPTIONS_SETTINGS_TOGGLE_DATA_ROAMING_RESTRICTION },
{ "activateNetwork", IDS_STATUSBAR_NETWORK_DEVICE_ACTIVATE },
// Internet details dialog.
{ "changeProxyButton",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CHANGE_PROXY_BUTTON },
{ "managedNetwork", IDS_OPTIONS_SETTINGS_MANAGED_NETWORK },
{ "wifiNetworkTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_CONNECTION },
{ "vpnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_VPN },
{ "cellularPlanTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_PLAN },
{ "cellularConnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_CONNECTION },
{ "cellularDeviceTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_DEVICE },
{ "networkTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_NETWORK },
{ "securityTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_SECURITY },
{ "proxyTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_PROXY },
{ "connectionState", IDS_OPTIONS_SETTINGS_INTERNET_CONNECTION_STATE },
{ "inetAddress", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_ADDRESS },
{ "inetNetmask", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SUBNETMASK },
{ "inetGateway", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_GATEWAY },
{ "inetNameServers", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_DNSSERVER },
{ "ipAutomaticConfiguration",
IDS_OPTIONS_SETTINGS_INTERNET_IP_AUTOMATIC_CONFIGURATION },
{ "automaticNameServers",
IDS_OPTIONS_SETTINGS_INTERNET_AUTOMATIC_NAME_SERVERS },
{ "userNameServer1", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_1 },
{ "userNameServer2", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_2 },
{ "userNameServer3", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_3 },
{ "userNameServer4", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVER_4 },
{ "googleNameServers", IDS_OPTIONS_SETTINGS_INTERNET_GOOGLE_NAME_SERVERS },
{ "userNameServers", IDS_OPTIONS_SETTINGS_INTERNET_USER_NAME_SERVERS },
{ "hardwareAddress",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_HARDWARE_ADDRESS },
{ "detailsInternetDismiss", IDS_CLOSE },
{ "activateButton", IDS_OPTIONS_SETTINGS_ACTIVATE },
{ "buyplanButton", IDS_OPTIONS_SETTINGS_BUY_PLAN },
{ "connectButton", IDS_OPTIONS_SETTINGS_CONNECT },
{ "disconnectButton", IDS_OPTIONS_SETTINGS_DISCONNECT },
{ "viewAccountButton", IDS_STATUSBAR_NETWORK_VIEW_ACCOUNT },
// TODO(zelidrag): Change details title to Wimax once we get strings.
{ "wimaxConnTabLabel", IDS_OPTIONS_SETTINGS_INTERNET_TAB_CONNECTION },
// Wifi Tab.
{ "accessLockedMsg", IDS_STATUSBAR_NETWORK_LOCKED },
{ "inetSsid", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID },
{ "inetBssid", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_BSSID },
{ "inetEncryption",
IDS_OPTIONS_SETTIGNS_INTERNET_OPTIONS_NETWORK_ENCRYPTION },
{ "inetFrequency",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_FREQUENCY },
{ "inetFrequencyFormat",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_FREQUENCY_MHZ },
{ "inetSignalStrength",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_STRENGTH },
{ "inetSignalStrengthFormat",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_STRENGTH_PERCENTAGE },
{ "inetPassProtected",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NET_PROTECTED },
{ "inetNetworkShared",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_SHARED },
{ "inetPreferredNetwork",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PREFER_NETWORK },
{ "inetAutoConnectNetwork",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_AUTO_CONNECT },
{ "inetLogin", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_LOGIN },
{ "inetShowPass", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SHOWPASSWORD },
{ "inetPassPrompt", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSWORD },
{ "inetSsidPrompt", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SSID },
{ "inetStatus", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_STATUS_TITLE },
{ "inetConnect", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CONNECT_TITLE },
// VPN Tab.
{ "inetServiceName",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_SERVICE_NAME },
{ "inetServerHostname",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_SERVER_HOSTNAME },
{ "inetProviderType",
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_PROVIDER_TYPE },
{ "inetUsername", IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_VPN_USERNAME },
// Cellular Tab.
{ "serviceName", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_SERVICE_NAME },
{ "networkTechnology",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_NETWORK_TECHNOLOGY },
{ "operatorName", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_OPERATOR },
{ "operatorCode", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_OPERATOR_CODE },
{ "activationState",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ACTIVATION_STATE },
{ "roamingState", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ROAMING_STATE },
{ "restrictedPool",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_RESTRICTED_POOL },
{ "errorState", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ERROR_STATE },
{ "manufacturer", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_MANUFACTURER },
{ "modelId", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_MODEL_ID },
{ "firmwareRevision",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_FIRMWARE_REVISION },
{ "hardwareRevision",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_HARDWARE_REVISION },
{ "prlVersion", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_PRL_VERSION },
{ "cellularApnLabel", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN },
{ "cellularApnOther", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_OTHER },
{ "cellularApnUsername",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_USERNAME },
{ "cellularApnPassword",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_PASSWORD },
{ "cellularApnUseDefault",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_CLEAR },
{ "cellularApnSet", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_APN_SET },
{ "cellularApnCancel", IDS_CANCEL },
// Security Tab.
{ "accessSecurityTabLink",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_ACCESS_SECURITY_TAB },
{ "lockSimCard", IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_LOCK_SIM_CARD },
{ "changePinButton",
IDS_OPTIONS_SETTINGS_INTERNET_CELLULAR_CHANGE_PIN_BUTTON },
};
RegisterStrings(localized_strings, resources, arraysize(resources));
std::string owner;
chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner);
localized_strings->SetString("ownerUserId", UTF8ToUTF16(owner));
DictionaryValue* network_dictionary = new DictionaryValue;
FillNetworkInfo(network_dictionary);
localized_strings->Set("networkData", network_dictionary);
}
void InternetOptionsHandler::InitializePage() {
cros_->RequestNetworkScan();
}
void InternetOptionsHandler::RegisterMessages() {
// Setup handlers specific to this panel.
web_ui()->RegisterMessageCallback(kNetworkCommandMessage,
base::Bind(&InternetOptionsHandler::NetworkCommandCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kRefreshNetworksMessage,
base::Bind(&InternetOptionsHandler::RefreshNetworksCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kRefreshCellularPlanMessage,
base::Bind(&InternetOptionsHandler::RefreshCellularPlanCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetPreferNetworkMessage,
base::Bind(&InternetOptionsHandler::SetPreferNetworkCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetAutoConnectMessage,
base::Bind(&InternetOptionsHandler::SetAutoConnectCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetIPConfigMessage,
base::Bind(&InternetOptionsHandler::SetIPConfigCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kEnableWifiMessage,
base::Bind(&InternetOptionsHandler::EnableWifiCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kDisableWifiMessage,
base::Bind(&InternetOptionsHandler::DisableWifiCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kEnableCellularMessage,
base::Bind(&InternetOptionsHandler::EnableCellularCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kDisableCellularMessage,
base::Bind(&InternetOptionsHandler::DisableCellularCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kEnableWimaxMessage,
base::Bind(&InternetOptionsHandler::EnableWimaxCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kDisableWimaxMessage,
base::Bind(&InternetOptionsHandler::DisableWimaxCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kBuyDataPlanMessage,
base::Bind(&InternetOptionsHandler::BuyDataPlanCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kShowMorePlanInfoMessage,
base::Bind(&InternetOptionsHandler::ShowMorePlanInfoCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetApnMessage,
base::Bind(&InternetOptionsHandler::SetApnCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetCarrierMessage,
base::Bind(&InternetOptionsHandler::SetCarrierCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetSimCardLockMessage,
base::Bind(&InternetOptionsHandler::SetSimCardLockCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kChangePinMessage,
base::Bind(&InternetOptionsHandler::ChangePinCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kToggleAirplaneModeMessage,
base::Bind(&InternetOptionsHandler::ToggleAirplaneModeCallback,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kSetServerHostname,
base::Bind(&InternetOptionsHandler::SetServerHostnameCallback,
base::Unretained(this)));
}
void InternetOptionsHandler::EnableWifiCallback(const ListValue* args) {
cros_->EnableWifiNetworkDevice(true);
}
void InternetOptionsHandler::DisableWifiCallback(const ListValue* args) {
cros_->EnableWifiNetworkDevice(false);
}
void InternetOptionsHandler::EnableCellularCallback(const ListValue* args) {
// TODO(nkostylev): Code duplication, see NetworkMenu::ToggleCellular().
const chromeos::NetworkDevice* mobile = cros_->FindMobileDevice();
if (!mobile) {
LOG(ERROR) << "Didn't find mobile device, it should have been available.";
cros_->EnableCellularNetworkDevice(true);
} else if (!mobile->is_sim_locked()) {
if (mobile->is_sim_absent()) {
std::string setup_url;
chromeos::MobileConfig* config = chromeos::MobileConfig::GetInstance();
if (config->IsReady()) {
const chromeos::MobileConfig::LocaleConfig* locale_config =
config->GetLocaleConfig();
if (locale_config)
setup_url = locale_config->setup_url();
}
if (!setup_url.empty()) {
chrome::ShowSingletonTab(GetAppropriateBrowser(), GURL(setup_url));
} else {
// TODO(nkostylev): Show generic error message. http://crosbug.com/15444
}
} else {
cros_->EnableCellularNetworkDevice(true);
}
} else {
chromeos::SimDialogDelegate::ShowDialog(GetNativeWindow(),
chromeos::SimDialogDelegate::SIM_DIALOG_UNLOCK);
}
}
void InternetOptionsHandler::DisableCellularCallback(const ListValue* args) {
cros_->EnableCellularNetworkDevice(false);
}
void InternetOptionsHandler::EnableWimaxCallback(const ListValue* args) {
cros_->EnableWimaxNetworkDevice(true);
}
void InternetOptionsHandler::DisableWimaxCallback(const ListValue* args) {
cros_->EnableWimaxNetworkDevice(false);
}
void InternetOptionsHandler::ShowMorePlanInfoCallback(const ListValue* args) {
if (!web_ui())
return;
const chromeos::CellularNetwork* cellular = cros_->cellular_network();
if (!cellular)
return;
web_ui()->GetWebContents()->OpenURL(content::OpenURLParams(
cellular->GetAccountInfoUrl(), content::Referrer(),
NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_LINK, false));
}
void InternetOptionsHandler::BuyDataPlanCallback(const ListValue* args) {
if (!web_ui())
return;
std::string service_path;
if (args->GetSize() != 1 || !args->GetString(0, &service_path)) {
NOTREACHED();
return;
}
ash::Shell::GetInstance()->delegate()->OpenMobileSetup(service_path);
}
void InternetOptionsHandler::SetApnCallback(const ListValue* args) {
std::string service_path;
std::string apn;
std::string username;
std::string password;
if (args->GetSize() != 4 ||
!args->GetString(0, &service_path) ||
!args->GetString(1, &apn) ||
!args->GetString(2, &username) ||
!args->GetString(3, &password)) {
NOTREACHED();
return;
}
chromeos::CellularNetwork* network =
cros_->FindCellularNetworkByPath(service_path);
if (network) {
network->SetApn(chromeos::CellularApn(
apn, network->apn().network_id, username, password));
}
}
void InternetOptionsHandler::CarrierStatusCallback(
const std::string& service_path,
chromeos::NetworkMethodErrorType error,
const std::string& error_message) {
UpdateCarrier(error == chromeos::NETWORK_METHOD_ERROR_NONE);
}
void InternetOptionsHandler::SetCarrierCallback(const ListValue* args) {
std::string service_path;
std::string carrier;
if (args->GetSize() != 2 ||
!args->GetString(0, &service_path) ||
!args->GetString(1, &carrier)) {
NOTREACHED();
return;
}
chromeos::NetworkLibrary* cros_net =
chromeos::CrosLibrary::Get()->GetNetworkLibrary();
if (cros_net) {
cros_net->SetCarrier(
carrier,
base::Bind(&InternetOptionsHandler::CarrierStatusCallback,
weak_factory_.GetWeakPtr()));
}
}
void InternetOptionsHandler::SetSimCardLockCallback(const ListValue* args) {
bool require_pin_new_value;
if (!args->GetBoolean(0, &require_pin_new_value)) {
NOTREACHED();
return;
}
// 1. Bring up SIM unlock dialog, pass new RequirePin setting in URL.
// 2. Dialog will ask for current PIN in any case.
// 3. If card is locked it will first call PIN unlock operation
// 4. Then it will call Set RequirePin, passing the same PIN.
// 5. We'll get notified by REQUIRE_PIN_SETTING_CHANGE_ENDED notification.
chromeos::SimDialogDelegate::SimDialogMode mode;
if (require_pin_new_value)
mode = chromeos::SimDialogDelegate::SIM_DIALOG_SET_LOCK_ON;
else
mode = chromeos::SimDialogDelegate::SIM_DIALOG_SET_LOCK_OFF;
chromeos::SimDialogDelegate::ShowDialog(GetNativeWindow(), mode);
}
void InternetOptionsHandler::ChangePinCallback(const ListValue* args) {
chromeos::SimDialogDelegate::ShowDialog(GetNativeWindow(),
chromeos::SimDialogDelegate::SIM_DIALOG_CHANGE_PIN);
}
void InternetOptionsHandler::RefreshNetworksCallback(const ListValue* args) {
cros_->RequestNetworkScan();
}
void InternetOptionsHandler::RefreshNetworkData() {
DictionaryValue dictionary;
FillNetworkInfo(&dictionary);
web_ui()->CallJavascriptFunction(
kRefreshNetworkDataFunction, dictionary);
}
void InternetOptionsHandler::UpdateCarrier(bool success) {
base::FundamentalValue success_value(success);
web_ui()->CallJavascriptFunction(kUpdateCarrierFunction, success_value);
}
void InternetOptionsHandler::OnNetworkManagerChanged(
chromeos::NetworkLibrary* cros) {
if (!web_ui())
return;
MonitorNetworks();
RefreshNetworkData();
}
void InternetOptionsHandler::OnNetworkChanged(
chromeos::NetworkLibrary* cros,
const chromeos::Network* network) {
if (web_ui())
RefreshNetworkData();
}
// Monitor wireless networks for changes. It is only necessary
// to set up individual observers for the cellular networks
// (if any) and for the connected Wi-Fi network (if any). The
// only change we are interested in for Wi-Fi networks is signal
// strength. For non-connected Wi-Fi networks, all information is
// reported via scan results, which trigger network manager
// updates. Only the connected Wi-Fi network has changes reported
// via service property updates.
void InternetOptionsHandler::MonitorNetworks() {
cros_->RemoveObserverForAllNetworks(this);
const chromeos::WifiNetwork* wifi_network = cros_->wifi_network();
if (wifi_network)
cros_->AddNetworkObserver(wifi_network->service_path(), this);
// Always monitor all mobile networks, if any, so that changes
// in network technology, roaming status, and signal strength
// will be shown.
const chromeos::WimaxNetworkVector& wimax_networks =
cros_->wimax_networks();
for (size_t i = 0; i < wimax_networks.size(); ++i) {
chromeos::WimaxNetwork* wimax_network = wimax_networks[i];
cros_->AddNetworkObserver(wimax_network->service_path(), this);
}
const chromeos::CellularNetworkVector& cell_networks =
cros_->cellular_networks();
for (size_t i = 0; i < cell_networks.size(); ++i) {
chromeos::CellularNetwork* cell_network = cell_networks[i];
cros_->AddNetworkObserver(cell_network->service_path(), this);
}
const chromeos::VirtualNetwork* virtual_network = cros_->virtual_network();
if (virtual_network)
cros_->AddNetworkObserver(virtual_network->service_path(), this);
}
void InternetOptionsHandler::OnCellularDataPlanChanged(
chromeos::NetworkLibrary* cros) {
if (!web_ui())
return;
const chromeos::CellularNetwork* cellular = cros_->cellular_network();
if (!cellular)
return;
const chromeos::CellularDataPlanVector* plans =
cros_->GetDataPlans(cellular->service_path());
DictionaryValue connection_plans;
ListValue* plan_list = new ListValue();
if (plans) {
for (chromeos::CellularDataPlanVector::const_iterator iter = plans->begin();
iter != plans->end(); ++iter) {
plan_list->Append(CellularDataPlanToDictionary(*iter));
}
}
connection_plans.SetString(kTagServicePath, cellular->service_path());
connection_plans.SetBoolean(kTagNeedsPlan, cellular->needs_new_plan());
connection_plans.SetBoolean(kTagActivated,
cellular->activation_state() == chromeos::ACTIVATION_STATE_ACTIVATED);
connection_plans.Set(kTagPlans, plan_list);
SetActivationButtonVisibility(cellular,
&connection_plans,
cros_->GetCellularHomeCarrierId());
web_ui()->CallJavascriptFunction(
kUpdateCellularPlansFunction,
connection_plans);
}
void InternetOptionsHandler::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
OptionsPageUIHandler::Observe(type, source, details);
if (type == chrome::NOTIFICATION_REQUIRE_PIN_SETTING_CHANGE_ENDED) {
base::FundamentalValue require_pin(*content::Details<bool>(details).ptr());
web_ui()->CallJavascriptFunction(
kUpdateSecurityTabFunction, require_pin);
} else if (type == chrome::NOTIFICATION_ENTER_PIN_ENDED) {
// We make an assumption (which is valid for now) that the SIM
// unlock dialog is put up only when the user is trying to enable
// mobile data.
bool cancelled = *content::Details<bool>(details).ptr();
if (cancelled)
RefreshNetworkData();
// The case in which the correct PIN was entered and the SIM is
// now unlocked is handled in NetworkMenuButton.
}
}
DictionaryValue* InternetOptionsHandler::CellularDataPlanToDictionary(
const chromeos::CellularDataPlan* plan) {
DictionaryValue* plan_dict = new DictionaryValue();
plan_dict->SetInteger(kTagPlanType, plan->plan_type);
plan_dict->SetString(kTagName, plan->plan_name);
plan_dict->SetString(kTagPlanSummary, plan->GetPlanDesciption());
plan_dict->SetString(kTagDataRemaining, plan->GetDataRemainingDesciption());
plan_dict->SetString(kTagPlanExpires, plan->GetPlanExpiration());
plan_dict->SetString(kTagWarning, plan->GetRemainingWarning());
return plan_dict;
}
void InternetOptionsHandler::SetServerHostnameCallback(const ListValue* args) {
std::string service_path;
std::string server_hostname;
if (args->GetSize() < 2 ||
!args->GetString(0, &service_path) ||
!args->GetString(1, &server_hostname)) {
NOTREACHED();
return;
}
chromeos::VirtualNetwork* vpn = cros_->FindVirtualNetworkByPath(service_path);
if (!vpn)
return;
if (server_hostname != vpn->server_hostname())
vpn->SetServerHostname(server_hostname);
}
void InternetOptionsHandler::SetPreferNetworkCallback(const ListValue* args) {
std::string service_path;
std::string prefer_network_str;
if (args->GetSize() < 2 ||
!args->GetString(0, &service_path) ||
!args->GetString(1, &prefer_network_str)) {
NOTREACHED();
return;
}
chromeos::Network* network = cros_->FindNetworkByPath(service_path);
if (!network)
return;
bool prefer_network = prefer_network_str == kTagTrue;
if (prefer_network != network->preferred())
network->SetPreferred(prefer_network);
}
void InternetOptionsHandler::SetAutoConnectCallback(const ListValue* args) {
std::string service_path;
std::string auto_connect_str;
if (args->GetSize() < 2 ||
!args->GetString(0, &service_path) ||
!args->GetString(1, &auto_connect_str)) {
NOTREACHED();
return;
}
chromeos::Network* network = cros_->FindNetworkByPath(service_path);
if (!network)
return;
bool auto_connect = auto_connect_str == kTagTrue;
if (auto_connect != network->auto_connect())
network->SetAutoConnect(auto_connect);
}
void InternetOptionsHandler::SetIPConfigCallback(const ListValue* args) {
std::string service_path;
bool dhcp_for_ip;
std::string address;
std::string netmask;
std::string gateway;
std::string name_server_type;
std::string name_servers;
if (args->GetSize() < 7 ||
!args->GetString(0, &service_path) ||
!args->GetBoolean(1, &dhcp_for_ip) ||
!args->GetString(2, &address) ||
!args->GetString(3, &netmask) ||
!args->GetString(4, &gateway) ||
!args->GetString(5, &name_server_type) ||
!args->GetString(6, &name_servers)) {
NOTREACHED();
return;
}
int dhcp_usage_mask = 0;
if (dhcp_for_ip) {
dhcp_usage_mask = (chromeos::NetworkLibrary::USE_DHCP_ADDRESS |
chromeos::NetworkLibrary::USE_DHCP_NETMASK |
chromeos::NetworkLibrary::USE_DHCP_GATEWAY);
}
if (name_server_type == kNameServerTypeAutomatic) {
dhcp_usage_mask |= chromeos::NetworkLibrary::USE_DHCP_NAME_SERVERS;
name_servers.clear();
} else if (name_server_type == kNameServerTypeGoogle) {
name_servers = kGoogleNameServers;
}
cros_->SetIPParameters(service_path,
address,
netmask,
gateway,
name_servers,
dhcp_usage_mask);
}
void InternetOptionsHandler::PopulateDictionaryDetails(
const chromeos::Network* network) {
DCHECK(network);
// Send off an asynchronous request to Shill to get the service properties
// and continue in the callback.
chromeos::CrosRequestNetworkServiceProperties(
network->service_path(),
base::Bind(&InternetOptionsHandler::PopulateDictionaryDetailsCallback,
weak_factory_.GetWeakPtr(), network));
}
void InternetOptionsHandler::PopulateDictionaryDetailsCallback(
const chromeos::Network* network,
const std::string& service_path,
const base::DictionaryValue* shill_properties) {
if (VLOG_IS_ON(2)) {
std::string properties_json;
base::JSONWriter::WriteWithOptions(shill_properties,
base::JSONWriter::OPTIONS_PRETTY_PRINT,
&properties_json);
VLOG(2) << "Shill Properties: " << std::endl << properties_json;
}
Profile::FromWebUI(web_ui())->GetProxyConfigTracker()->UISetCurrentNetwork(
network->service_path());
const chromeos::NetworkUIData& ui_data = network->ui_data();
const chromeos::NetworkPropertyUIData property_ui_data(ui_data);
const base::DictionaryValue* onc =
cros_->FindOncForNetwork(network->unique_id());
base::DictionaryValue dictionary;
std::string hardware_address;
chromeos::NetworkIPConfigVector ipconfigs = cros_->GetIPConfigs(
network->device_path(), &hardware_address,
chromeos::NetworkLibrary::FORMAT_COLON_SEPARATED_HEX);
if (!hardware_address.empty())
dictionary.SetString(kTagHardwareAddress, hardware_address);
// The DHCP IPConfig contains the values that are actually in use at the
// moment, even if some are overridden by static IP values.
scoped_ptr<DictionaryValue> ipconfig_dhcp(new DictionaryValue);
std::string ipconfig_name_servers;
for (chromeos::NetworkIPConfigVector::const_iterator it = ipconfigs.begin();
it != ipconfigs.end(); ++it) {
const chromeos::NetworkIPConfig& ipconfig = *it;
if (ipconfig.type == chromeos::IPCONFIG_TYPE_DHCP) {
ipconfig_dhcp->SetString(kIpConfigAddress, ipconfig.address);
VLOG(2) << "Found DHCP Address: " << ipconfig.address;
ipconfig_dhcp->SetString(kIpConfigNetmask, ipconfig.netmask);
VLOG(2) << "Found DHCP Netmask: " << ipconfig.netmask;
ipconfig_dhcp->SetString(kIpConfigGateway, ipconfig.gateway);
VLOG(2) << "Found DHCP Gateway: " << ipconfig.gateway;
ipconfig_dhcp->SetString(kIpConfigNameServers, ipconfig.name_servers);
ipconfig_name_servers = ipconfig.name_servers; // save for later
VLOG(2) << "Found DHCP Name Servers: " << ipconfig.name_servers;
break;
}
}
int automatic_ip_config;
scoped_ptr<DictionaryValue> static_ip_dict(
BuildIPInfoDictionary(*shill_properties, true, &automatic_ip_config));
dictionary.SetBoolean(kIpConfigAutoConfig, automatic_ip_config == 0);
DCHECK(automatic_ip_config == 3 || automatic_ip_config == 0)
<< "UI doesn't support automatic specification of individual "
<< "static ip parameters.";
scoped_ptr<DictionaryValue> saved_ip_dict(
BuildIPInfoDictionary(*shill_properties, false, NULL));
dictionary.Set(kDictionarySavedIp, saved_ip_dict.release());
// Determine what kind of name server setting we have by comparing the
// StaticIP and Google values with the ipconfig values.
std::string name_server_type = kNameServerTypeAutomatic;
std::string static_ip_nameservers;
static_ip_dict->GetString(kIpConfigNameServers, &static_ip_nameservers);
if (!static_ip_nameservers.empty() &&
static_ip_nameservers == ipconfig_name_servers) {
name_server_type = kNameServerTypeUser;
}
if (ipconfig_name_servers == kGoogleNameServers) {
name_server_type = kNameServerTypeGoogle;
}
SetValueDictionary(&dictionary, kDictionaryIpConfig, ipconfig_dhcp.release(),
property_ui_data);
SetValueDictionary(&dictionary, kDictionaryStaticIp, static_ip_dict.release(),
property_ui_data);
chromeos::ConnectionType type = network->type();
dictionary.SetInteger(kTagType, type);
dictionary.SetString(kTagServicePath, network->service_path());
dictionary.SetBoolean(kTagConnecting, network->connecting());
dictionary.SetBoolean(kTagConnected, network->connected());
dictionary.SetString(kTagConnectionState, network->GetStateString());
dictionary.SetString(kTagNetworkName, network->name());
dictionary.SetString(kTagNameServerType, name_server_type);
dictionary.SetString(kTagNameServersGoogle, kGoogleNameServers);
// Only show proxy for remembered networks.
chromeos::NetworkProfileType network_profile = network->profile_type();
dictionary.SetBoolean(kTagShowProxy,
network_profile != chromeos::PROFILE_NONE);
// Enable static ip config for ethernet. For wifi, enable if flag is set.
bool staticIPConfig = type == chromeos::TYPE_ETHERNET ||
(type == chromeos::TYPE_WIFI &&
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableStaticIPConfig));
dictionary.SetBoolean(kTagShowStaticIPConfig, staticIPConfig);
dictionary.SetBoolean(kTagShowPreferred,
network_profile == chromeos::PROFILE_USER);
SetValueDictionary(&dictionary, kTagPreferred,
Value::CreateBooleanValue(network->preferred()),
property_ui_data);
chromeos::NetworkPropertyUIData auto_connect_ui_data(ui_data);
if (type == chromeos::TYPE_WIFI) {
auto_connect_ui_data.ParseOncProperty(
ui_data, onc,
base::StringPrintf("%s.%s",
chromeos::onc::kWiFi,
chromeos::onc::wifi::kAutoConnect));
}
SetValueDictionary(&dictionary, kTagAutoConnect,
Value::CreateBooleanValue(network->auto_connect()),
auto_connect_ui_data);
if (type == chromeos::TYPE_WIFI) {
dictionary.SetBoolean(kTagDeviceConnected, cros_->wifi_connected());
PopulateWifiDetails(static_cast<const chromeos::WifiNetwork*>(network),
&dictionary);
} else if (type == chromeos::TYPE_WIMAX) {
dictionary.SetBoolean(kTagDeviceConnected, cros_->wimax_connected());
PopulateWimaxDetails(static_cast<const chromeos::WimaxNetwork*>(network),
&dictionary);
} else if (type == chromeos::TYPE_CELLULAR) {
dictionary.SetBoolean(kTagDeviceConnected, cros_->cellular_connected());
PopulateCellularDetails(
static_cast<const chromeos::CellularNetwork*>(network),
&dictionary);
} else if (type == chromeos::TYPE_VPN) {
dictionary.SetBoolean(kTagDeviceConnected,
cros_->virtual_network_connected());
PopulateVPNDetails(static_cast<const chromeos::VirtualNetwork*>(network),
*onc,
&dictionary);
} else if (type == chromeos::TYPE_ETHERNET) {
dictionary.SetBoolean(kTagDeviceConnected, cros_->ethernet_connected());
}
web_ui()->CallJavascriptFunction(
kShowDetailedInfoFunction, dictionary);
}
void InternetOptionsHandler::PopulateWifiDetails(
const chromeos::WifiNetwork* wifi,
DictionaryValue* dictionary) {
dictionary->SetString(kTagSsid, wifi->name());
bool remembered = (wifi->profile_type() != chromeos::PROFILE_NONE);
dictionary->SetBoolean(kTagRemembered, remembered);
bool shared = wifi->profile_type() == chromeos::PROFILE_SHARED;
dictionary->SetBoolean(kTagShared, shared);
dictionary->SetString(kTagEncryption, wifi->GetEncryptionString());
dictionary->SetString(kTagBssid, wifi->bssid());
dictionary->SetInteger(kTagFrequency, wifi->frequency());
dictionary->SetInteger(kTagStrength, wifi->strength());
}
void InternetOptionsHandler::PopulateWimaxDetails(
const chromeos::WimaxNetwork* wimax,
DictionaryValue* dictionary) {
bool remembered = (wimax->profile_type() != chromeos::PROFILE_NONE);
dictionary->SetBoolean(kTagRemembered, remembered);
bool shared = wimax->profile_type() == chromeos::PROFILE_SHARED;
dictionary->SetBoolean(kTagShared, shared);
if (wimax->passphrase_required())
dictionary->SetString(kTagIdentity, wimax->eap_identity());
dictionary->SetInteger(kTagStrength, wimax->strength());
}
DictionaryValue* InternetOptionsHandler::CreateDictionaryFromCellularApn(
const chromeos::CellularApn& apn) {
DictionaryValue* dictionary = new DictionaryValue();
dictionary->SetString(kTagApn, apn.apn);
dictionary->SetString(kTagNetworkId, apn.network_id);
dictionary->SetString(kTagUsername, apn.username);
dictionary->SetString(kTagPassword, apn.password);
dictionary->SetString(kTagName, apn.name);
dictionary->SetString(kTagLocalizedName, apn.localized_name);
dictionary->SetString(kTagLanguage, apn.language);
return dictionary;
}
void InternetOptionsHandler::PopulateCellularDetails(
const chromeos::CellularNetwork* cellular,
DictionaryValue* dictionary) {
dictionary->SetBoolean(kTagCarrierSelectFlag,
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableCarrierSwitching));
// Cellular network / connection settings.
dictionary->SetString(kTagServiceName, cellular->name());
dictionary->SetString(kTagNetworkTechnology,
cellular->GetNetworkTechnologyString());
dictionary->SetString(kTagOperatorName, cellular->operator_name());
dictionary->SetString(kTagOperatorCode, cellular->operator_code());
dictionary->SetString(kTagActivationState,
cellular->GetActivationStateString());
dictionary->SetString(kTagRoamingState,
cellular->GetRoamingStateString());
dictionary->SetString(kTagRestrictedPool,
cellular->restricted_pool() ?
l10n_util::GetStringUTF8(
IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL) :
l10n_util::GetStringUTF8(
IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL));
dictionary->SetString(kTagErrorState, cellular->GetErrorString());
dictionary->SetString(kTagSupportUrl, cellular->payment_url());
dictionary->SetBoolean(kTagNeedsPlan, cellular->needs_new_plan());
dictionary->Set(kTagApn, CreateDictionaryFromCellularApn(cellular->apn()));
dictionary->Set(kTagLastGoodApn,
CreateDictionaryFromCellularApn(cellular->last_good_apn()));
// Device settings.
const chromeos::NetworkDevice* device =
cros_->FindNetworkDeviceByPath(cellular->device_path());
if (device) {
const chromeos::NetworkPropertyUIData cellular_property_ui_data(
cellular->ui_data());
dictionary->SetString(kTagManufacturer, device->manufacturer());
dictionary->SetString(kTagModelId, device->model_id());
dictionary->SetString(kTagFirmwareRevision, device->firmware_revision());
dictionary->SetString(kTagHardwareRevision, device->hardware_revision());
dictionary->SetString(kTagPrlVersion,
base::StringPrintf("%u", device->prl_version()));
dictionary->SetString(kTagMeid, device->meid());
dictionary->SetString(kTagImei, device->imei());
dictionary->SetString(kTagMdn, device->mdn());
dictionary->SetString(kTagImsi, device->imsi());
dictionary->SetString(kTagEsn, device->esn());
dictionary->SetString(kTagMin, device->min());
dictionary->SetBoolean(kTagGsm,
device->technology_family() == chromeos::TECHNOLOGY_FAMILY_GSM);
SetValueDictionary(
dictionary, kTagSimCardLockEnabled,
Value::CreateBooleanValue(
device->sim_pin_required() == chromeos::SIM_PIN_REQUIRED),
cellular_property_ui_data);
chromeos::MobileConfig* config = chromeos::MobileConfig::GetInstance();
if (config->IsReady()) {
const std::string& carrier_id = cros_->GetCellularHomeCarrierId();
const chromeos::MobileConfig::Carrier* carrier =
config->GetCarrier(carrier_id);
if (carrier && !carrier->top_up_url().empty())
dictionary->SetString(kTagCarrierUrl, carrier->top_up_url());
}
const chromeos::CellularApnList& apn_list = device->provider_apn_list();
ListValue* apn_list_value = new ListValue();
for (chromeos::CellularApnList::const_iterator it = apn_list.begin();
it != apn_list.end(); ++it) {
apn_list_value->Append(CreateDictionaryFromCellularApn(*it));
}
SetValueDictionary(dictionary, kTagProviderApnList, apn_list_value,
cellular_property_ui_data);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableCarrierSwitching)) {
base::ListValue* supported_carriers = device->supported_carriers();
if (supported_carriers) {
dictionary->Set(kTagCarriers, supported_carriers->DeepCopy());
dictionary->SetInteger(kTagCurrentCarrierIndex,
FindCurrentCarrierIndex(supported_carriers,
device));
} else {
// In case of any error, set the current carrier tag to -1 indicating
// to the JS code to fallback to a single carrier.
dictionary->SetInteger(kTagCurrentCarrierIndex, -1);
}
}
}
SetActivationButtonVisibility(cellular,
dictionary,
cros_->GetCellularHomeCarrierId());
}
void InternetOptionsHandler::SetActivationButtonVisibility(
const chromeos::CellularNetwork* cellular,
DictionaryValue* dictionary,
const std::string& carrier_id) {
if (cellular->needs_new_plan()) {
dictionary->SetBoolean(kTagShowBuyButton, true);
} else if (cellular->activation_state() !=
chromeos::ACTIVATION_STATE_ACTIVATING &&
cellular->activation_state() !=
chromeos::ACTIVATION_STATE_ACTIVATED) {
dictionary->SetBoolean(kTagShowActivateButton, true);
} else {
const chromeos::MobileConfig::Carrier* carrier =
chromeos::MobileConfig::GetInstance()->GetCarrier(carrier_id);
if (carrier && carrier->show_portal_button()) {
// This will trigger BuyDataPlanCallback() so that
// chrome://mobilesetup/ will open carrier specific portal.
dictionary->SetBoolean(kTagShowViewAccountButton, true);
}
}
}
gfx::NativeWindow InternetOptionsHandler::GetNativeWindow() const {
// TODO(beng): This is an improper direct dependency on Browser. Route this
// through some sort of delegate.
Browser* browser =
browser::FindBrowserWithWebContents(web_ui()->GetWebContents());
return browser->window()->GetNativeWindow();
}
Browser* InternetOptionsHandler::GetAppropriateBrowser() {
return browser::FindOrCreateTabbedBrowser(
ProfileManager::GetDefaultProfileOrOffTheRecord(),
chrome::HOST_DESKTOP_TYPE_ASH);
}
void InternetOptionsHandler::NetworkCommandCallback(const ListValue* args) {
std::string str_type;
std::string service_path;
std::string command;
if (args->GetSize() != 3 ||
!args->GetString(0, &str_type) ||
!args->GetString(1, &service_path) ||
!args->GetString(2, &command)) {
NOTREACHED();
return;
}
chromeos::ConnectionType type =
(chromeos::ConnectionType) atoi(str_type.c_str());
// Process commands that do not require an existing network.
if (command == kTagAddConnection) {
if (CanAddNetworkType(type))
AddConnection(type);
return;
} else if (command == kTagForget) {
if (CanForgetNetworkType(type))
cros_->ForgetNetwork(service_path);
return;
}
// Process commands that require an active network.
chromeos::Network *network = NULL;
if (!service_path.empty())
network = cros_->FindNetworkByPath(service_path);
if (!network) {
VLOG(2) << "Network command: " << command
<< "Called with unknown service-path: " << service_path;
return;
}
DCHECK_EQ(network->type(), type)
<< "Provided type: " << type << " does not match: " << network->type()
<< " For network: " << service_path;
if (command == kTagOptions) {
PopulateDictionaryDetails(network);
} else if (command == kTagConnect) {
ConnectToNetwork(network);
} else if (command == kTagDisconnect && type != chromeos::TYPE_ETHERNET) {
cros_->DisconnectFromNetwork(network);
} else if (command == kTagActivate && type == chromeos::TYPE_CELLULAR) {
ash::Shell::GetInstance()->delegate()->OpenMobileSetup(
network->service_path());
} else {
VLOG(1) << "Unknown command: " << command;
NOTREACHED();
}
}
void InternetOptionsHandler::ToggleAirplaneModeCallback(const ListValue* args) {
// TODO(kevers): The use of 'offline_mode' is not quite correct. Update once
// we have proper back-end support.
cros_->EnableOfflineMode(!cros_->offline_mode());
}
void InternetOptionsHandler::AddConnection(chromeos::ConnectionType type) {
switch (type) {
case chromeos::TYPE_WIFI:
case chromeos::TYPE_VPN:
chromeos::NetworkConfigView::ShowForType(type,
GetNativeWindow());
break;
case chromeos::TYPE_CELLULAR:
chromeos::ChooseMobileNetworkDialog::ShowDialog(GetNativeWindow());
break;
default:
NOTREACHED();
}
}
void InternetOptionsHandler::ConnectToNetwork(chromeos::Network* network) {
if (network->type() == chromeos::TYPE_CELLULAR) {
cros_->ConnectToCellularNetwork(
static_cast<chromeos::CellularNetwork*>(network));
} else {
network->SetEnrollmentDelegate(
chromeos::CreateEnrollmentDelegate(
GetNativeWindow(),
network->name(),
ProfileManager::GetLastUsedProfile()));
network->AttemptConnection(base::Bind(&InternetOptionsHandler::DoConnect,
weak_factory_.GetWeakPtr(),
network));
}
}
void InternetOptionsHandler::DoConnect(chromeos::Network* network) {
if (network->type() == chromeos::TYPE_VPN) {
chromeos::VirtualNetwork* vpn =
static_cast<chromeos::VirtualNetwork*>(network);
if (vpn->NeedMoreInfoToConnect()) {
chromeos::NetworkConfigView::Show(network, GetNativeWindow());
} else {
cros_->ConnectToVirtualNetwork(vpn);
// Connection failures are responsible for updating the UI, including
// reopening dialogs.
}
} else if (network->type() == chromeos::TYPE_WIFI) {
chromeos::WifiNetwork* wifi = static_cast<chromeos::WifiNetwork*>(network);
if (wifi->IsPassphraseRequired()) {
// Show the connection UI if we require a passphrase.
chromeos::NetworkConfigView::Show(wifi, GetNativeWindow());
} else {
cros_->ConnectToWifiNetwork(wifi);
// Connection failures are responsible for updating the UI, including
// reopening dialogs.
}
} else if (network->type() == chromeos::TYPE_WIMAX) {
chromeos::WimaxNetwork* wimax =
static_cast<chromeos::WimaxNetwork*>(network);
if (wimax->passphrase_required()) {
// Show the connection UI if we require a passphrase.
// TODO(stevenjb): Implement WiMAX connection UI.
chromeos::NetworkConfigView::Show(wimax, GetNativeWindow());
} else {
cros_->ConnectToWimaxNetwork(wimax);
// Connection failures are responsible for updating the UI, including
// reopening dialogs.
}
}
}
void InternetOptionsHandler::RefreshCellularPlanCallback(
const ListValue* args) {
std::string service_path;
if (args->GetSize() != 1 ||
!args->GetString(0, &service_path)) {
NOTREACHED();
return;
}
const chromeos::CellularNetwork* cellular =
cros_->FindCellularNetworkByPath(service_path);
if (cellular)
cellular->RefreshDataPlansIfNeeded();
}
ListValue* InternetOptionsHandler::GetWiredList() {
ListValue* list = new ListValue();
// If ethernet is not enabled, then don't add anything.
if (cros_->ethernet_enabled()) {
const chromeos::EthernetNetwork* ethernet_network =
cros_->ethernet_network();
if (ethernet_network) {
NetworkInfoDictionary network_dict(ethernet_network,
web_ui()->GetDeviceScaleFactor());
network_dict.set_name(
l10n_util::GetStringUTF8(IDS_STATUSBAR_NETWORK_DEVICE_ETHERNET)),
list->Append(network_dict.BuildDictionary());
}
}
return list;
}
ListValue* InternetOptionsHandler::GetWirelessList() {
ListValue* list = new ListValue();
const chromeos::WifiNetworkVector& wifi_networks = cros_->wifi_networks();
for (chromeos::WifiNetworkVector::const_iterator it =
wifi_networks.begin(); it != wifi_networks.end(); ++it) {
NetworkInfoDictionary network_dict(*it, web_ui()->GetDeviceScaleFactor());
network_dict.set_connectable(cros_->CanConnectToNetwork(*it));
list->Append(network_dict.BuildDictionary());
}
const chromeos::WimaxNetworkVector& wimax_networks = cros_->wimax_networks();
for (chromeos::WimaxNetworkVector::const_iterator it =
wimax_networks.begin(); it != wimax_networks.end(); ++it) {
NetworkInfoDictionary network_dict(*it, web_ui()->GetDeviceScaleFactor());
network_dict.set_connectable(cros_->CanConnectToNetwork(*it));
list->Append(network_dict.BuildDictionary());
}
const chromeos::CellularNetworkVector cellular_networks =
cros_->cellular_networks();
for (chromeos::CellularNetworkVector::const_iterator it =
cellular_networks.begin(); it != cellular_networks.end(); ++it) {
NetworkInfoDictionary network_dict(*it, web_ui()->GetDeviceScaleFactor());
network_dict.set_connectable(cros_->CanConnectToNetwork(*it));
network_dict.set_activation_state((*it)->activation_state());
network_dict.set_needs_new_plan(
(*it)->SupportsDataPlan() && (*it)->restricted_pool());
list->Append(network_dict.BuildDictionary());
}
return list;
}
ListValue* InternetOptionsHandler::GetVPNList() {
ListValue* list = new ListValue();
const chromeos::VirtualNetworkVector& virtual_networks =
cros_->virtual_networks();
for (chromeos::VirtualNetworkVector::const_iterator it =
virtual_networks.begin(); it != virtual_networks.end(); ++it) {
NetworkInfoDictionary network_dict(*it, web_ui()->GetDeviceScaleFactor());
network_dict.set_connectable(cros_->CanConnectToNetwork(*it));
list->Append(network_dict.BuildDictionary());
}
return list;
}
ListValue* InternetOptionsHandler::GetRememberedList() {
ListValue* list = new ListValue();
for (chromeos::WifiNetworkVector::const_iterator rit =
cros_->remembered_wifi_networks().begin();
rit != cros_->remembered_wifi_networks().end(); ++rit) {
chromeos::WifiNetwork* remembered = *rit;
chromeos::WifiNetwork* wifi = static_cast<chromeos::WifiNetwork*>(
cros_->FindNetworkByUniqueId(remembered->unique_id()));
NetworkInfoDictionary network_dict(wifi,
remembered,
web_ui()->GetDeviceScaleFactor());
list->Append(network_dict.BuildDictionary());
}
for (chromeos::VirtualNetworkVector::const_iterator rit =
cros_->remembered_virtual_networks().begin();
rit != cros_->remembered_virtual_networks().end(); ++rit) {
chromeos::VirtualNetwork* remembered = *rit;
chromeos::VirtualNetwork* vpn = static_cast<chromeos::VirtualNetwork*>(
cros_->FindNetworkByUniqueId(remembered->unique_id()));
NetworkInfoDictionary network_dict(vpn,
remembered,
web_ui()->GetDeviceScaleFactor());
list->Append(network_dict.BuildDictionary());
}
return list;
}
void InternetOptionsHandler::FillNetworkInfo(DictionaryValue* dictionary) {
dictionary->SetBoolean(kTagAccessLocked, cros_->IsLocked());
dictionary->Set(kTagWiredList, GetWiredList());
dictionary->Set(kTagWirelessList, GetWirelessList());
dictionary->Set(kTagVpnList, GetVPNList());
dictionary->Set(kTagRememberedList, GetRememberedList());
dictionary->SetBoolean(kTagWifiAvailable, cros_->wifi_available());
dictionary->SetBoolean(kTagWifiBusy, cros_->wifi_busy());
dictionary->SetBoolean(kTagWifiEnabled, cros_->wifi_enabled());
dictionary->SetBoolean(kTagCellularAvailable, cros_->cellular_available());
dictionary->SetBoolean(kTagCellularBusy, cros_->cellular_busy());
dictionary->SetBoolean(kTagCellularEnabled, cros_->cellular_enabled());
const chromeos::NetworkDevice* cellular_device = cros_->FindCellularDevice();
dictionary->SetBoolean(
kTagCellularSupportsScan,
cellular_device && cellular_device->support_network_scan());
dictionary->SetBoolean(kTagWimaxEnabled, cros_->wimax_enabled());
dictionary->SetBoolean(kTagWimaxAvailable, cros_->wimax_available());
dictionary->SetBoolean(kTagWimaxBusy, cros_->wimax_busy());
// TODO(kevers): The use of 'offline_mode' is not quite correct. Update once
// we have proper back-end support.
dictionary->SetBoolean(kTagAirplaneMode, cros_->offline_mode());
}
} // namespace options
| 41.174586 | 80 | 0.727276 | [
"object",
"vector"
] |
11f17566bbeb86341c5e4d1476947169758d4ea4 | 4,133 | cpp | C++ | tests/test1/unitCatch.cpp | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | 1 | 2018-11-18T11:30:39.000Z | 2018-11-18T11:30:39.000Z | tests/test1/unitCatch.cpp | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | null | null | null | tests/test1/unitCatch.cpp | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | null | null | null | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "AMQPSerialize/serializeamqp.h"
#include "structures/structsdsl.h"
using namespace Queue1;
static_assert(!serializeAMQP::detail::isAMQPStruct<int>);
static_assert(serializeAMQP::detail::isAMQPStruct<AMQPTestStruct>);
static_assert(serializeAMQP::detail::is_variant_v<VariantStruct>);
static_assert(!serializeAMQP::detail::is_variant_v<std::variant<int,char>>);
namespace{
struct TestVct{
int32_t i;
float f;
std::vector<double> vct;
int8_t s;
};
inline bool operator==(const TestVct&a,const TestVct &b)
{
return (a.i==b.i) && (a.s==b.s) && (a.vct==b.vct);
}
struct ABC { uint32_t i;
uint8_t s;
std::array<int,3> arr;
std::string str;
TypesAMQP typesAMQP=TypesAMQP::One;
};
bool operator==(const ABC&a,const ABC &b)
{
return a.i == b.i && a.s == b.s;
}
TEST_CASE( "AMQPSerialize ", "[AMQPSerialize]" )
{
SECTION( "Misc1" )
{
qpid::types::Variant valc('f');
auto c=serializeAMQP::get<char>(valc);
REQUIRE(c=='f');
std::list<int> a={1,2,3,4,5,6,7,8,9};
auto it=a.begin();
std::advance(it,2);
REQUIRE(*it==3);
qpid::types::Variant val(12.5f);
auto dbl=serializeAMQP::get<double>(val);
REQUIRE(dbl==12.5);
qpid::types::Variant val1(12u);
auto ul=serializeAMQP::get<uint64_t>(val1);
REQUIRE(ul==12);
auto ts=TestStruct{2,3.14,'c',{4.3,45,"hello","world"},{7,8}};
AMQPTestStruct v{ts};
auto listVariants=serializeAMQP::toQpid(v);
qpid::messaging::Message request;
request.setContentObject(listVariants);
auto var= Queue1::fromAMQP(listVariants);
REQUIRE(static_cast<size_t>(TypesAMQP::One)==var.index());
auto ts2=std::get<TestStruct>(var);
REQUIRE(ts==ts2);
}
SECTION("PointTest")
{
auto p1 =Point {1.1,2.1,3.1};
auto listVariants1=serializeAMQP::toProton(AMQPPoint{p1});
auto listVariants2=serializeAMQP::toQpid(AMQPPoint{p1});
auto var1= Queue1::fromAMQP(listVariants1);
REQUIRE(static_cast<size_t>(TypesAMQP::Three)==var1.index());
auto var2= Queue1::fromAMQP(listVariants2);
REQUIRE(static_cast<size_t>(TypesAMQP::Three)==var2.index());
auto p2=std::get<Queue1::Point>(var1);
REQUIRE(p1==p2);
auto p3=std::get<Queue1::Point>(var2);
REQUIRE(p1==p3);
}
SECTION("ProfileTest")
{
auto p1 =Point {1.1,1.2,1.3};
auto p2 =Point {2.1,2.2,2.3};
auto p3 =Point {3.1,3.2,3.3};
auto profile=Profile{{p1,p2,p3}};
auto listVariants3=serializeAMQP::toProton(AMQPProfile{profile});
auto var3= Queue1::fromAMQP(listVariants3);
REQUIRE(static_cast<size_t>(TypesAMQP::Five)==var3.index());
auto profile2=std::get<Profile>(var3);
REQUIRE(profile==profile2);
}
SECTION( "VctPoints")
{
auto p1 =Point {1.1,1.2,1.3};
auto p2 =Point {2.1,2.2,2.3};
auto p3 =Point {3.1,3.2,3.3};
VctPoint vctPoint{p1,p2,p3};
auto listVariants4=serializeAMQP::toQpid(AMQPVctPoint{vctPoint});
auto var4= Queue1::fromAMQP(listVariants4);
REQUIRE(static_cast<size_t>(TypesAMQP::Four)==var4.index());
auto vctPoint2=std::get<Queue1::VctPoint>(var4);
REQUIRE(vctPoint2==vctPoint);
}
SECTION("TestStruct")
{
auto ts=TestStruct{2,3.14,'c',{4.3,45,"hello","world"}};
AMQPTestStruct v{ts};
auto vctProtVal=serializeAMQP::toProton(v);
auto var= Queue1::fromAMQP(vctProtVal);
REQUIRE(static_cast<size_t>(TypesAMQP::One)==var.index());
auto ts2=std::get<Queue1::TestStruct>(var);
REQUIRE(ts==ts2);
}
SECTION("TestTemperature")
{
auto ts=Temperature{283.14,"Kelvin",StatusSensor::Busy};
AMQPTemperature v{ts};
auto vctProtVal=serializeAMQP::toProton(v);
auto var= Queue1::fromAMQP(vctProtVal);
REQUIRE(static_cast<size_t>(TypesAMQP::Six)==var.index());
auto ts2=std::get<Queue1::Temperature>(var);
REQUIRE(ts==ts2);
}
}
}
| 22.461957 | 97 | 0.631986 | [
"vector"
] |
11f6b5fddc8adb1da52c129b98fca71fd7faf086 | 21,448 | cpp | C++ | dart/dynamics/Frame.cpp | purewind7/CS7496 | ca0b8376db400f265d9515d8307d928590a1569a | [
"BSD-2-Clause"
] | null | null | null | dart/dynamics/Frame.cpp | purewind7/CS7496 | ca0b8376db400f265d9515d8307d928590a1569a | [
"BSD-2-Clause"
] | null | null | null | dart/dynamics/Frame.cpp | purewind7/CS7496 | ca0b8376db400f265d9515d8307d928590a1569a | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2014-2016, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2014-2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/dynamics/Frame.hpp"
#include "dart/common/Console.hpp"
#include "dart/dynamics/Shape.hpp"
namespace dart {
namespace dynamics {
typedef std::set<Entity*> EntityPtrSet;
typedef std::set<Frame*> FramePtrSet;
//==============================================================================
Frame::~Frame()
{
if(isWorld())
return;
changeParentFrame(nullptr);
// Inform all child entities that this Frame is disappearing by setting their
// reference frames to the World frame.
EntityPtrSet::iterator it=mChildEntities.begin(), end=mChildEntities.end();
while( it != end )
(*(it++))->changeParentFrame(Frame::World());
// Note: When we instruct an Entity to change its parent Frame, it will erase
// itself from this Frame's mChildEntities list. This would invalidate the
// 'it' and clobber our attempt to iterate through the std::set if we applied
// changeParentFrame() directly to the 'it' iterator. So instead we use the
// post-increment operator to iterate 'it' forward and we apply
// changeParentFrame() to the temporary iterator created by the
// post-increment operator. Put simply: we increment 'it' forward once and
// then apply changeParentFrame() to the pointer that 'it' held just before
// it incremented.
// The entity destructor takes care of informing the parent Frame that this
// one is disappearing
}
//==============================================================================
Frame* Frame::World()
{
static WorldFrame world;
return &world;
}
//==============================================================================
const Eigen::Isometry3d& Frame::getWorldTransform() const
{
if(mAmWorld)
return mWorldTransform;
if(mNeedTransformUpdate)
{
mWorldTransform = mParentFrame->getWorldTransform()*getRelativeTransform();
mNeedTransformUpdate = false;
}
return mWorldTransform;
}
//==============================================================================
Eigen::Isometry3d Frame::getTransform(const Frame* _withRespectTo) const
{
if(_withRespectTo->isWorld())
return getWorldTransform();
else if(_withRespectTo == mParentFrame)
return getRelativeTransform();
else if(_withRespectTo == this)
return Eigen::Isometry3d::Identity();
return _withRespectTo->getWorldTransform().inverse()*getWorldTransform();
}
//==============================================================================
Eigen::Isometry3d Frame::getTransform(const Frame* withRespectTo,
const Frame* inCoordinatesOf) const
{
assert(nullptr != withRespectTo);
assert(nullptr != inCoordinatesOf);
if (withRespectTo == inCoordinatesOf)
return getTransform(withRespectTo);
// Rotation from "inCoordinatesOf" to "withRespecTo"
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.linear() = inCoordinatesOf->getWorldTransform().linear().transpose()
* withRespectTo->getWorldTransform().linear();
return T * getTransform(withRespectTo);
}
//==============================================================================
const Eigen::Vector6d& Frame::getSpatialVelocity() const
{
if(mAmWorld)
return mVelocity;
if(mNeedVelocityUpdate)
{
mVelocity = math::AdInvT(getRelativeTransform(),
getParentFrame()->getSpatialVelocity())
+ getRelativeSpatialVelocity();
mNeedVelocityUpdate = false;
}
return mVelocity;
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialVelocity(const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
if(this == _relativeTo)
return Eigen::Vector6d::Zero();
if(_relativeTo->isWorld())
{
if(this == _inCoordinatesOf)
return getSpatialVelocity();
if(_inCoordinatesOf->isWorld())
return math::AdR(getWorldTransform(), getSpatialVelocity());
return math::AdR(getTransform(_inCoordinatesOf), getSpatialVelocity());
}
const Eigen::Vector6d& result =
(getSpatialVelocity() - math::AdT(_relativeTo->getTransform(this),
_relativeTo->getSpatialVelocity())).eval();
if(this == _inCoordinatesOf)
return result;
return math::AdR(getTransform(_inCoordinatesOf), result);
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialVelocity(const Eigen::Vector3d& _offset) const
{
return getSpatialVelocity(_offset, Frame::World(), this);
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialVelocity(const Eigen::Vector3d& _offset,
const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
if(this == _relativeTo)
return Eigen::Vector6d::Zero();
Eigen::Vector6d v = getSpatialVelocity();
v.tail<3>().noalias() += v.head<3>().cross(_offset);
if(_relativeTo->isWorld())
{
if(this == _inCoordinatesOf)
return v;
return math::AdR(getTransform(_inCoordinatesOf), v);
}
Eigen::Vector6d v_0 = math::AdT(_relativeTo->getTransform(this),
_relativeTo->getSpatialVelocity());
v_0.tail<3>().noalias() += v_0.head<3>().cross(_offset);
v = v - v_0;
if(this == _inCoordinatesOf)
return v;
return math::AdR(getTransform(_inCoordinatesOf), v);
}
//==============================================================================
Eigen::Vector3d Frame::getLinearVelocity(const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
return getSpatialVelocity(_relativeTo, _inCoordinatesOf).tail<3>();
}
//==============================================================================
Eigen::Vector3d Frame::getLinearVelocity(const Eigen::Vector3d& _offset,
const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
return getSpatialVelocity(_offset, _relativeTo, _inCoordinatesOf).tail<3>();
}
//==============================================================================
Eigen::Vector3d Frame::getAngularVelocity(const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
return getSpatialVelocity(_relativeTo,_inCoordinatesOf).head<3>();
}
//==============================================================================
const Eigen::Vector6d& Frame::getSpatialAcceleration() const
{
if(mAmWorld)
return mAcceleration;
if(mNeedAccelerationUpdate)
{
mAcceleration = math::AdInvT(getRelativeTransform(),
getParentFrame()->getSpatialAcceleration())
+ getPrimaryRelativeAcceleration()
+ getPartialAcceleration();
mNeedAccelerationUpdate = false;
}
return mAcceleration;
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialAcceleration(
const Frame* _relativeTo, const Frame* _inCoordinatesOf) const
{
// Frame 2: this, Frame 1: _relativeTo, Frame O: _inCoordinatesOf
// Acceleration of Frame 2 relative to Frame 1 in coordinates of O: a_21[O]
// Total acceleration of Frame 2 in coordinates of Frame 2: a_2[2]
// Velocity of Frame 2 relative to Frame 1 in coordinates of Frame 2: v_21[2]
// a_21[O] = R_O2*( a_2[2] - X_21*a_1[1] - v_2[2] x v_21[2] )
if(this == _relativeTo)
return Eigen::Vector6d::Zero();
if(_relativeTo->isWorld())
{
if(this == _inCoordinatesOf)
return getSpatialAcceleration();
if(_inCoordinatesOf->isWorld())
return math::AdR(getWorldTransform(), getSpatialAcceleration());
return math::AdR(getTransform(_inCoordinatesOf), getSpatialAcceleration());
}
const Eigen::Vector6d& result =
(getSpatialAcceleration()
- math::AdT(_relativeTo->getTransform(this),
_relativeTo->getSpatialAcceleration())
+ math::ad(getSpatialVelocity(),
math::AdT(_relativeTo->getTransform(this),
_relativeTo->getSpatialVelocity()))).eval();
if(this == _inCoordinatesOf)
return result;
return math::AdR(getTransform(_inCoordinatesOf), result);
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialAcceleration(const Eigen::Vector3d& _offset) const
{
return getSpatialAcceleration(_offset, Frame::World(), this);
}
//==============================================================================
Eigen::Vector6d Frame::getSpatialAcceleration(const Eigen::Vector3d& _offset,
const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
if(this == _relativeTo)
return Eigen::Vector6d::Zero();
// Compute spatial acceleration of the point
Eigen::Vector6d a = getSpatialAcceleration();
a.tail<3>().noalias() += a.head<3>().cross(_offset);
if(_relativeTo->isWorld())
{
if(this == _inCoordinatesOf)
return a;
return math::AdR(getTransform(_inCoordinatesOf), a);
}
// Compute the spatial velocity of the point
Eigen::Vector6d v = getSpatialVelocity();
v.tail<3>().noalias() += v.head<3>().cross(_offset);
// Compute the acceleration of the reference Frame
Eigen::Vector6d a_ref = math::AdT(_relativeTo->getTransform(this),
_relativeTo->getSpatialAcceleration());
a_ref.tail<3>().noalias() += a_ref.head<3>().cross(_offset);
// Compute the relative velocity of the point
const Eigen::Vector6d& v_rel = getSpatialVelocity(_offset, _relativeTo, this);
a = a - a_ref - math::ad(v, v_rel);
if(this == _inCoordinatesOf)
return a;
return math::AdR(getTransform(_inCoordinatesOf), a);
}
//==============================================================================
Eigen::Vector3d Frame::getLinearAcceleration(
const Frame* _relativeTo, const Frame* _inCoordinatesOf) const
{
if(this == _relativeTo)
return Eigen::Vector3d::Zero();
const Eigen::Vector6d& v_rel = getSpatialVelocity(_relativeTo, this);
// r'' = a + w x v
const Eigen::Vector3d& a =
(getSpatialAcceleration(_relativeTo, this).tail<3>()
+ v_rel.head<3>().cross(v_rel.tail<3>())).eval();
if(this == _inCoordinatesOf)
return a;
return getTransform(_inCoordinatesOf).linear() * a;
}
//==============================================================================
Eigen::Vector3d Frame::getLinearAcceleration(const Eigen::Vector3d& _offset,
const Frame* _relativeTo,
const Frame* _inCoordinatesOf) const
{
if(this == _relativeTo)
return Eigen::Vector3d::Zero();
const Eigen::Vector6d& v_rel = getSpatialVelocity(_offset, _relativeTo, this);
const Eigen::Vector3d& a = (getSpatialAcceleration(_offset, _relativeTo,
this).tail<3>()
+ v_rel.head<3>().cross(v_rel.tail<3>())).eval();
if(this == _inCoordinatesOf)
return a;
return getTransform(_inCoordinatesOf).linear() * a;
}
//==============================================================================
Eigen::Vector3d Frame::getAngularAcceleration(
const Frame* _relativeTo, const Frame* _inCoordinatesOf) const
{
return getSpatialAcceleration(_relativeTo, _inCoordinatesOf).head<3>();
}
//==============================================================================
template <typename T>
static std::set<const T*> convertToConstSet(const std::set<T*>& _set)
{
std::set<const T*> const_set;
for(const auto& element : _set)
const_set.insert(element);
return const_set;
}
//==============================================================================
const std::set<Entity*>& Frame::getChildEntities()
{
return mChildEntities;
}
//==============================================================================
const std::set<const Entity*> Frame::getChildEntities() const
{
return convertToConstSet<Entity>(mChildEntities);
}
//==============================================================================
std::size_t Frame::getNumChildEntities() const
{
return mChildEntities.size();
}
//==============================================================================
const std::set<Frame*>& Frame::getChildFrames()
{
return mChildFrames;
}
//==============================================================================
std::set<const Frame*> Frame::getChildFrames() const
{
return convertToConstSet<Frame>(mChildFrames);
}
//==============================================================================
std::size_t Frame::getNumChildFrames() const
{
return mChildFrames.size();
}
//==============================================================================
bool Frame::isShapeFrame() const
{
return mAmShapeFrame;
}
//==============================================================================
ShapeFrame* Frame::asShapeFrame()
{
return nullptr;
}
//==============================================================================
const ShapeFrame* Frame::asShapeFrame() const
{
return nullptr;
}
//==============================================================================
bool Frame::isWorld() const
{
return mAmWorld;
}
//==============================================================================
void Frame::notifyTransformUpdate()
{
notifyVelocityUpdate(); // Global Velocity depends on the Global Transform
// Always trigger the signal, in case a new subscriber has registered in the
// time since the last signal
mTransformUpdatedSignal.raise(this);
// If we already know we need to update, just quit
if(mNeedTransformUpdate)
return;
mNeedTransformUpdate = true;
for(Entity* entity : mChildEntities)
entity->notifyTransformUpdate();
}
//==============================================================================
void Frame::notifyVelocityUpdate()
{
notifyAccelerationUpdate(); // Global Acceleration depends on Global Velocity
// Always trigger the signal, in case a new subscriber has registered in the
// time since the last signal
mVelocityChangedSignal.raise(this);
// If we already know we need to update, just quit
if(mNeedVelocityUpdate)
return;
mNeedVelocityUpdate = true;
for(Entity* entity : mChildEntities)
entity->notifyVelocityUpdate();
}
//==============================================================================
void Frame::notifyAccelerationUpdate()
{
// Always trigger the signal, in case a new subscriber has registered in the
// time since the last signal
mAccelerationChangedSignal.raise(this);
// If we already know we need to update, just quit
if(mNeedAccelerationUpdate)
return;
mNeedAccelerationUpdate = true;
for(Entity* entity : mChildEntities)
entity->notifyAccelerationUpdate();
}
//==============================================================================
Frame::Frame(Frame* _refFrame)
: Entity(ConstructFrame),
mWorldTransform(Eigen::Isometry3d::Identity()),
mVelocity(Eigen::Vector6d::Zero()),
mAcceleration(Eigen::Vector6d::Zero()),
mAmWorld(false),
mAmShapeFrame(false)
{
mAmFrame = true;
changeParentFrame(_refFrame);
}
//==============================================================================
Frame::Frame()
: Frame(ConstructAbstract)
{
// Delegated to Frame(ConstructAbstract)
}
//==============================================================================
Frame::Frame(ConstructAbstractTag)
: Entity(Entity::ConstructAbstract),
mAmWorld(false),
mAmShapeFrame(false)
{
dterr << "[Frame::constructor] You are calling a constructor for the Frame "
<< "class which is only meant to be used by pure abstract classes. If "
<< "you are seeing this, then there is a bug!\n";
assert(false);
}
//==============================================================================
void Frame::changeParentFrame(Frame* _newParentFrame)
{
if (mParentFrame == _newParentFrame)
return;
if(_newParentFrame)
{
if(_newParentFrame->descendsFrom(this))
{
if(!(this->isWorld() && _newParentFrame->isWorld()))
// We make an exception here for the World Frame, because it's special/unique
{
dtwarn << "[Frame::changeParentFrame] Attempting to create a circular "
<< "kinematic dependency by making Frame '" << getName()
<< "' a child of Frame '" << _newParentFrame->getName() << "'. "
<< "This will not be allowed.\n";
return;
}
}
}
if(mParentFrame && !mParentFrame->isWorld())
{
FramePtrSet::iterator it = mParentFrame->mChildFrames.find(this);
if(it != mParentFrame->mChildFrames.end())
mParentFrame->mChildFrames.erase(it);
}
if(nullptr==_newParentFrame)
{
Entity::changeParentFrame(_newParentFrame);
return;
}
if(!mAmQuiet && !_newParentFrame->isWorld())
_newParentFrame->mChildFrames.insert(this);
Entity::changeParentFrame(_newParentFrame);
}
//==============================================================================
void Frame::processNewEntity(Entity*)
{
// Do nothing
}
//==============================================================================
void Frame::processRemovedEntity(Entity*)
{
// Do nothing
}
//==============================================================================
Frame::Frame(ConstructWorldTag)
: Entity(this, true),
mWorldTransform(Eigen::Isometry3d::Identity()),
mVelocity(Eigen::Vector6d::Zero()),
mAcceleration(Eigen::Vector6d::Zero()),
mAmWorld(true),
mAmShapeFrame(false)
{
mAmFrame = true;
}
//==============================================================================
const Eigen::Vector6d WorldFrame::mZero = Eigen::Vector6d::Zero();
//==============================================================================
const Eigen::Isometry3d& WorldFrame::getRelativeTransform() const
{
return mRelativeTf;
}
//==============================================================================
const Eigen::Vector6d& WorldFrame::getRelativeSpatialVelocity() const
{
return mZero;
}
//==============================================================================
const Eigen::Vector6d& WorldFrame::getRelativeSpatialAcceleration() const
{
return mZero;
}
//==============================================================================
const Eigen::Vector6d& WorldFrame::getPrimaryRelativeAcceleration() const
{
return mZero;
}
//==============================================================================
const Eigen::Vector6d& WorldFrame::getPartialAcceleration() const
{
return mZero;
}
//==============================================================================
const std::string& WorldFrame::setName(const std::string& name)
{
dterr << "[WorldFrame::setName] attempting to change name of World frame to ["
<< name << "], but this is not allowed!\n";
static const std::string worldName = "World";
return worldName;
}
//==============================================================================
const std::string& WorldFrame::getName() const
{
static const std::string worldName = "World";
return worldName;
}
//==============================================================================
WorldFrame::WorldFrame()
: Entity(nullptr, true),
Frame(ConstructWorld),
mRelativeTf(Eigen::Isometry3d::Identity())
{
changeParentFrame(this);
}
} // namespace dart
} // namespace dynamics
| 32.447806 | 83 | 0.556649 | [
"shape",
"transform"
] |
11f8a289c924afaba9690ab5ec1f0d652d5610ce | 71,227 | cc | C++ | src/kudu/tserver/ts_tablet_manager.cc | rajesh-ibm-power/kudu | cb8f0138c345b5209899e95db8d5c63994d2c721 | [
"Apache-2.0"
] | null | null | null | src/kudu/tserver/ts_tablet_manager.cc | rajesh-ibm-power/kudu | cb8f0138c345b5209899e95db8d5c63994d2c721 | [
"Apache-2.0"
] | null | null | null | src/kudu/tserver/ts_tablet_manager.cc | rajesh-ibm-power/kudu | cb8f0138c345b5209899e95db8d5c63994d2c721 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/tserver/ts_tablet_manager.h"
#include <cstdint>
#include <memory>
#include <mutex>
#include <ostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <boost/optional/optional.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "kudu/common/common.pb.h"
#include "kudu/common/wire_protocol.h"
#include "kudu/common/wire_protocol.pb.h"
#include "kudu/consensus/consensus.pb.h"
#include "kudu/consensus/consensus_meta.h"
#include "kudu/consensus/consensus_meta_manager.h"
#include "kudu/consensus/log.h"
#include "kudu/consensus/log_anchor_registry.h"
#include "kudu/consensus/metadata.pb.h"
#include "kudu/consensus/opid.pb.h"
#include "kudu/consensus/opid_util.h"
#include "kudu/consensus/quorum_util.h"
#include "kudu/consensus/raft_consensus.h"
#include "kudu/fs/data_dirs.h"
#include "kudu/fs/fs_manager.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/master/master.pb.h"
#include "kudu/rpc/result_tracker.h"
#include "kudu/tablet/metadata.pb.h"
#include "kudu/tablet/tablet.h"
#include "kudu/tablet/tablet_bootstrap.h"
#include "kudu/tablet/tablet_metadata.h"
#include "kudu/tablet/tablet_replica.h"
#include "kudu/tablet/txn_coordinator.h"
#include "kudu/transactions/txn_status_manager.h"
#include "kudu/tserver/heartbeater.h"
#include "kudu/tserver/tablet_server.h"
#include "kudu/util/debug/trace_event.h"
#include "kudu/util/fault_injection.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/flag_validators.h"
#include "kudu/util/logging.h"
#include "kudu/util/monotime.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/stopwatch.h"
#include "kudu/util/threadpool.h"
#include "kudu/util/trace.h"
DEFINE_int32(num_tablets_to_copy_simultaneously, 10,
"Number of threads available to copy tablets from remote servers.");
TAG_FLAG(num_tablets_to_copy_simultaneously, advanced);
DEFINE_int32(num_tablets_to_open_simultaneously, 0,
"Number of threads available to open tablets during startup. If this "
"is set to 0 (the default), then the number of bootstrap threads will "
"be set based on the number of data directories. If the data directories "
"are on some very fast storage device such as SSD or a RAID array, it "
"may make sense to manually tune this.");
TAG_FLAG(num_tablets_to_open_simultaneously, advanced);
DEFINE_int32(num_tablets_to_delete_simultaneously, 0,
"Number of threads available to delete tablets. If this is set to 0 (the "
"default), then the number of delete threads will be set based on the number "
"of data directories. If the data directories are on some very fast storage "
"device such as SSD or a RAID array, it may make sense to manually tune this.");
TAG_FLAG(num_tablets_to_delete_simultaneously, advanced);
DEFINE_int32(tablet_start_warn_threshold_ms, 500,
"If a tablet takes more than this number of millis to start, issue "
"a warning with a trace.");
TAG_FLAG(tablet_start_warn_threshold_ms, hidden);
DEFINE_double(fault_crash_after_blocks_deleted, 0.0,
"Fraction of the time when the tablet will crash immediately "
"after deleting the data blocks during tablet deletion. "
"(For testing only!)");
TAG_FLAG(fault_crash_after_blocks_deleted, unsafe);
DEFINE_double(fault_crash_after_wal_deleted, 0.0,
"Fraction of the time when the tablet will crash immediately "
"after deleting the WAL segments during tablet deletion. "
"(For testing only!)");
TAG_FLAG(fault_crash_after_wal_deleted, unsafe);
DEFINE_double(fault_crash_after_cmeta_deleted, 0.0,
"Fraction of the time when the tablet will crash immediately "
"after deleting the consensus metadata during tablet deletion. "
"(For testing only!)");
TAG_FLAG(fault_crash_after_cmeta_deleted, unsafe);
DEFINE_double(fault_crash_after_tc_files_fetched, 0.0,
"Fraction of the time when the tablet will crash immediately "
"after fetching the files during a tablet copy but before "
"marking the superblock as TABLET_DATA_READY. "
"(For testing only!)");
TAG_FLAG(fault_crash_after_tc_files_fetched, unsafe);
DEFINE_int32(tablet_state_walk_min_period_ms, 1000,
"Minimum amount of time in milliseconds between walks of the "
"tablet map to update tablet state counts.");
TAG_FLAG(tablet_state_walk_min_period_ms, advanced);
DEFINE_int32(delete_tablet_inject_latency_ms, 0,
"Amount of delay in milliseconds to inject into delete tablet operations.");
TAG_FLAG(delete_tablet_inject_latency_ms, unsafe);
DEFINE_int32(update_tablet_stats_interval_ms, 5000,
"Interval at which the tablet statistics should be updated."
"Should be greater than 'heartbeat_interval_ms'");
TAG_FLAG(update_tablet_stats_interval_ms, advanced);
DEFINE_int32(tablet_bootstrap_inject_latency_ms, 0,
"Injects latency into the tablet bootstrapping. "
"For use in tests only.");
TAG_FLAG(tablet_bootstrap_inject_latency_ms, unsafe);
DEFINE_int32(tablet_open_inject_latency_ms, 0,
"Injects latency into the tablet opening. For use in tests only.");
TAG_FLAG(tablet_open_inject_latency_ms, unsafe);
DEFINE_uint32(txn_staleness_tracker_disabled_interval_ms, 60000,
"Polling interval (in milliseconds) for the disabled staleness "
"transaction tracker task to check whether it's been re-enabled. "
"This is made configurable only for testing purposes.");
TAG_FLAG(txn_staleness_tracker_disabled_interval_ms, hidden);
DECLARE_bool(raft_prepare_replacement_before_eviction);
DECLARE_uint32(txn_staleness_tracker_interval_ms);
METRIC_DEFINE_gauge_int32(server, tablets_num_not_initialized,
"Number of Not Initialized Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently not initialized",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_initialized,
"Number of Initialized Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently initialized",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_bootstrapping,
"Number of Bootstrapping Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently bootstrapping",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_running,
"Number of Running Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently running",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_failed,
"Number of Failed Tablets",
kudu::MetricUnit::kTablets,
"Number of failed tablets",
kudu::MetricLevel::kWarn);
METRIC_DEFINE_gauge_int32(server, tablets_num_stopping,
"Number of Stopping Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently stopping",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_stopped,
"Number of Stopped Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently stopped",
kudu::MetricLevel::kInfo);
METRIC_DEFINE_gauge_int32(server, tablets_num_shutdown,
"Number of Shut Down Tablets",
kudu::MetricUnit::kTablets,
"Number of tablets currently shut down",
kudu::MetricLevel::kInfo);
DECLARE_int32(heartbeat_interval_ms);
using kudu::consensus::ConsensusMetadata;
using kudu::consensus::ConsensusMetadataCreateMode;
using kudu::consensus::ConsensusMetadataManager;
using kudu::consensus::ConsensusStatePB;
using kudu::consensus::EXCLUDE_HEALTH_REPORT;
using kudu::consensus::INCLUDE_HEALTH_REPORT;
using kudu::consensus::OpId;
using kudu::consensus::OpIdToString;
using kudu::consensus::RECEIVED_OPID;
using kudu::consensus::RaftConfigPB;
using kudu::consensus::RaftConsensus;
using kudu::consensus::StartTabletCopyRequestPB;
using kudu::consensus::kMinimumTerm;
using kudu::fs::DataDirManager;
using kudu::log::Log;
using kudu::master::ReportedTabletPB;
using kudu::master::TabletReportPB;
using kudu::tablet::ReportedTabletStatsPB;
using kudu::tablet::Tablet;
using kudu::tablet::TABLET_DATA_COPYING;
using kudu::tablet::TABLET_DATA_DELETED;
using kudu::tablet::TABLET_DATA_READY;
using kudu::tablet::TABLET_DATA_TOMBSTONED;
using kudu::tablet::TabletDataState;
using kudu::tablet::TabletMetadata;
using kudu::tablet::TabletReplica;
using kudu::transactions::TxnStatusManagerFactory;
using kudu::tserver::TabletCopyClient;
using std::make_shared;
using std::set;
using std::shared_ptr;
using std::string;
using std::vector;
using strings::Substitute;
namespace kudu {
namespace tserver {
namespace {
bool ValidateUpdateTabletStatsInterval() {
if (FLAGS_update_tablet_stats_interval_ms < FLAGS_heartbeat_interval_ms) {
LOG(ERROR) << "Tablet stats updating interval (--update_tablet_stats_interval_ms)"
<< "should be greater than heartbeat interval (--heartbeat_interval_ms)";
return false;
}
return true;
}
} // anonymous namespace
GROUP_FLAG_VALIDATOR(update_tablet_stats_interval_ms, ValidateUpdateTabletStatsInterval);
TSTabletManager::TSTabletManager(TabletServer* server)
: fs_manager_(server->fs_manager()),
cmeta_manager_(new ConsensusMetadataManager(fs_manager_)),
server_(server),
shutdown_latch_(1),
metric_registry_(server->metric_registry()),
tablet_copy_metrics_(server->metric_entity()),
state_(MANAGER_INITIALIZING) {
// A heartbeat msg without statistics will be considered to be from an old
// version, thus it's necessary to trigger updating stats as soon as possible.
next_update_time_ = MonoTime::Now();
METRIC_tablets_num_not_initialized.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::NOT_INITIALIZED);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_initialized.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::INITIALIZED);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_bootstrapping.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::BOOTSTRAPPING);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_running.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::RUNNING);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_failed.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::FAILED);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_stopping.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::STOPPING);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_stopped.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::STOPPED);
})
->AutoDetach(&metric_detacher_);
METRIC_tablets_num_shutdown.InstantiateFunctionGauge(
server->metric_entity(), [this]() {
return this->RefreshTabletStateCacheAndReturnCount(tablet::SHUTDOWN);
})
->AutoDetach(&metric_detacher_);
}
// Base class for tasks submitted against TSTabletManager threadpools whose
// whose callback must fire, for example if the callback responds to an RPC.
class TabletManagerRunnable {
public:
TabletManagerRunnable(TSTabletManager* ts_tablet_manager,
std::function<void(const Status&, TabletServerErrorPB::Code)> cb)
: ts_tablet_manager_(ts_tablet_manager),
cb_(std::move(cb)) {
}
virtual ~TabletManagerRunnable() {
// If the task is destroyed without the Run() method being invoked, we
// must invoke the user callback ourselves in order to free request
// resources. This may happen when the ThreadPool is shut down while the
// task is enqueued.
if (!cb_invoked_) {
cb_(Status::ServiceUnavailable("Tablet server shutting down"),
TabletServerErrorPB::THROTTLED);
}
}
// Runs the task itself.
virtual void Run() = 0;
// Disable automatic invocation of the callback by the destructor.
// Does not disable invocation of the callback by Run().
void DisableCallback() {
cb_invoked_ = true;
}
protected:
TSTabletManager* const ts_tablet_manager_;
const std::function<void(const Status&, TabletServerErrorPB::Code)> cb_;
bool cb_invoked_ = false;
DISALLOW_COPY_AND_ASSIGN(TabletManagerRunnable);
};
TSTabletManager::~TSTabletManager() {
}
Status TSTabletManager::Init() {
CHECK_EQ(state(), MANAGER_INITIALIZING);
// Start the tablet copy thread pool. We set a max queue size of 0 so that if
// the number of requests exceeds the number of threads, a
// SERVICE_UNAVAILABLE error may be returned to the remote caller.
RETURN_NOT_OK(ThreadPoolBuilder("tablet-copy")
.set_max_queue_size(0)
.set_max_threads(FLAGS_num_tablets_to_copy_simultaneously)
.Build(&tablet_copy_pool_));
// Start the threadpools we'll use to open and delete tablets.
// This has to be done in Init() instead of the constructor, since the
// FsManager isn't initialized until this point.
int max_open_threads = FLAGS_num_tablets_to_open_simultaneously;
if (max_open_threads == 0) {
// Default to the number of disks.
max_open_threads = fs_manager_->GetDataRootDirs().size();
}
RETURN_NOT_OK(ThreadPoolBuilder("tablet-open")
.set_max_threads(max_open_threads)
.Build(&open_tablet_pool_));
int max_delete_threads = FLAGS_num_tablets_to_delete_simultaneously;
if (max_delete_threads == 0) {
// Default to the number of disks.
max_delete_threads = fs_manager_->GetDataRootDirs().size();
}
RETURN_NOT_OK(ThreadPoolBuilder("tablet-delete")
.set_max_threads(max_delete_threads)
.Build(&delete_tablet_pool_));
// TODO(aserbin): if better parallelism is needed to serve higher txn volume,
// consider using multiple threads in this pool and schedule
// per-tablet-replica clean-up tasks via threadpool serial
// tokens to make sure no more than one clean-up task
// is running against a txn status tablet replica.
RETURN_NOT_OK(ThreadPoolBuilder("txn-status-manager")
.set_max_threads(1)
.set_max_queue_size(0)
.Build(&txn_status_manager_pool_));
RETURN_NOT_OK(txn_status_manager_pool_->Submit([this]() {
this->TxnStalenessTrackerTask();
}));
// Search for tablets in the metadata dir.
vector<string> tablet_ids;
RETURN_NOT_OK(fs_manager_->ListTabletIds(&tablet_ids));
InitLocalRaftPeerPB();
vector<scoped_refptr<TabletMetadata>> metas;
// First, load all of the tablet metadata. We do this before we start
// submitting the actual OpenTablet() tasks so that we don't have to compete
// for disk resources, etc, with bootstrap processes and running tablets.
int loaded_count = 0;
for (const string& tablet_id : tablet_ids) {
KLOG_EVERY_N_SECS(INFO, 1) << Substitute("Loading tablet metadata ($0/$1 complete)",
loaded_count, tablet_ids.size());
scoped_refptr<TabletMetadata> meta;
RETURN_NOT_OK_PREPEND(OpenTabletMeta(tablet_id, &meta),
"Failed to open tablet metadata for tablet: " + tablet_id);
loaded_count++;
if (meta->tablet_data_state() != TABLET_DATA_READY) {
RETURN_NOT_OK(HandleNonReadyTabletOnStartup(meta));
continue;
}
metas.push_back(meta);
}
LOG(INFO) << Substitute("Loaded tablet metadata ($0 total tablets, $1 live tablets)",
loaded_count, metas.size());
// Now submit the "Open" task for each.
int registered_count = 0;
for (const auto& meta : metas) {
KLOG_EVERY_N_SECS(INFO, 1) << Substitute("Registering tablets ($0/$1 complete)",
registered_count, metas.size());
scoped_refptr<TransitionInProgressDeleter> deleter;
{
std::lock_guard<RWMutex> lock(lock_);
CHECK_OK(StartTabletStateTransitionUnlocked(meta->tablet_id(), "opening tablet", &deleter));
}
scoped_refptr<TabletReplica> replica;
RETURN_NOT_OK(CreateAndRegisterTabletReplica(meta, NEW_REPLICA, &replica));
RETURN_NOT_OK(open_tablet_pool_->Submit([this, replica, deleter]() {
this->OpenTablet(replica, deleter);
}));
registered_count++;
}
LOG(INFO) << Substitute("Registered $0 tablets", registered_count);
{
std::lock_guard<RWMutex> lock(lock_);
state_ = MANAGER_RUNNING;
}
return Status::OK();
}
Status TSTabletManager::WaitForAllBootstrapsToFinish() {
CHECK_EQ(state(), MANAGER_RUNNING);
open_tablet_pool_->Wait();
shared_lock<RWMutex> l(lock_);
for (const TabletMap::value_type& entry : tablet_map_) {
if (entry.second->state() == tablet::FAILED) {
return entry.second->error();
}
}
return Status::OK();
}
Status TSTabletManager::CreateNewTablet(const string& table_id,
const string& tablet_id,
const Partition& partition,
const string& table_name,
const Schema& schema,
const PartitionSchema& partition_schema,
RaftConfigPB config,
boost::optional<TableExtraConfigPB> extra_config,
boost::optional<string> dimension_label,
boost::optional<TableTypePB> table_type,
scoped_refptr<TabletReplica>* replica) {
CHECK_EQ(state(), MANAGER_RUNNING);
CHECK(IsRaftConfigMember(server_->instance_pb().permanent_uuid(), config));
// Set the initial opid_index for a RaftConfigPB to -1.
config.set_opid_index(consensus::kInvalidOpIdIndex);
scoped_refptr<TransitionInProgressDeleter> deleter;
{
// acquire the lock in exclusive mode as we'll add a entry to the
// transition_in_progress_ set if the lookup fails.
std::lock_guard<RWMutex> lock(lock_);
TRACE("Acquired tablet manager lock");
// Sanity check that the tablet isn't already registered.
scoped_refptr<TabletReplica> junk;
if (LookupTabletUnlocked(tablet_id, &junk)) {
return Status::AlreadyPresent("Tablet already registered", tablet_id);
}
// Sanity check that the tablet's creation isn't already in progress
RETURN_NOT_OK(StartTabletStateTransitionUnlocked(tablet_id, "creating tablet", &deleter));
}
// Create the metadata.
TRACE("Creating new metadata...");
scoped_refptr<TabletMetadata> meta;
RETURN_NOT_OK_PREPEND(
TabletMetadata::CreateNew(fs_manager_,
tablet_id,
table_name,
table_id,
schema,
partition_schema,
partition,
TABLET_DATA_READY,
boost::none,
/*supports_live_row_count=*/ true,
std::move(extra_config),
std::move(dimension_label),
std::move(table_type),
&meta),
"Couldn't create tablet metadata");
// We must persist the consensus metadata to disk before starting a new
// tablet's TabletReplica and RaftConsensus implementation.
RETURN_NOT_OK_PREPEND(cmeta_manager_->Create(tablet_id, config, kMinimumTerm),
"Unable to create new ConsensusMetadata for tablet " + tablet_id);
scoped_refptr<TabletReplica> new_replica;
RETURN_NOT_OK(CreateAndRegisterTabletReplica(meta, NEW_REPLICA, &new_replica));
// We can run this synchronously since there is nothing to bootstrap.
RETURN_NOT_OK(open_tablet_pool_->Submit([this, new_replica, deleter]() {
this->OpenTablet(new_replica, deleter);
}));
if (replica) {
*replica = new_replica;
}
return Status::OK();
}
Status TSTabletManager::CheckLeaderTermNotLower(const string& tablet_id,
int64_t leader_term,
int64_t last_logged_term) {
if (PREDICT_FALSE(leader_term < last_logged_term)) {
Status s = Status::InvalidArgument(
Substitute("Leader has replica of tablet $0 with term $1, which "
"is lower than last-logged term $2 on local replica. Rejecting "
"tablet copy request",
tablet_id, leader_term, last_logged_term));
LOG(WARNING) << LogPrefix(tablet_id) << "Tablet Copy: " << s.ToString();
return s;
}
return Status::OK();
}
// Tablet Copy runnable that will run on a ThreadPool.
class TabletCopyRunnable : public TabletManagerRunnable {
public:
TabletCopyRunnable(TSTabletManager* ts_tablet_manager,
const StartTabletCopyRequestPB* req,
std::function<void(const Status&, TabletServerErrorPB::Code)> cb)
: TabletManagerRunnable(ts_tablet_manager, std::move(cb)),
req_(req) {
}
void Run() override {
ts_tablet_manager_->RunTabletCopy(req_, cb_);
cb_invoked_ = true;
}
private:
const StartTabletCopyRequestPB* const req_;
DISALLOW_COPY_AND_ASSIGN(TabletCopyRunnable);
};
void TSTabletManager::StartTabletCopy(
const StartTabletCopyRequestPB* req,
std::function<void(const Status&, TabletServerErrorPB::Code)> cb) {
// Attempt to submit the tablet copy task to the threadpool. The threadpool
// is configured with 0 queue slots, so if there is not a thread immediately
// available the submit will fail. When successful, the table copy task will
// immediately check whether the tablet is already being copied, and if so,
// return ALREADY_INPROGRESS.
string tablet_id = req->tablet_id();
auto runnable = make_shared<TabletCopyRunnable>(this, req, cb);
Status s = tablet_copy_pool_->Submit([runnable]() { runnable->Run(); });
if (PREDICT_TRUE(s.ok())) {
return;
}
// We were unable to submit the tablet copy task to the thread pool. We will
// invoke the callback ourselves, so disable the automatic callback mechanism.
runnable->DisableCallback();
// Check if the tablet is already in transition (i.e. being copied).
boost::optional<string> transition;
{
// Lock must be dropped before executing callbacks.
shared_lock<RWMutex> lock(lock_);
auto* t = FindOrNull(transition_in_progress_, tablet_id);
if (t) {
transition = *t;
}
}
if (transition) {
cb(Status::IllegalState(
strings::Substitute("State transition of tablet $0 already in progress: $1",
tablet_id, *transition)),
TabletServerErrorPB::ALREADY_INPROGRESS);
return;
}
// The tablet is not already being copied, but there are no remaining slots in
// the threadpool.
if (s.IsServiceUnavailable()) {
cb(s, TabletServerErrorPB::THROTTLED);
return;
}
cb(s, TabletServerErrorPB::UNKNOWN_ERROR);
}
#define CALLBACK_AND_RETURN(status) \
do { \
cb(status, error_code); \
return; \
} while (0)
#define CALLBACK_RETURN_NOT_OK(expr) \
do { \
Status _s = (expr); \
if (PREDICT_FALSE(!_s.ok())) { \
CALLBACK_AND_RETURN(_s); \
} \
} while (0)
#define CALLBACK_RETURN_NOT_OK_WITH_ERROR(expr, error) \
do { \
Status _s = (expr); \
if (PREDICT_FALSE(!_s.ok())) { \
error_code = (error); \
CALLBACK_AND_RETURN(_s); \
} \
} while (0)
void TSTabletManager::RunTabletCopy(
const StartTabletCopyRequestPB* req,
std::function<void(const Status&, TabletServerErrorPB::Code)> cb) {
TabletServerErrorPB::Code error_code = TabletServerErrorPB::UNKNOWN_ERROR;
// Copy these strings so they stay valid even after responding to the request.
string tablet_id = req->tablet_id(); // NOLINT(*)
string copy_source_uuid = req->copy_peer_uuid(); // NOLINT(*)
HostPort copy_source_addr = HostPortFromPB(req->copy_peer_addr());
int64_t leader_term = req->caller_term();
scoped_refptr<TabletReplica> old_replica;
scoped_refptr<TabletMetadata> meta;
bool replacing_tablet = false;
scoped_refptr<TransitionInProgressDeleter> deleter;
{
std::lock_guard<RWMutex> lock(lock_);
if (LookupTabletUnlocked(tablet_id, &old_replica)) {
meta = old_replica->tablet_metadata();
replacing_tablet = true;
}
Status ret = StartTabletStateTransitionUnlocked(tablet_id, "copying tablet",
&deleter);
if (!ret.ok()) {
error_code = TabletServerErrorPB::ALREADY_INPROGRESS;
CALLBACK_AND_RETURN(ret);
}
}
if (replacing_tablet) {
// Make sure the existing tablet replica is shut down and tombstoned.
TabletDataState data_state = meta->tablet_data_state();
switch (data_state) {
case TABLET_DATA_COPYING:
// This should not be possible due to the transition_in_progress_ "lock".
LOG(FATAL) << LogPrefix(tablet_id) << "Tablet Copy: "
<< "Found tablet in TABLET_DATA_COPYING state during StartTabletCopy()";
case TABLET_DATA_TOMBSTONED: {
boost::optional<OpId> last_logged_opid = meta->tombstone_last_logged_opid();
if (last_logged_opid) {
CALLBACK_RETURN_NOT_OK_WITH_ERROR(CheckLeaderTermNotLower(tablet_id, leader_term,
last_logged_opid->term()),
TabletServerErrorPB::INVALID_CONFIG);
}
// Shut down the old TabletReplica so that it is no longer allowed to
// mutate the ConsensusMetadata.
old_replica->Shutdown();
break;
}
case TABLET_DATA_READY: {
shared_ptr<RaftConsensus> consensus = old_replica->shared_consensus();
if (!consensus) {
CALLBACK_AND_RETURN(
Status::IllegalState("consensus unavailable: tablet not running", tablet_id));
}
boost::optional<OpId> opt_last_logged_opid = consensus->GetLastOpId(RECEIVED_OPID);
if (!opt_last_logged_opid) {
CALLBACK_AND_RETURN(
Status::IllegalState("cannot determine last-logged opid: tablet not running",
tablet_id));
}
CHECK(opt_last_logged_opid);
CALLBACK_RETURN_NOT_OK_WITH_ERROR(
CheckLeaderTermNotLower(tablet_id, leader_term, opt_last_logged_opid->term()),
TabletServerErrorPB::INVALID_CONFIG);
// Shut down the old TabletReplica so that it is no longer allowed to
// mutate the ConsensusMetadata.
old_replica->Shutdown();
// Note that this leaves the data dir manager without any references to
// tablet_id. This is okay because the tablet_copy_client should
// generate a new disk group during the call to Start().
// Tombstone the tablet and store the last-logged OpId.
// TODO(mpercy): Because we begin shutdown of the tablet after we check our
// last-logged term against the leader's term, there may be operations
// in flight and it may be possible for the same check in the tablet
// copy client Start() method to fail. This will leave the replica in
// a tombstoned state, and then the leader with the latest log entries
// will simply tablet copy this replica again. We could try to
// check again after calling Shutdown(), and if the check fails, try to
// reopen the tablet. For now, we live with the (unlikely) race.
Status s = DeleteTabletData(meta, cmeta_manager_, TABLET_DATA_TOMBSTONED,
opt_last_logged_opid);
if (PREDICT_FALSE(!s.ok())) {
CALLBACK_AND_RETURN(
s.CloneAndPrepend(Substitute("Unable to delete on-disk data from tablet $0",
tablet_id)));
}
TRACE("Shutdown and deleted data from running replica");
break;
}
default:
CALLBACK_AND_RETURN(Status::IllegalState(
Substitute("Found tablet in unsupported state for tablet copy. "
"Tablet: $0, tablet data state: $1",
tablet_id, TabletDataState_Name(data_state))));
}
}
const string kSrcPeerInfo = Substitute("$0 ($1)", copy_source_uuid, copy_source_addr.ToString());
string init_msg = LogPrefix(tablet_id) +
Substitute("Initiating tablet copy from peer $0", kSrcPeerInfo);
LOG(INFO) << init_msg;
TRACE(init_msg);
// The TabletCopyClient instance should be kept alive until the tablet
// is successfully copied over and opened/started. This is because we want
// to maintain the LogAnchor until the replica starts up. Upon destruction,
// the TabletCopyClient instance sends an RPC explicitly ending the tablet
// copy session. The source replica then destroys the corresponding
// TabletCopySourceSession object, releasing its LogAnchor and allowing
// the WAL segments being copied to be GCed.
//
// See below for more details on why anchoring of WAL segments is necessary.
//
// * Assume there are WAL segments 0-10 when tablet copy starts. Tablet copy
// will anchor 0 until its destroyed, meaning the source replica wont
// delete it.
//
// * When tablet copy is done the tablet still needs to bootstrap which will
// take some time.
//
// * When tablet bootstrap is done, the new replica will need to continue
// catching up to the leader, this time through consensus. It needs segment
// 11 to be still available. We need the anchor to still be alive at this
// point, otherwise there is nothing preventing the leader from deleting
// segment 11 and thus making the new replica unable to catch up. Yes, it's
// not optimal: we're anchoring 0 and we might only need to anchor 10/11.
// However, having no anchor at all is likely to cause replicas to start
// fail copying.
//
// NOTE:
// Ideally, we should wait until the leader starts tracking of the target
// replica's log watermark. As for current implementation, the intent is
// to at least try preventing GC of logs before the tablet replica connects
// to the leader.
//
// TODO(aserbin): make this robust and more optimal than it is now.
TabletCopyClient tc_client(tablet_id, fs_manager_, cmeta_manager_,
server_->messenger(), &tablet_copy_metrics_);
// Download and persist the remote superblock in TABLET_DATA_COPYING state.
if (replacing_tablet) {
CALLBACK_RETURN_NOT_OK(tc_client.SetTabletToReplace(meta, leader_term));
}
CALLBACK_RETURN_NOT_OK(tc_client.Start(copy_source_addr, &meta));
// After calling TabletCopyClient::Start(), the superblock is persisted in
// TABLET_DATA_COPYING state. TabletCopyClient will automatically tombstone
// the tablet by implicitly calling Abort() on itself if it is destroyed
// prior to calling TabletCopyClient::Finish(), which if successful
// transitions the tablet into the TABLET_DATA_READY state.
// Registering an unstarted TabletReplica allows for tombstoned voting and
// offers visibility through the Web UI.
RegisterTabletReplicaMode mode = replacing_tablet ? REPLACEMENT_REPLICA : NEW_REPLICA;
scoped_refptr<TabletReplica> replica;
CALLBACK_RETURN_NOT_OK(CreateAndRegisterTabletReplica(meta, mode, &replica));
TRACE("Replica registered.");
// Now we invoke the StartTabletCopy callback and respond success to the
// remote caller, since StartTabletCopy() is an asynchronous RPC call. Then
// we proceed with the Tablet Copy process.
cb(Status::OK(), TabletServerErrorPB::UNKNOWN_ERROR);
cb = [](const Status&, TabletServerErrorPB::Code) {
LOG(FATAL) << "Callback invoked twice from TSTabletManager::RunTabletCopy()";
};
// From this point onward, we do not notify the caller about progress or
// success. That said, if the copy fails for whatever reason, we must make
// sure to clean up.
Status s;
auto fail_tablet = MakeScopedCleanup([&] {
replica->SetError(s);
replica->Shutdown();
});
// Go through and synchronously download the remote blocks and WAL segments.
s = tc_client.FetchAll(replica);
if (!s.ok()) {
LOG(WARNING) << LogPrefix(tablet_id) << "Tablet Copy: Unable to fetch data from remote peer "
<< kSrcPeerInfo << ": " << s.ToString();
return;
}
MAYBE_FAULT(FLAGS_fault_crash_after_tc_files_fetched);
// Write out the last files to make the new replica visible and update the
// TabletDataState in the superblock to TABLET_DATA_READY.
s = tc_client.Finish();
if (!s.ok()) {
LOG(WARNING) << LogPrefix(tablet_id) << "Tablet Copy: Failure calling Finish(): "
<< s.ToString();
return;
}
fail_tablet.cancel();
// Bootstrap and start the fully-copied tablet.
OpenTablet(replica, deleter);
}
// Create and register a new TabletReplica, given tablet metadata.
Status TSTabletManager::CreateAndRegisterTabletReplica(
scoped_refptr<TabletMetadata> meta,
RegisterTabletReplicaMode mode,
scoped_refptr<TabletReplica>* replica_out) {
// TODO(awong): this factory will at some point contain some tserver-wide
// state like a system client that can make calls to leader tablets. For now,
// just use a simple local factory.
TxnStatusManagerFactory tsm_factory;
const auto& tablet_id = meta->tablet_id();
scoped_refptr<TabletReplica> replica(
new TabletReplica(std::move(meta),
cmeta_manager_,
local_peer_pb_,
server_->tablet_apply_pool(),
&tsm_factory,
[this, tablet_id](const string& reason) {
this->MarkTabletDirty(tablet_id, reason);
}));
Status s = replica->Init({ server_->mutable_quiescing(),
server_->num_raft_leaders(),
server_->raft_pool() });
if (PREDICT_FALSE(!s.ok())) {
replica->SetError(s);
replica->Shutdown();
}
RegisterTablet(tablet_id, replica, mode);
*replica_out = std::move(replica);
return Status::OK();
}
Status TSTabletManager::BeginReplicaStateTransition(
const string& tablet_id,
const string& reason,
scoped_refptr<TabletReplica>* replica,
scoped_refptr<TransitionInProgressDeleter>* deleter,
TabletServerErrorPB::Code* error_code) {
// Acquire the lock in exclusive mode as we'll add a entry to the
// transition_in_progress_ map.
std::lock_guard<RWMutex> lock(lock_);
TRACE("Acquired tablet manager lock");
RETURN_NOT_OK(CheckRunningUnlocked(error_code));
if (!LookupTabletUnlocked(tablet_id, replica)) {
if (error_code) {
*error_code = TabletServerErrorPB::TABLET_NOT_FOUND;
}
return Status::NotFound("Tablet not found", tablet_id);
}
// Sanity check that the tablet's transition isn't already in progress
Status s = StartTabletStateTransitionUnlocked(tablet_id, reason, deleter);
if (PREDICT_FALSE(!s.ok())) {
if (error_code) {
*error_code = TabletServerErrorPB::ALREADY_INPROGRESS;
}
return s;
}
return Status::OK();
}
// Delete Tablet runnable that will run on a ThreadPool.
class DeleteTabletRunnable : public TabletManagerRunnable {
public:
DeleteTabletRunnable(TSTabletManager* ts_tablet_manager,
string tablet_id,
tablet::TabletDataState delete_type,
const boost::optional<int64_t>& cas_config_index, // NOLINT
std::function<void(const Status&, TabletServerErrorPB::Code)> cb)
: TabletManagerRunnable(ts_tablet_manager, std::move(cb)),
tablet_id_(std::move(tablet_id)),
delete_type_(delete_type),
cas_config_index_(cas_config_index) {
}
void Run() override {
TabletServerErrorPB::Code code = TabletServerErrorPB::UNKNOWN_ERROR;
Status s = ts_tablet_manager_->DeleteTablet(tablet_id_, delete_type_, cas_config_index_, &code);
cb_(s, code);
cb_invoked_ = true;
}
private:
const string tablet_id_;
const tablet::TabletDataState delete_type_;
const boost::optional<int64_t> cas_config_index_;
DISALLOW_COPY_AND_ASSIGN(DeleteTabletRunnable);
};
void TSTabletManager::DeleteTabletAsync(
const string& tablet_id,
tablet::TabletDataState delete_type,
const boost::optional<int64_t>& cas_config_index,
const std::function<void(const Status&, TabletServerErrorPB::Code)>& cb) {
auto runnable = make_shared<DeleteTabletRunnable>(this, tablet_id, delete_type,
cas_config_index, cb);
Status s = delete_tablet_pool_->Submit([runnable]() { runnable->Run(); });
if (PREDICT_TRUE(s.ok())) {
return;
}
// Threadpool submission failed, so we'll invoke the callback ourselves.
runnable->DisableCallback();
cb(s, s.IsServiceUnavailable() ? TabletServerErrorPB::THROTTLED :
TabletServerErrorPB::UNKNOWN_ERROR);
}
Status TSTabletManager::DeleteTablet(
const string& tablet_id,
TabletDataState delete_type,
const boost::optional<int64_t>& cas_config_index,
TabletServerErrorPB::Code* error_code) {
if (delete_type != TABLET_DATA_DELETED && delete_type != TABLET_DATA_TOMBSTONED) {
return Status::InvalidArgument("DeleteTablet() requires an argument that is one of "
"TABLET_DATA_DELETED or TABLET_DATA_TOMBSTONED",
Substitute("Given: $0 ($1)",
TabletDataState_Name(delete_type), delete_type));
}
TRACE("Deleting tablet $0", tablet_id);
if (PREDICT_FALSE(FLAGS_delete_tablet_inject_latency_ms > 0)) {
LOG(WARNING) << "Injecting " << FLAGS_delete_tablet_inject_latency_ms
<< "ms of latency into DeleteTablet";
SleepFor(MonoDelta::FromMilliseconds(FLAGS_delete_tablet_inject_latency_ms));
}
scoped_refptr<TabletReplica> replica;
scoped_refptr<TransitionInProgressDeleter> deleter;
RETURN_NOT_OK(BeginReplicaStateTransition(tablet_id, "deleting tablet", &replica,
&deleter, error_code));
// If the tablet has been deleted or forcefully shut down, the CAS check
// isn't possible because consensus and therefore the log is not available.
TabletDataState data_state = replica->tablet_metadata()->tablet_data_state();
bool tablet_already_deleted = (data_state == TABLET_DATA_DELETED ||
data_state == TABLET_DATA_TOMBSTONED);
// If a tablet is already tombstoned, then a request to tombstone
// the same tablet should become a no-op.
if (delete_type == TABLET_DATA_TOMBSTONED && data_state == TABLET_DATA_TOMBSTONED) {
return Status::OK();
}
// They specified an "atomic" delete. Check the committed config's opid_index.
// TODO(mpercy): There's actually a race here between the check and shutdown,
// but it's tricky to fix. We could try checking again after the shutdown and
// restarting the tablet if the local replica committed a higher config change
// op during that time, or potentially something else more invasive.
shared_ptr<RaftConsensus> consensus = replica->shared_consensus();
if (cas_config_index && !tablet_already_deleted) {
if (!consensus) {
*error_code = TabletServerErrorPB::TABLET_NOT_RUNNING;
return Status::IllegalState("Raft Consensus not available. Tablet shutting down");
}
RaftConfigPB committed_config = consensus->CommittedConfig();
if (committed_config.opid_index() > *cas_config_index) {
*error_code = TabletServerErrorPB::CAS_FAILED;
return Status::IllegalState(Substitute("Request specified cas_config_opid_index_less_or_equal"
" of $0 but the committed config has opid_index of $1",
*cas_config_index,
committed_config.opid_index()));
}
}
replica->Stop();
boost::optional<OpId> opt_last_logged_opid;
if (consensus) {
opt_last_logged_opid = consensus->GetLastOpId(RECEIVED_OPID);
DCHECK(!opt_last_logged_opid || opt_last_logged_opid->IsInitialized());
}
Status s = DeleteTabletData(replica->tablet_metadata(), cmeta_manager_, delete_type,
opt_last_logged_opid);
if (PREDICT_FALSE(!s.ok())) {
s = s.CloneAndPrepend(Substitute("Unable to delete on-disk data from tablet $0",
tablet_id));
// TODO(awong): A failure status here indicates a failure to update the
// tablet metadata, consensus metadta, or WAL (failures to remove blocks
// only log warnings). Once the above are no longer points of failure,
// handle errors here accordingly.
//
// If this fails, there is no guarantee that the on-disk metadata reflects
// that the tablet is deleted. To be safe, crash here.
LOG(FATAL) << Substitute("Failed to delete tablet data for $0: ",
tablet_id) << s.ToString();
}
replica->SetStatusMessage("Deleted tablet blocks from disk");
// Only DELETED tablets are fully shut down and removed from the tablet map.
if (delete_type == TABLET_DATA_DELETED) {
replica->Shutdown();
std::lock_guard<RWMutex> lock(lock_);
RETURN_NOT_OK(CheckRunningUnlocked(error_code));
CHECK_EQ(1, tablet_map_.erase(tablet_id)) << tablet_id;
InsertOrDie(&perm_deleted_tablet_ids_, tablet_id);
}
return Status::OK();
}
string TSTabletManager::LogPrefix(const string& tablet_id, FsManager *fs_manager) {
DCHECK(fs_manager != nullptr);
return Substitute("T $0 P $1: ", tablet_id, fs_manager->uuid());
}
Status TSTabletManager::CheckRunningUnlocked(
TabletServerErrorPB::Code* error_code) const {
if (state_ == MANAGER_RUNNING) {
return Status::OK();
}
if (error_code) {
*error_code = TabletServerErrorPB::TABLET_NOT_RUNNING;
}
return Status::ServiceUnavailable(Substitute("Tablet Manager is not running: $0",
TSTabletManagerStatePB_Name(state_)));
}
Status TSTabletManager::StartTabletStateTransitionUnlocked(
const string& tablet_id,
const string& reason,
scoped_refptr<TransitionInProgressDeleter>* deleter) {
lock_.AssertAcquiredForWriting();
if (ContainsKey(perm_deleted_tablet_ids_, tablet_id)) {
// When a table is deleted, the master sends a DeleteTablet() RPC to every
// replica of every tablet with the TABLET_DATA_DELETED parameter, which
// indicates a "permanent" tablet deletion. If a follower services
// DeleteTablet() before the leader does, it's possible for the leader to
// react to the missing replica by asking the follower to tablet copy
// itself.
//
// If the tablet was permanently deleted, we should not allow it to
// transition back to "liveness" because that can result in flapping back
// and forth between deletion and tablet copying.
return Status::IllegalState(
Substitute("Tablet $0 was permanently deleted. Cannot transition from state $1.",
tablet_id, TabletDataState_Name(TABLET_DATA_DELETED)));
}
if (!InsertIfNotPresent(&transition_in_progress_, tablet_id, reason)) {
return Status::AlreadyPresent(
Substitute("State transition of tablet $0 already in progress: $1",
tablet_id, transition_in_progress_[tablet_id]));
}
deleter->reset(new TransitionInProgressDeleter(&transition_in_progress_, &lock_, tablet_id));
return Status::OK();
}
Status TSTabletManager::OpenTabletMeta(const string& tablet_id,
scoped_refptr<TabletMetadata>* metadata) {
VLOG(1) << LogPrefix(tablet_id) << "Loading tablet metadata";
TRACE("Loading metadata...");
scoped_refptr<TabletMetadata> meta;
RETURN_NOT_OK_PREPEND(TabletMetadata::Load(fs_manager_, tablet_id, &meta),
strings::Substitute("Failed to load tablet metadata for tablet id $0",
tablet_id));
TRACE("Metadata loaded");
metadata->swap(meta);
return Status::OK();
}
void TSTabletManager::OpenTablet(const scoped_refptr<TabletReplica>& replica,
const scoped_refptr<TransitionInProgressDeleter>& deleter) {
const string& tablet_id = replica->tablet_id();
TRACE_EVENT1("tserver", "TSTabletManager::OpenTablet",
"tablet_id", tablet_id);
shared_ptr<Tablet> tablet;
scoped_refptr<Log> log;
VLOG(1) << LogPrefix(tablet_id) << "Bootstrapping tablet";
TRACE("Bootstrapping tablet");
if (FLAGS_tablet_bootstrap_inject_latency_ms > 0) {
LOG(WARNING) << "Injecting " << FLAGS_tablet_bootstrap_inject_latency_ms
<< "ms delay in tablet bootstrapping";
SleepFor(MonoDelta::FromMilliseconds(FLAGS_tablet_bootstrap_inject_latency_ms));
}
scoped_refptr<ConsensusMetadata> cmeta;
Status s = cmeta_manager_->Load(replica->tablet_id(), &cmeta);
auto fail_tablet = MakeScopedCleanup([&]() {
// If something goes wrong, clean up the replica's internal members and mark
// it FAILED.
replica->SetError(s);
replica->Shutdown();
});
if (PREDICT_FALSE(!s.ok())) {
LOG(ERROR) << LogPrefix(tablet_id) << "Failed to load consensus metadata: " << s.ToString();
return;
}
consensus::ConsensusBootstrapInfo bootstrap_info;
LOG_TIMING_PREFIX(INFO, LogPrefix(tablet_id), "bootstrapping tablet") {
// Disable tracing for the bootstrap, since this would result in
// potentially millions of op traces being attached to the
// TabletCopy trace.
ADOPT_TRACE(nullptr);
// TODO(mpercy): Handle crash mid-creation of tablet? Do we ever end up
// with a partially created tablet here?
replica->SetBootstrapping();
s = BootstrapTablet(replica->tablet_metadata(),
replica->consensus()->CommittedConfig(),
server_->clock(),
server_->mem_tracker(),
server_->result_tracker(),
metric_registry_,
server_->file_cache(),
replica,
replica->log_anchor_registry(),
&tablet,
&log,
&bootstrap_info);
if (!s.ok()) {
LOG(ERROR) << LogPrefix(tablet_id) << "Tablet failed to bootstrap: "
<< s.ToString();
return;
}
}
MonoTime start(MonoTime::Now());
LOG_TIMING_PREFIX(INFO, LogPrefix(tablet_id), "starting tablet") {
TRACE("Starting tablet replica");
s = replica->Start(bootstrap_info,
tablet,
server_->clock(),
server_->messenger(),
server_->result_tracker(),
log,
server_->tablet_prepare_pool(),
server_->dns_resolver());
if (!s.ok()) {
LOG(ERROR) << LogPrefix(tablet_id) << "Tablet failed to start: "
<< s.ToString();
return;
}
replica->RegisterMaintenanceOps(server_->maintenance_manager());
}
if (PREDICT_FALSE(FLAGS_tablet_open_inject_latency_ms > 0)) {
LOG(WARNING) << "Injecting " << FLAGS_tablet_open_inject_latency_ms
<< "ms of latency into OpenTablet";
SleepFor(MonoDelta::FromMilliseconds(FLAGS_tablet_open_inject_latency_ms));
}
// Now that the tablet has successfully opened, cancel the cleanup.
fail_tablet.cancel();
int elapsed_ms = (MonoTime::Now() - start).ToMilliseconds();
if (elapsed_ms > FLAGS_tablet_start_warn_threshold_ms) {
LOG(WARNING) << LogPrefix(tablet_id) << "Tablet startup took " << elapsed_ms << "ms";
if (Trace::CurrentTrace()) {
LOG(WARNING) << LogPrefix(tablet_id) << "Trace:" << std::endl
<< Trace::CurrentTrace()->DumpToString();
}
}
deleter->Destroy();
MarkTabletDirty(tablet_id, "Open tablet completed");
}
void TSTabletManager::Shutdown() {
{
std::lock_guard<RWMutex> lock(lock_);
switch (state_) {
case MANAGER_QUIESCING: {
VLOG(1) << "Tablet manager shut down already in progress..";
return;
}
case MANAGER_SHUTDOWN: {
VLOG(1) << "Tablet manager has already been shut down.";
return;
}
case MANAGER_INITIALIZING:
case MANAGER_RUNNING: {
LOG(INFO) << "Shutting down tablet manager...";
state_ = MANAGER_QUIESCING;
break;
}
default: {
LOG(FATAL) << "Invalid state: " << TSTabletManagerStatePB_Name(state_);
}
}
}
// Stop copying tablets.
// TODO(mpercy): Cancel all outstanding tablet copy tasks (KUDU-1795).
tablet_copy_pool_->Shutdown();
// Shut down the bootstrap pool, so no new tablets are registered after this point.
open_tablet_pool_->Shutdown();
// Shut down the delete pool, so no new tablets are deleted after this point.
delete_tablet_pool_->Shutdown();
// Signal the only task running on the txn_status_manager_pool_ to wrap up.
shutdown_latch_.CountDown();
// Shut down the pool running the dedicated TxnStatusManager-related task.
txn_status_manager_pool_->Shutdown();
// Take a snapshot of the replicas list -- that way we don't have to hold
// on to the lock while shutting them down, which might cause a lock
// inversion. (see KUDU-308 for example).
vector<scoped_refptr<TabletReplica>> replicas_to_shutdown;
GetTabletReplicas(&replicas_to_shutdown);
for (const scoped_refptr<TabletReplica>& replica : replicas_to_shutdown) {
replica->Shutdown();
}
{
std::lock_guard<RWMutex> l(lock_);
// We don't expect anyone else to be modifying the map after we start the
// shut down process.
CHECK_EQ(tablet_map_.size(), replicas_to_shutdown.size())
<< "Map contents changed during shutdown!";
tablet_map_.clear();
state_ = MANAGER_SHUTDOWN;
}
}
void TSTabletManager::RegisterTablet(const string& tablet_id,
const scoped_refptr<TabletReplica>& replica,
RegisterTabletReplicaMode mode) {
std::lock_guard<RWMutex> lock(lock_);
// If we are replacing a tablet replica, we delete the existing one first.
if (mode == REPLACEMENT_REPLICA && tablet_map_.erase(tablet_id) != 1) {
LOG(FATAL) << "Unable to remove previous tablet replica " << tablet_id << ": not registered!";
}
if (!InsertIfNotPresent(&tablet_map_, tablet_id, replica)) {
LOG(FATAL) << "Unable to register tablet replica " << tablet_id << ": already registered!";
}
TabletDataState data_state = replica->tablet_metadata()->tablet_data_state();
VLOG(1) << LogPrefix(tablet_id) << Substitute("Registered tablet (data state: $0)",
TabletDataState_Name(data_state));
}
bool TSTabletManager::LookupTablet(const string& tablet_id,
scoped_refptr<TabletReplica>* replica) const {
shared_lock<RWMutex> l(lock_);
return LookupTabletUnlocked(tablet_id, replica);
}
bool TSTabletManager::LookupTabletUnlocked(const string& tablet_id,
scoped_refptr<TabletReplica>* replica) const {
const scoped_refptr<TabletReplica>* found = FindOrNull(tablet_map_, tablet_id);
if (!found) {
return false;
}
*replica = *found;
return true;
}
Status TSTabletManager::GetTabletReplica(const string& tablet_id,
scoped_refptr<tablet::TabletReplica>* replica) const {
if (!LookupTablet(tablet_id, replica)) {
return Status::NotFound("Tablet not found", tablet_id);
}
return Status::OK();
}
const NodeInstancePB& TSTabletManager::NodeInstance() const {
return server_->instance_pb();
}
void TSTabletManager::GetTabletReplicas(vector<scoped_refptr<TabletReplica> >* replicas) const {
shared_lock<RWMutex> l(lock_);
AppendValuesFromMap(tablet_map_, replicas);
}
void TSTabletManager::MarkTabletDirty(const string& tablet_id, const string& reason) {
VLOG(2) << Substitute("$0 Marking dirty. Reason: $1. Will report this "
"tablet to the Master in the next heartbeat",
LogPrefix(tablet_id), reason);
MarkTabletsDirty({ tablet_id }, reason);
}
void TSTabletManager::MarkTabletsDirty(const vector<string>& tablet_ids, const string& reason) {
server_->heartbeater()->MarkTabletsDirty(tablet_ids, reason);
server_->heartbeater()->TriggerASAP();
}
int TSTabletManager::GetNumLiveTablets() const {
int count = 0;
shared_lock<RWMutex> l(lock_);
for (const auto& entry : tablet_map_) {
tablet::TabletStatePB state = entry.second->state();
if (state == tablet::BOOTSTRAPPING ||
state == tablet::RUNNING) {
count++;
}
}
return count;
}
TabletNumByDimensionMap TSTabletManager::GetNumLiveTabletsByDimension() const {
TabletNumByDimensionMap result;
shared_lock<RWMutex> l(lock_);
for (const auto& entry : tablet_map_) {
tablet::TabletStatePB state = entry.second->state();
if (state == tablet::BOOTSTRAPPING ||
state == tablet::RUNNING) {
boost::optional<string> dimension_label = entry.second->tablet_metadata()->dimension_label();
if (dimension_label) {
result[*dimension_label]++;
}
}
}
return result;
}
void TSTabletManager::InitLocalRaftPeerPB() {
DCHECK_EQ(state(), MANAGER_INITIALIZING);
local_peer_pb_.set_permanent_uuid(fs_manager_->uuid());
Sockaddr addr = server_->first_rpc_address();
HostPort hp;
CHECK_OK(HostPortFromSockaddrReplaceWildcard(addr, &hp));
*local_peer_pb_.mutable_last_known_addr() = HostPortToPB(hp);
}
void TSTabletManager::TxnStalenessTrackerTask() {
while (true) {
// This little dance below is to provide functionality of re-enabling the
// staleness tracking task at run-time without restarting the process.
auto interval_ms = FLAGS_txn_staleness_tracker_interval_ms;
bool task_enabled = true;
if (interval_ms == 0) {
// The task is disabled.
interval_ms = FLAGS_txn_staleness_tracker_disabled_interval_ms;
task_enabled = false;
}
// Wait for a notification on shutdown or a timeout expiration.
if (shutdown_latch_.WaitFor(MonoDelta::FromMilliseconds(interval_ms))) {
return;
}
if (!task_enabled) {
continue;
}
vector<scoped_refptr<TabletReplica>> replicas;
{
shared_lock<RWMutex> l(lock_);
for (const auto& elem : tablet_map_) {
auto r = elem.second;
// Find txn status tablet replicas.
if (r->txn_coordinator()) {
replicas.emplace_back(std::move(r));
}
}
}
for (auto& r : replicas) {
if (shutdown_latch_.count() == 0) {
return;
}
auto* coordinator = DCHECK_NOTNULL(r->txn_coordinator());
coordinator->AbortStaleTransactions();
}
}
}
void TSTabletManager::CreateReportedTabletPB(const scoped_refptr<TabletReplica>& replica,
ReportedTabletPB* reported_tablet) const {
reported_tablet->set_tablet_id(replica->tablet_id());
reported_tablet->set_state(replica->state());
reported_tablet->set_tablet_data_state(replica->tablet_metadata()->tablet_data_state());
const Status& error = replica->error();
if (!error.ok()) {
StatusToPB(error, reported_tablet->mutable_error());
}
reported_tablet->set_schema_version(replica->tablet_metadata()->schema_version());
// We cannot get consensus state information unless the TabletReplica is running.
shared_ptr<consensus::RaftConsensus> consensus = replica->shared_consensus();
if (!consensus) {
return;
}
auto include_health = FLAGS_raft_prepare_replacement_before_eviction ?
INCLUDE_HEALTH_REPORT : EXCLUDE_HEALTH_REPORT;
ConsensusStatePB cstate;
Status s = consensus->ConsensusState(&cstate, include_health);
if (PREDICT_TRUE(s.ok())) {
// If we're the leader, report stats.
if (cstate.leader_uuid() == fs_manager_->uuid()) {
ReportedTabletStatsPB stats_pb = replica->GetTabletStats();
*reported_tablet->mutable_stats() = std::move(stats_pb);
}
*reported_tablet->mutable_consensus_state() = std::move(cstate);
}
}
void TSTabletManager::PopulateFullTabletReport(TabletReportPB* report) const {
// Creating the tablet report can be slow in the case that it is in the
// middle of flushing its consensus metadata. We don't want to hold
// lock_ for too long, even in read mode, since it can cause other readers
// to block if there is a waiting writer (see KUDU-2193). So, we just make
// a local copy of the set of replicas.
vector<scoped_refptr<tablet::TabletReplica>> to_report;
GetTabletReplicas(&to_report);
for (const auto& replica : to_report) {
CreateReportedTabletPB(replica, report->add_updated_tablets());
}
}
void TSTabletManager::PopulateIncrementalTabletReport(TabletReportPB* report,
const vector<string>& tablet_ids) const {
// See comment in PopulateFullTabletReport for rationale on making a local
// copy of the set of tablets to report.
vector<scoped_refptr<tablet::TabletReplica>> to_report;
to_report.reserve(tablet_ids.size());
{
shared_lock<RWMutex> shared_lock(lock_);
for (const auto& id : tablet_ids) {
const scoped_refptr<tablet::TabletReplica>* replica =
FindOrNull(tablet_map_, id);
if (replica) {
// Dirty entry, report on it.
to_report.push_back(*replica);
} else {
// Removed.
report->add_removed_tablet_ids(id);
}
}
}
for (const auto& replica : to_report) {
CreateReportedTabletPB(replica, report->add_updated_tablets());
}
}
Status TSTabletManager::HandleNonReadyTabletOnStartup(const scoped_refptr<TabletMetadata>& meta) {
const string& tablet_id = meta->tablet_id();
TabletDataState data_state = meta->tablet_data_state();
CHECK(data_state == TABLET_DATA_DELETED ||
data_state == TABLET_DATA_TOMBSTONED ||
data_state == TABLET_DATA_COPYING)
<< "Unexpected TabletDataState in tablet " << tablet_id << ": "
<< TabletDataState_Name(data_state) << " (" << data_state << ")";
// If the tablet is already fully tombstoned with no remaining data or WAL,
// then no need to roll anything forward.
bool skip_deletion = meta->IsTombstonedWithNoBlocks() &&
!Log::HasOnDiskData(meta->fs_manager(), tablet_id);
LOG_IF(WARNING, !skip_deletion)
<< LogPrefix(tablet_id) << "Tablet Manager startup: Rolling forward tablet deletion "
<< "of type " << TabletDataState_Name(data_state);
if (data_state == TABLET_DATA_COPYING) {
// We tombstone tablets that failed to copy.
data_state = TABLET_DATA_TOMBSTONED;
}
if (data_state == TABLET_DATA_TOMBSTONED) {
// It is possible for tombstoned replicas to legitimately not have a cmeta
// file as a result of crashing during a first tablet copy, or failing a
// tablet copy operation in an older version of Kudu. Not having a cmeta
// file results in those tombstoned replicas being unable to vote in Raft
// leader elections. We remedy this by creating a cmeta object (with an
// empty config) at startup time. The empty config is safe for a tombstoned
// replica, because the config doesn't affect a replica's ability to vote
// in a leader election. Additionally, if the tombstoned replica were ever
// to be overwritten by a tablet copy operation, that would also result in
// overwriting the config stored in the local cmeta with a valid Raft
// config. Finally, all of this assumes that the nonexistence of a cmeta
// file guarantees that the replica has never voted in a leader election.
//
// As an optimization, the cmeta is created with the NO_FLUSH_ON_CREATE
// flag, meaning that it will only be flushed to disk if the replica ever
// votes.
RETURN_NOT_OK(cmeta_manager_->LoadOrCreate(tablet_id, RaftConfigPB(), kMinimumTerm,
ConsensusMetadataCreateMode::NO_FLUSH_ON_CREATE));
}
if (!skip_deletion) {
// Passing no OpId will retain the last_logged_opid that was previously in the metadata.
RETURN_NOT_OK(DeleteTabletData(meta, cmeta_manager_, data_state, boost::none));
}
// Register TOMBSTONED tablets so that they get reported to the Master, which
// allows us to permanently delete replica tombstones when a table gets
// deleted.
if (data_state == TABLET_DATA_TOMBSTONED) {
scoped_refptr<TabletReplica> dummy;
RETURN_NOT_OK(CreateAndRegisterTabletReplica(meta, NEW_REPLICA, &dummy));
dummy->SetStatusMessage("Tombstoned");
}
return Status::OK();
}
Status TSTabletManager::DeleteTabletData(
const scoped_refptr<TabletMetadata>& meta,
const scoped_refptr<consensus::ConsensusMetadataManager>& cmeta_manager,
TabletDataState delete_type,
boost::optional<OpId> last_logged_opid) {
const string& tablet_id = meta->tablet_id();
LOG(INFO) << LogPrefix(tablet_id, meta->fs_manager())
<< "Deleting tablet data with delete state "
<< TabletDataState_Name(delete_type);
CHECK(delete_type == TABLET_DATA_DELETED ||
delete_type == TABLET_DATA_TOMBSTONED ||
delete_type == TABLET_DATA_COPYING)
<< "Unexpected delete_type to delete tablet " << tablet_id << ": "
<< TabletDataState_Name(delete_type) << " (" << delete_type << ")";
// Note: Passing an unset 'last_logged_opid' will retain the last_logged_opid
// that was previously in the metadata.
RETURN_NOT_OK(meta->DeleteTabletData(delete_type, last_logged_opid));
last_logged_opid = meta->tombstone_last_logged_opid();
LOG(INFO) << LogPrefix(tablet_id, meta->fs_manager())
<< "tablet deleted with delete type "
<< TabletDataState_Name(delete_type) << ": "
<< "last-logged OpId "
<< (last_logged_opid ? OpIdToString(*last_logged_opid) : "unknown");
MAYBE_FAULT(FLAGS_fault_crash_after_blocks_deleted);
CHECK_OK(Log::DeleteOnDiskData(meta->fs_manager(), tablet_id));
CHECK_OK(Log::RemoveRecoveryDirIfExists(meta->fs_manager(), tablet_id));
MAYBE_FAULT(FLAGS_fault_crash_after_wal_deleted);
// We do not delete the superblock or the consensus metadata when tombstoning
// a tablet or marking it as entering the tablet copy process.
if (delete_type == TABLET_DATA_COPYING ||
delete_type == TABLET_DATA_TOMBSTONED) {
return Status::OK();
}
// Only TABLET_DATA_DELETED tablets get this far.
DCHECK_EQ(TABLET_DATA_DELETED, delete_type);
LOG(INFO) << LogPrefix(tablet_id, meta->fs_manager()) << "Deleting consensus metadata";
Status s = cmeta_manager->Delete(tablet_id);
// NotFound means we already deleted the cmeta in a previous attempt.
if (PREDICT_FALSE(!s.ok() && !s.IsNotFound())) {
if (s.IsDiskFailure()) {
LOG(FATAL) << LogPrefix(tablet_id, meta->fs_manager())
<< "consensus metadata is on a failed disk";
}
return s;
}
MAYBE_FAULT(FLAGS_fault_crash_after_cmeta_deleted);
s = meta->DeleteSuperBlock();
if (PREDICT_FALSE(!s.ok())) {
if (s.IsDiskFailure()) {
LOG(FATAL) << LogPrefix(tablet_id, meta->fs_manager())
<< "tablet metadata is on a failed disk";
}
return s;
}
return Status::OK();
}
void TSTabletManager::FailTabletsInDataDir(const string& uuid) {
DataDirManager* dd_manager = fs_manager_->dd_manager();
int uuid_idx;
CHECK(dd_manager->FindUuidIndexByUuid(uuid, &uuid_idx))
<< Substitute("No data directory found with UUID $0", uuid);
if (fs_manager_->dd_manager()->IsDirFailed(uuid_idx)) {
LOG(WARNING) << "Data directory is already marked failed.";
return;
}
// Fail the directory to prevent other tablets from being placed in it.
dd_manager->MarkDirFailed(uuid_idx);
set<string> tablets = dd_manager->FindTabletsByDirUuidIdx(uuid_idx);
LOG(INFO) << Substitute("Data dir $0 has $1 tablets", uuid, tablets.size());
for (const string& tablet_id : dd_manager->FindTabletsByDirUuidIdx(uuid_idx)) {
FailTabletAndScheduleShutdown(tablet_id);
}
}
void TSTabletManager::FailTabletAndScheduleShutdown(const string& tablet_id) {
LOG(INFO) << LogPrefix(tablet_id, fs_manager_) << "failing tablet";
scoped_refptr<TabletReplica> replica;
if (LookupTablet(tablet_id, &replica)) {
// Stop further IO to the replica and set an error in the replica.
// When the replica is shutdown, this will leave it in a FAILED state.
replica->MakeUnavailable(Status::IOError("failing tablet"));
// Submit a request to actually shut down the tablet asynchronously.
CHECK_OK(open_tablet_pool_->Submit([tablet_id, this]() {
scoped_refptr<TabletReplica> replica;
scoped_refptr<TransitionInProgressDeleter> deleter;
TabletServerErrorPB::Code error;
Status s;
// Transition tablet state to ensure nothing else (e.g. tablet copies,
// deletions, etc) happens concurrently.
while (true) {
s = BeginReplicaStateTransition(tablet_id, "failing tablet",
&replica, &deleter, &error);
if (!s.IsAlreadyPresent()) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(10));
}
// Success: we started the transition.
//
// Only proceed if there is no Tablet (e.g. a bootstrap terminated early
// due to error before creating the Tablet) or if the tablet has been
// stopped (e.g. due to the above call to MakeUnavailable).
auto tablet = replica->shared_tablet();
if (s.ok() && (!tablet || tablet->HasBeenStopped())) {
replica->Shutdown();
}
// Else: the tablet is healthy, or is already either not running or
// deleted (e.g. because another thread was able to successfully create a
// new replica).
}));
}
}
int TSTabletManager::RefreshTabletStateCacheAndReturnCount(tablet::TabletStatePB st) {
MonoDelta period = MonoDelta::FromMilliseconds(FLAGS_tablet_state_walk_min_period_ms);
std::lock_guard<RWMutex> lock(lock_);
if (last_walked_ + period < MonoTime::Now()) {
// Old cache: regenerate counts.
tablet_state_counts_.clear();
for (const auto& entry : tablet_map_) {
tablet_state_counts_[entry.second->state()]++;
}
last_walked_ = MonoTime::Now();
}
return FindWithDefault(tablet_state_counts_, st, 0);
}
Status TSTabletManager::WaitForNoTransitionsForTests(const MonoDelta& timeout) const {
const MonoTime start = MonoTime::Now();
while (MonoTime::Now() - start < timeout) {
{
shared_lock<RWMutex> lock(lock_);
if (transition_in_progress_.empty()) {
return Status::OK();
}
}
SleepFor(MonoDelta::FromMilliseconds(50));
}
return Status::TimedOut("transitions still in progress after waiting $0",
timeout.ToString());
}
void TSTabletManager::UpdateTabletStatsIfNecessary() {
// Only one thread is allowed to update at the same time.
std::unique_lock<rw_spinlock> try_lock(lock_update_, std::try_to_lock);
if (!try_lock.owns_lock()) {
return;
}
if (MonoTime::Now() < next_update_time_) {
return;
}
next_update_time_ = MonoTime::Now() +
MonoDelta::FromMilliseconds(FLAGS_update_tablet_stats_interval_ms);
try_lock.unlock();
// Update the tablet stats and collect the dirty tablets.
vector<string> dirty_tablets;
vector<scoped_refptr<TabletReplica>> replicas;
GetTabletReplicas(&replicas);
for (const auto& replica : replicas) {
replica->UpdateTabletStats(&dirty_tablets);
}
if (!dirty_tablets.empty()) {
MarkTabletsDirty(dirty_tablets, "The tablet statistics have been changed");
}
}
void TSTabletManager::SetNextUpdateTimeForTests() {
std::lock_guard<rw_spinlock> l(lock_update_);
next_update_time_ = MonoTime::Now();
}
TransitionInProgressDeleter::TransitionInProgressDeleter(
TransitionInProgressMap* map, RWMutex* lock, string entry)
: in_progress_(map), lock_(lock), entry_(std::move(entry)), is_destroyed_(false) {}
void TransitionInProgressDeleter::Destroy() {
CHECK(!is_destroyed_);
std::lock_guard<RWMutex> lock(*lock_);
CHECK(in_progress_->erase(entry_));
is_destroyed_ = true;
}
TransitionInProgressDeleter::~TransitionInProgressDeleter() {
if (!is_destroyed_) {
Destroy();
}
}
} // namespace tserver
} // namespace kudu
| 40.794387 | 100 | 0.677019 | [
"object",
"vector"
] |
f5049e48ae8f4c471b8cf8a8f4f3bc842362dec2 | 11,902 | cc | C++ | src/gn/function_rebase_path.cc | yue/gn | 9caff23f0143a8bb959293f36c1fffed2c8a44ca | [
"BSD-3-Clause"
] | 3 | 2017-09-28T12:23:10.000Z | 2019-11-25T05:41:42.000Z | src/gn/function_rebase_path.cc | yue/gn | 9caff23f0143a8bb959293f36c1fffed2c8a44ca | [
"BSD-3-Clause"
] | 1 | 2020-12-17T17:03:36.000Z | 2020-12-17T17:03:36.000Z | src/gn/function_rebase_path.cc | yue/gn | 9caff23f0143a8bb959293f36c1fffed2c8a44ca | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 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 <stddef.h>
#include "base/strings/string_util.h"
#include "gn/build_settings.h"
#include "gn/filesystem_utils.h"
#include "gn/functions.h"
#include "gn/parse_tree.h"
#include "gn/scope.h"
#include "gn/settings.h"
#include "gn/source_dir.h"
#include "gn/source_file.h"
#include "gn/value.h"
namespace functions {
namespace {
// We want the output to match the input in terms of ending in a slash or not.
// Through all the transformations, these can get added or removed in various
// cases.
void MakeSlashEndingMatchInput(const std::string& input, std::string* output) {
if (EndsWithSlash(input)) {
if (!EndsWithSlash(*output)) // Preserve same slash type as input.
output->push_back(input[input.size() - 1]);
} else {
if (EndsWithSlash(*output))
output->resize(output->size() - 1);
}
}
// Returns true if the given value looks like a directory, otherwise we'll
// assume it's a file.
bool ValueLooksLikeDir(const std::string& value) {
if (value.empty())
return true;
size_t value_size = value.size();
// Count the number of dots at the end of the string.
size_t num_dots = 0;
while (num_dots < value_size && value[value_size - num_dots - 1] == '.')
num_dots++;
if (num_dots == value.size())
return true; // String is all dots.
if (IsSlash(value[value_size - num_dots - 1]))
return true; // String is a [back]slash followed by 0 or more dots.
// Anything else.
return false;
}
Value ConvertOnePath(const Scope* scope,
const FunctionCallNode* function,
const Value& value,
const SourceDir& from_dir,
const SourceDir& to_dir,
bool convert_to_system_absolute,
Err* err) {
Value result; // Ensure return value optimization.
if (!value.VerifyTypeIs(Value::STRING, err))
return result;
const std::string& string_value = value.string_value();
bool looks_like_dir = ValueLooksLikeDir(string_value);
// Convert to abosulte if we are referencing files under chromium buildconfig.
bool is_chromium_build_config = false;
if (scope->settings()->build_settings()->use_chromium_config()) {
std::string rp = looks_like_dir ?
from_dir.ResolveRelativeDir(value, err,
scope->settings()->build_settings()->root_path_utf8()).value() :
from_dir.ResolveRelativeFile(value, err,
scope->settings()->build_settings()->root_path_utf8()).value();
is_chromium_build_config = scope->settings()->build_settings()->IsChromiumPath(rp);
}
// System-absolute output special case.
if (convert_to_system_absolute) {
base::FilePath system_path;
if (looks_like_dir) {
if (is_chromium_build_config) {
system_path = scope->settings()->build_settings()->GetFullPathChromium(
from_dir.ResolveRelativeDir(
value, err,
scope->settings()->build_settings()->root_path_utf8()));
} else {
system_path = scope->settings()->build_settings()->GetFullPath(
from_dir.ResolveRelativeDir(
value, err,
scope->settings()->build_settings()->root_path_utf8()));
}
} else {
if (is_chromium_build_config) {
system_path = scope->settings()->build_settings()->GetFullPathChromium(
from_dir.ResolveRelativeFile(
value, err,
scope->settings()->build_settings()->root_path_utf8()));
} else {
system_path = scope->settings()->build_settings()->GetFullPath(
from_dir.ResolveRelativeFile(
value, err,
scope->settings()->build_settings()->root_path_utf8()));
}
}
if (err->has_error())
return Value();
result = Value(function, FilePathToUTF8(system_path));
if (looks_like_dir)
MakeSlashEndingMatchInput(string_value, &result.string_value());
return result;
}
if (is_chromium_build_config && to_dir.value() == "//")
is_chromium_build_config = false;
result = Value(function, Value::STRING);
if (looks_like_dir) {
SourceDir resolved_dir = from_dir.ResolveRelativeDir(
value, err, scope->settings()->build_settings()->root_path_utf8());
if (err->has_error())
return Value();
if (is_chromium_build_config) {
resolved_dir = SourceDir(FilePathToUTF8(
scope->settings()->build_settings()->GetFullPathChromium(
resolved_dir)));
}
result.string_value() = RebasePath(
resolved_dir.value(),
to_dir, scope->settings()->build_settings()->root_path_utf8());
MakeSlashEndingMatchInput(string_value, &result.string_value());
} else {
SourceFile resolved_file = from_dir.ResolveRelativeFile(
value, err, scope->settings()->build_settings()->root_path_utf8());
if (err->has_error())
return Value();
if (is_chromium_build_config) {
resolved_file = SourceFile(FilePathToUTF8(
scope->settings()->build_settings()->GetFullPathChromium(
resolved_file)));
}
result.string_value() =
RebasePath(resolved_file.value(), to_dir,
scope->settings()->build_settings()->root_path_utf8());
}
return result;
}
} // namespace
const char kRebasePath[] = "rebase_path";
const char kRebasePath_HelpShort[] =
"rebase_path: Rebase a file or directory to another location.";
const char kRebasePath_Help[] =
R"(rebase_path: Rebase a file or directory to another location.
converted = rebase_path(input,
new_base = "",
current_base = ".")
Takes a string argument representing a file name, or a list of such strings
and converts it/them to be relative to a different base directory.
When invoking the compiler or scripts, GN will automatically convert sources
and include directories to be relative to the build directory. However, if
you're passing files directly in the "args" array or doing other manual
manipulations where GN doesn't know something is a file name, you will need
to convert paths to be relative to what your tool is expecting.
The common case is to use this to convert paths relative to the current
directory to be relative to the build directory (which will be the current
directory when executing scripts).
If you want to convert a file path to be source-absolute (that is, beginning
with a double slash like "//foo/bar"), you should use the get_path_info()
function. This function won't work because it will always make relative
paths, and it needs to support making paths relative to the source root, so
it can't also generate source-absolute paths without more special-cases.
Arguments
input
A string or list of strings representing file or directory names. These
can be relative paths ("foo/bar.txt"), system absolute paths
("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt").
new_base
The directory to convert the paths to be relative to. This can be an
absolute path or a relative path (which will be treated as being relative
to the current BUILD-file's directory).
As a special case, if new_base is the empty string (the default), all
paths will be converted to system-absolute native style paths with system
path separators. This is useful for invoking external programs.
current_base
Directory representing the base for relative paths in the input. If this
is not an absolute path, it will be treated as being relative to the
current build file. Use "." (the default) to convert paths from the
current BUILD-file's directory.
Return value
The return value will be the same type as the input value (either a string or
a list of strings). All relative and source-absolute file names will be
converted to be relative to the requested output System-absolute paths will
be unchanged.
Whether an output path will end in a slash will match whether the
corresponding input path ends in a slash. It will return "." or "./"
(depending on whether the input ends in a slash) to avoid returning empty
strings. This means if you want a root path ("//" or "/") not ending in a
slash, you can add a dot ("//.").
Example
# Convert a file in the current directory to be relative to the build
# directory (the current dir when executing compilers and scripts).
foo = rebase_path("myfile.txt", root_build_dir)
# might produce "../../project/myfile.txt".
# Convert a file to be system absolute:
foo = rebase_path("myfile.txt")
# Might produce "D:\\source\\project\\myfile.txt" on Windows or
# "/home/you/source/project/myfile.txt" on Linux.
# Typical usage for converting to the build directory for a script.
action("myscript") {
# Don't convert sources, GN will automatically convert these to be relative
# to the build directory when it constructs the command line for your
# script.
sources = [ "foo.txt", "bar.txt" ]
# Extra file args passed manually need to be explicitly converted
# to be relative to the build directory:
args = [
"--data",
rebase_path("//mything/data/input.dat", root_build_dir),
"--rel",
rebase_path("relative_path.txt", root_build_dir)
] + rebase_path(sources, root_build_dir)
}
)";
Value RunRebasePath(Scope* scope,
const FunctionCallNode* function,
const std::vector<Value>& args,
Err* err) {
Value result;
// Argument indices.
static const size_t kArgIndexInputs = 0;
static const size_t kArgIndexDest = 1;
static const size_t kArgIndexFrom = 2;
// Inputs.
if (args.size() < 1 || args.size() > 3) {
*err = Err(function->function(), "Wrong # of arguments for rebase_path.");
return result;
}
const Value& inputs = args[kArgIndexInputs];
// To path.
bool convert_to_system_absolute = true;
SourceDir to_dir;
const SourceDir& current_dir = scope->GetSourceDir();
if (args.size() > kArgIndexDest) {
if (!args[kArgIndexDest].VerifyTypeIs(Value::STRING, err))
return result;
if (!args[kArgIndexDest].string_value().empty()) {
to_dir = current_dir.ResolveRelativeDir(
args[kArgIndexDest], err,
scope->settings()->build_settings()->root_path_utf8());
if (err->has_error())
return Value();
convert_to_system_absolute = false;
}
}
// From path.
SourceDir from_dir;
if (args.size() > kArgIndexFrom) {
if (!args[kArgIndexFrom].VerifyTypeIs(Value::STRING, err))
return result;
from_dir = current_dir.ResolveRelativeDir(
args[kArgIndexFrom], err,
scope->settings()->build_settings()->root_path_utf8());
if (err->has_error())
return Value();
} else {
// Default to current directory if unspecified.
from_dir = current_dir;
}
// Path conversion.
if (inputs.type() == Value::STRING) {
return ConvertOnePath(scope, function, inputs, from_dir, to_dir,
convert_to_system_absolute, err);
} else if (inputs.type() == Value::LIST) {
result = Value(function, Value::LIST);
result.list_value().reserve(inputs.list_value().size());
for (const auto& input : inputs.list_value()) {
result.list_value().push_back(
ConvertOnePath(scope, function, input, from_dir, to_dir,
convert_to_system_absolute, err));
if (err->has_error()) {
result = Value();
return result;
}
}
return result;
}
*err = Err(function->function(), "rebase_path requires a list or a string.");
return result;
}
} // namespace functions
| 36.286585 | 87 | 0.667787 | [
"vector"
] |
f509bd97e6c6c27b818222bd587f5ae43e6ed58c | 4,534 | hpp | C++ | lion/math/solve_nonlinear_system.hpp | juanmanzanero/lion-cpp | 3485b2d42dd9c3dd81d364ac0ee2bc968802db2d | [
"MIT"
] | 1 | 2021-10-17T14:52:25.000Z | 2021-10-17T14:52:25.000Z | lion/math/solve_nonlinear_system.hpp | juanmanzanero/lion-cpp | 3485b2d42dd9c3dd81d364ac0ee2bc968802db2d | [
"MIT"
] | null | null | null | lion/math/solve_nonlinear_system.hpp | juanmanzanero/lion-cpp | 3485b2d42dd9c3dd81d364ac0ee2bc968802db2d | [
"MIT"
] | 1 | 2022-01-05T16:45:26.000Z | 2022-01-05T16:45:26.000Z | #ifndef __SOLVE_NONLINEAR_SYSTEM_HPP__
#define __SOLVE_NONLINEAR_SYSTEM_HPP__
#include "ipopt_handler.h"
#include "lion/thirdparty/include/coin-or/IpSolveStatistics.hpp"
#include "lion/math/matrix_extensions.h"
#include <math.h>
#include "lion/thirdparty/include/logger.hpp"
template<typename C>
inline typename Solve_nonlinear_system<C>::Nonlinear_system_solution Solve_nonlinear_system<C>::solve(const size_t n, const size_t nc,
const std::vector<scalar>& x0, C& c,
const std::vector<scalar>& x_lb, const std::vector<scalar>& x_ub, const std::vector<scalar>& c_lb,
const std::vector<scalar>& c_ub, const Solve_nonlinear_system_options& options)
{
assert(x0.size() == n);
assert(x_lb.size() == n);
assert(x_ub.size() == n);
assert(c_lb.size() == nc);
assert(c_ub.size() == nc);
Fitness_function f;
Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();
Ipopt::ApplicationReturnStatus status = app->Initialize();
if ( status != Ipopt::Solve_Succeeded )
throw std::runtime_error("Ipopt: error during initialization");
// Configure options
app->Options()->SetStringValue ("hessian_approximation", options.hessian_approximation);
app->Options()->SetIntegerValue("print_level" , options.print_level);
app->Options()->SetStringValue ("mu_strategy" , options.mu_strategy);
app->Options()->SetStringValue ("nlp_scaling_method" , options.nlp_scaling_method);
app->Options()->SetNumericValue("constr_viol_tol" , options.constr_viol_tol);
app->Options()->SetNumericValue("acceptable_tol" , options.acceptable_tol);
app->Options()->SetNumericValue("tol" , options.tol);
app->Options()->SetStringValue ("derivative_test" ,options.derivative_test);
app->Options()->SetStringValue ("jacobian_approximation" ,options.jacobian_approximation);
app->Options()->SetNumericValue("findiff_perturbation" ,options.findiff_perturbation);
Ipopt::SmartPtr<Ipopt::TNLP> nlp = new Ipopt_handler<Fitness_function,C>(n, nc, x0, f, c, x_lb, x_ub, c_lb, c_ub);
status = app->OptimizeTNLP(nlp);
Ipopt::Number dual_inf, constr_viol, complementarity, kkt_error, varbounds_viol;
app->Statistics()->Infeasibilities(dual_inf, constr_viol, varbounds_viol, complementarity, kkt_error);
// Get solution
const std::vector<scalar>& x = static_cast<Ipopt_handler<Fitness_function,C>*>(GetRawPtr(nlp))->x();
// Regardless of the ipopt output flag we base the status flag on the constraints violation
bool succeed = true;
std::ostringstream sOut; // Aux buffer to print the errors
// Check that all variables are within bounds
for (size_t i = 0; i < n; ++i)
{
if ( x[i] < (x_lb[i] - 10.0*options.constr_viol_tol) )
{
sOut << "lower bound not satisfied for variable " << i << std::endl;
succeed = false;
}
if ( x[i] > (x_ub[i] + 10.0*options.constr_viol_tol) )
{
sOut << "upper bound not satisfied for variable " << i << std::endl;
succeed = false;
}
}
// Check that constraints are satisfied
typename C::argument_type x_c;
if constexpr (std::is_same<typename C::argument_type, std::vector<double>>::value)
x_c = std::vector<double>(n);
for (size_t i = 0; i < n; ++i)
x_c[i] = x[i];
auto constraints = c(x_c);
for (size_t i = 0; i < nc; ++i)
{
if ( constraints[i] < (c_lb[i] - 10.0*options.constr_viol_tol) )
{
sOut << "lower bound not satisfied for constraint " << i << std::endl;
succeed = false;
}
if ( constraints[i] > (c_ub[i] + 10.0*options.constr_viol_tol) )
{
sOut << "lower bound not satisfied for constraint " << i << std::endl;
succeed = false;
}
}
if ( !succeed )
{
sOut << std::setprecision(16);
for (size_t i = 0; i < n; ++i)
{
sOut << x_lb[i] << " < x[" << i << "]: " << x[i] << " < " << x_ub[i] << std::endl;
}
for (size_t i = 0; i < nc; ++i)
{
sOut << c_lb[i] << " < c[" << i << "]: " << constraints[i] << " < " << c_ub[i] << std::endl;
}
if ( options.throw_if_fail )
{
out(2) << sOut.str();
throw std::runtime_error("Nonlinear system solution not found");
}
}
return
{
succeed,
x
};
}
#endif
| 36.861789 | 134 | 0.609616 | [
"vector"
] |
f50a09047ba63e79239bbf2c5f0790f8bf91a83c | 23,238 | cc | C++ | src/mips/macro-assembler-mips.cc | dachev/v8 | 8f8d0603bdf51464aef6c7c345491ed918cd4874 | [
"BSD-3-Clause-Clear"
] | 3 | 2015-12-26T17:15:40.000Z | 2019-06-26T02:28:49.000Z | src/mips/macro-assembler-mips.cc | dachev/v8 | 8f8d0603bdf51464aef6c7c345491ed918cd4874 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/mips/macro-assembler-mips.cc | dachev/v8 | 8f8d0603bdf51464aef6c7c345491ed918cd4874 | [
"BSD-3-Clause-Clear"
] | null | null | null | // Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "bootstrapper.h"
#include "codegen-inl.h"
#include "debug.h"
#include "runtime.h"
namespace v8 {
namespace internal {
MacroAssembler::MacroAssembler(void* buffer, int size)
: Assembler(buffer, size),
unresolved_(0),
generating_stub_(false),
allow_stub_calls_(true),
code_object_(Heap::undefined_value()) {
}
void MacroAssembler::Jump(Register target, Condition cond,
Register r1, const Operand& r2) {
Jump(Operand(target), cond, r1, r2);
}
void MacroAssembler::Jump(intptr_t target, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
Jump(Operand(target), cond, r1, r2);
}
void MacroAssembler::Jump(byte* target, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
ASSERT(!RelocInfo::IsCodeTarget(rmode));
Jump(reinterpret_cast<intptr_t>(target), rmode, cond, r1, r2);
}
void MacroAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
ASSERT(RelocInfo::IsCodeTarget(rmode));
Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond);
}
void MacroAssembler::Call(Register target,
Condition cond, Register r1, const Operand& r2) {
Call(Operand(target), cond, r1, r2);
}
void MacroAssembler::Call(intptr_t target, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
Call(Operand(target), cond, r1, r2);
}
void MacroAssembler::Call(byte* target, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
ASSERT(!RelocInfo::IsCodeTarget(rmode));
Call(reinterpret_cast<intptr_t>(target), rmode, cond, r1, r2);
}
void MacroAssembler::Call(Handle<Code> code, RelocInfo::Mode rmode,
Condition cond, Register r1, const Operand& r2) {
ASSERT(RelocInfo::IsCodeTarget(rmode));
Call(reinterpret_cast<intptr_t>(code.location()), rmode, cond, r1, r2);
}
void MacroAssembler::Ret(Condition cond, Register r1, const Operand& r2) {
Jump(Operand(ra), cond, r1, r2);
}
void MacroAssembler::LoadRoot(Register destination,
Heap::RootListIndex index) {
lw(destination, MemOperand(s4, index << kPointerSizeLog2));
}
void MacroAssembler::LoadRoot(Register destination,
Heap::RootListIndex index,
Condition cond,
Register src1, const Operand& src2) {
Branch(NegateCondition(cond), 2, src1, src2);
nop();
lw(destination, MemOperand(s4, index << kPointerSizeLog2));
}
void MacroAssembler::RecordWrite(Register object, Register offset,
Register scratch) {
UNIMPLEMENTED_MIPS();
}
// ---------------------------------------------------------------------------
// Instruction macros
void MacroAssembler::Add(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
add(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
addi(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
add(rd, rs, at);
}
}
}
void MacroAssembler::Addu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
addu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
addiu(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
addu(rd, rs, at);
}
}
}
void MacroAssembler::Mul(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
mul(rd, rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
mul(rd, rs, at);
}
}
void MacroAssembler::Mult(Register rs, const Operand& rt) {
if (rt.is_reg()) {
mult(rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
mult(rs, at);
}
}
void MacroAssembler::Multu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
multu(rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
multu(rs, at);
}
}
void MacroAssembler::Div(Register rs, const Operand& rt) {
if (rt.is_reg()) {
div(rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
div(rs, at);
}
}
void MacroAssembler::Divu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
divu(rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
divu(rs, at);
}
}
void MacroAssembler::And(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
and_(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
andi(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
and_(rd, rs, at);
}
}
}
void MacroAssembler::Or(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
or_(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
ori(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
or_(rd, rs, at);
}
}
}
void MacroAssembler::Xor(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
xor_(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
xori(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
xor_(rd, rs, at);
}
}
}
void MacroAssembler::Nor(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
nor(rd, rs, rt.rm());
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
nor(rd, rs, at);
}
}
void MacroAssembler::Slt(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
slt(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
slti(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
slt(rd, rs, at);
}
}
}
void MacroAssembler::Sltu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
sltu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm32_) && !MustUseAt(rt.rmode_)) {
sltiu(rd, rs, rt.imm32_);
} else {
// li handles the relocation.
ASSERT(!rs.is(at));
li(at, rt);
sltu(rd, rs, at);
}
}
}
//------------Pseudo-instructions-------------
void MacroAssembler::movn(Register rd, Register rt) {
addiu(at, zero_reg, -1); // Fill at with ones.
xor_(rd, rt, at);
}
// load wartd in a register
void MacroAssembler::li(Register rd, Operand j, bool gen2instr) {
ASSERT(!j.is_reg());
if (!MustUseAt(j.rmode_) && !gen2instr) {
// Normal load of an immediate value which does not need Relocation Info.
if (is_int16(j.imm32_)) {
addiu(rd, zero_reg, j.imm32_);
} else if (!(j.imm32_ & HIMask)) {
ori(rd, zero_reg, j.imm32_);
} else if (!(j.imm32_ & LOMask)) {
lui(rd, (HIMask & j.imm32_) >> 16);
} else {
lui(rd, (HIMask & j.imm32_) >> 16);
ori(rd, rd, (LOMask & j.imm32_));
}
} else if (MustUseAt(j.rmode_) || gen2instr) {
if (MustUseAt(j.rmode_)) {
RecordRelocInfo(j.rmode_, j.imm32_);
}
// We need always the same number of instructions as we may need to patch
// this code to load another value which may need 2 instructions to load.
if (is_int16(j.imm32_)) {
nop();
addiu(rd, zero_reg, j.imm32_);
} else if (!(j.imm32_ & HIMask)) {
nop();
ori(rd, zero_reg, j.imm32_);
} else if (!(j.imm32_ & LOMask)) {
nop();
lui(rd, (HIMask & j.imm32_) >> 16);
} else {
lui(rd, (HIMask & j.imm32_) >> 16);
ori(rd, rd, (LOMask & j.imm32_));
}
}
}
// Exception-generating instructions and debugging support
void MacroAssembler::stop(const char* msg) {
// TO_UPGRADE: Just a break for now. Maybe we could upgrade it.
// We use the 0x54321 value to be able to find it easily when reading memory.
break_(0x54321);
}
void MacroAssembler::MultiPush(RegList regs) {
int16_t NumSaved = 0;
int16_t NumToPush = NumberOfBitsSet(regs);
addiu(sp, sp, -4 * NumToPush);
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
sw(ToRegister(i), MemOperand(sp, 4 * (NumToPush - ++NumSaved)));
}
}
}
void MacroAssembler::MultiPushReversed(RegList regs) {
int16_t NumSaved = 0;
int16_t NumToPush = NumberOfBitsSet(regs);
addiu(sp, sp, -4 * NumToPush);
for (int16_t i = kNumRegisters; i > 0; i--) {
if ((regs & (1 << i)) != 0) {
sw(ToRegister(i), MemOperand(sp, 4 * (NumToPush - ++NumSaved)));
}
}
}
void MacroAssembler::MultiPop(RegList regs) {
int16_t NumSaved = 0;
for (int16_t i = kNumRegisters; i > 0; i--) {
if ((regs & (1 << i)) != 0) {
lw(ToRegister(i), MemOperand(sp, 4 * (NumSaved++)));
}
}
addiu(sp, sp, 4 * NumSaved);
}
void MacroAssembler::MultiPopReversed(RegList regs) {
int16_t NumSaved = 0;
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
lw(ToRegister(i), MemOperand(sp, 4 * (NumSaved++)));
}
}
addiu(sp, sp, 4 * NumSaved);
}
// Emulated condtional branches do not emit a nop in the branch delay slot.
// Trashes the at register if no scratch register is provided.
void MacroAssembler::Branch(Condition cond, int16_t offset, Register rs,
const Operand& rt, Register scratch) {
Register r2;
if (rt.is_reg()) {
// We don't want any other register but scratch clobbered.
ASSERT(!scratch.is(rs) && !scratch.is(rt.rm_));
r2 = rt.rm_;
} else if (cond != cc_always) {
// We don't want any other register but scratch clobbered.
ASSERT(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
}
switch (cond) {
case cc_always:
b(offset);
break;
case eq:
beq(rs, r2, offset);
break;
case ne:
bne(rs, r2, offset);
break;
// Signed comparison
case greater:
slt(scratch, r2, rs);
bne(scratch, zero_reg, offset);
break;
case greater_equal:
slt(scratch, rs, r2);
beq(scratch, zero_reg, offset);
break;
case less:
slt(scratch, rs, r2);
bne(scratch, zero_reg, offset);
break;
case less_equal:
slt(scratch, r2, rs);
beq(scratch, zero_reg, offset);
break;
// Unsigned comparison.
case Ugreater:
sltu(scratch, r2, rs);
bne(scratch, zero_reg, offset);
break;
case Ugreater_equal:
sltu(scratch, rs, r2);
beq(scratch, zero_reg, offset);
break;
case Uless:
sltu(scratch, rs, r2);
bne(scratch, zero_reg, offset);
break;
case Uless_equal:
sltu(scratch, r2, rs);
beq(scratch, zero_reg, offset);
break;
default:
UNREACHABLE();
}
}
void MacroAssembler::Branch(Condition cond, Label* L, Register rs,
const Operand& rt, Register scratch) {
Register r2;
if (rt.is_reg()) {
r2 = rt.rm_;
} else if (cond != cc_always) {
r2 = scratch;
li(r2, rt);
}
// We use branch_offset as an argument for the branch instructions to be sure
// it is called just before generating the branch instruction, as needed.
switch (cond) {
case cc_always:
b(shifted_branch_offset(L, false));
break;
case eq:
beq(rs, r2, shifted_branch_offset(L, false));
break;
case ne:
bne(rs, r2, shifted_branch_offset(L, false));
break;
// Signed comparison
case greater:
slt(scratch, r2, rs);
bne(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case greater_equal:
slt(scratch, rs, r2);
beq(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case less:
slt(scratch, rs, r2);
bne(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case less_equal:
slt(scratch, r2, rs);
beq(scratch, zero_reg, shifted_branch_offset(L, false));
break;
// Unsigned comparison.
case Ugreater:
sltu(scratch, r2, rs);
bne(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case Ugreater_equal:
sltu(scratch, rs, r2);
beq(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case Uless:
sltu(scratch, rs, r2);
bne(scratch, zero_reg, shifted_branch_offset(L, false));
break;
case Uless_equal:
sltu(scratch, r2, rs);
beq(scratch, zero_reg, shifted_branch_offset(L, false));
break;
default:
UNREACHABLE();
}
}
// Trashes the at register if no scratch register is provided.
// We need to use a bgezal or bltzal, but they can't be used directly with the
// slt instructions. We could use sub or add instead but we would miss overflow
// cases, so we keep slt and add an intermediate third instruction.
void MacroAssembler::BranchAndLink(Condition cond, int16_t offset, Register rs,
const Operand& rt, Register scratch) {
Register r2;
if (rt.is_reg()) {
r2 = rt.rm_;
} else if (cond != cc_always) {
r2 = scratch;
li(r2, rt);
}
switch (cond) {
case cc_always:
bal(offset);
break;
case eq:
bne(rs, r2, 2);
nop();
bal(offset);
break;
case ne:
beq(rs, r2, 2);
nop();
bal(offset);
break;
// Signed comparison
case greater:
slt(scratch, r2, rs);
addiu(scratch, scratch, -1);
bgezal(scratch, offset);
break;
case greater_equal:
slt(scratch, rs, r2);
addiu(scratch, scratch, -1);
bltzal(scratch, offset);
break;
case less:
slt(scratch, rs, r2);
addiu(scratch, scratch, -1);
bgezal(scratch, offset);
break;
case less_equal:
slt(scratch, r2, rs);
addiu(scratch, scratch, -1);
bltzal(scratch, offset);
break;
// Unsigned comparison.
case Ugreater:
sltu(scratch, r2, rs);
addiu(scratch, scratch, -1);
bgezal(scratch, offset);
break;
case Ugreater_equal:
sltu(scratch, rs, r2);
addiu(scratch, scratch, -1);
bltzal(scratch, offset);
break;
case Uless:
sltu(scratch, rs, r2);
addiu(scratch, scratch, -1);
bgezal(scratch, offset);
break;
case Uless_equal:
sltu(scratch, r2, rs);
addiu(scratch, scratch, -1);
bltzal(scratch, offset);
break;
default:
UNREACHABLE();
}
}
void MacroAssembler::BranchAndLink(Condition cond, Label* L, Register rs,
const Operand& rt, Register scratch) {
Register r2;
if (rt.is_reg()) {
r2 = rt.rm_;
} else if (cond != cc_always) {
r2 = scratch;
li(r2, rt);
}
switch (cond) {
case cc_always:
bal(shifted_branch_offset(L, false));
break;
case eq:
bne(rs, r2, 2);
nop();
bal(shifted_branch_offset(L, false));
break;
case ne:
beq(rs, r2, 2);
nop();
bal(shifted_branch_offset(L, false));
break;
// Signed comparison
case greater:
slt(scratch, r2, rs);
addiu(scratch, scratch, -1);
bgezal(scratch, shifted_branch_offset(L, false));
break;
case greater_equal:
slt(scratch, rs, r2);
addiu(scratch, scratch, -1);
bltzal(scratch, shifted_branch_offset(L, false));
break;
case less:
slt(scratch, rs, r2);
addiu(scratch, scratch, -1);
bgezal(scratch, shifted_branch_offset(L, false));
break;
case less_equal:
slt(scratch, r2, rs);
addiu(scratch, scratch, -1);
bltzal(scratch, shifted_branch_offset(L, false));
break;
// Unsigned comparison.
case Ugreater:
sltu(scratch, r2, rs);
addiu(scratch, scratch, -1);
bgezal(scratch, shifted_branch_offset(L, false));
break;
case Ugreater_equal:
sltu(scratch, rs, r2);
addiu(scratch, scratch, -1);
bltzal(scratch, shifted_branch_offset(L, false));
break;
case Uless:
sltu(scratch, rs, r2);
addiu(scratch, scratch, -1);
bgezal(scratch, shifted_branch_offset(L, false));
break;
case Uless_equal:
sltu(scratch, r2, rs);
addiu(scratch, scratch, -1);
bltzal(scratch, shifted_branch_offset(L, false));
break;
default:
UNREACHABLE();
}
}
void MacroAssembler::Jump(const Operand& target,
Condition cond, Register rs, const Operand& rt) {
if (target.is_reg()) {
if (cond == cc_always) {
jr(target.rm());
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
jr(target.rm());
}
} else { // !target.is_reg()
if (!MustUseAt(target.rmode_)) {
if (cond == cc_always) {
j(target.imm32_);
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
j(target.imm32_); // will generate only one instruction.
}
} else { // MustUseAt(target)
li(at, rt);
if (cond == cc_always) {
jr(at);
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
jr(at); // will generate only one instruction.
}
}
}
}
void MacroAssembler::Call(const Operand& target,
Condition cond, Register rs, const Operand& rt) {
if (target.is_reg()) {
if (cond == cc_always) {
jalr(target.rm());
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
jalr(target.rm());
}
} else { // !target.is_reg()
if (!MustUseAt(target.rmode_)) {
if (cond == cc_always) {
jal(target.imm32_);
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
jal(target.imm32_); // will generate only one instruction.
}
} else { // MustUseAt(target)
li(at, rt);
if (cond == cc_always) {
jalr(at);
} else {
Branch(NegateCondition(cond), 2, rs, rt);
nop();
jalr(at); // will generate only one instruction.
}
}
}
}
void MacroAssembler::StackLimitCheck(Label* on_stack_overflow) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::Drop(int count, Condition cond) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::Call(Label* target) {
UNIMPLEMENTED_MIPS();
}
// ---------------------------------------------------------------------------
// Exception handling
void MacroAssembler::PushTryHandler(CodeLocation try_location,
HandlerType type) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::PopTryHandler() {
UNIMPLEMENTED_MIPS();
}
// ---------------------------------------------------------------------------
// Activation frames
void MacroAssembler::CallStub(CodeStub* stub, Condition cond,
Register r1, const Operand& r2) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::StubReturn(int argc) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::CallRuntime(Runtime::Function* f, int num_arguments) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::CallRuntime(Runtime::FunctionId fid, int num_arguments) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
int num_arguments,
int result_size) {
TailCallExternalReference(ExternalReference(fid), num_arguments, result_size);
}
void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin) {
UNIMPLEMENTED_MIPS();
}
Handle<Code> MacroAssembler::ResolveBuiltin(Builtins::JavaScript id,
bool* resolved) {
UNIMPLEMENTED_MIPS();
return Handle<Code>(reinterpret_cast<Code*>(NULL)); // UNIMPLEMENTED RETURN
}
void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
InvokeJSFlags flags) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::SetCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::Assert(Condition cc, const char* msg,
Register rs, Operand rt) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::Check(Condition cc, const char* msg,
Register rs, Operand rt) {
UNIMPLEMENTED_MIPS();
}
void MacroAssembler::Abort(const char* msg) {
UNIMPLEMENTED_MIPS();
}
} } // namespace v8::internal
| 25.734219 | 80 | 0.593338 | [
"object"
] |
f50b22573b42bd2c2e0c0cc4f6047841620aac88 | 10,508 | cpp | C++ | src/gui_app/MainFrame.cpp | euklid/PangaeaTracking | cff35a6636301d94f69d19bddc312da5c3a2a2e5 | [
"MIT"
] | 70 | 2015-12-01T23:40:03.000Z | 2022-03-29T19:56:04.000Z | src/gui_app/MainFrame.cpp | euklid/PangaeaTracking | cff35a6636301d94f69d19bddc312da5c3a2a2e5 | [
"MIT"
] | 6 | 2015-11-19T06:52:05.000Z | 2018-10-23T15:09:01.000Z | src/gui_app/MainFrame.cpp | euklid/PangaeaTracking | cff35a6636301d94f69d19bddc312da5c3a2a2e5 | [
"MIT"
] | 26 | 2015-11-29T04:57:56.000Z | 2021-04-04T15:43:01.000Z | #include "gui_app/MainFrame.h"
#include "gui_app/controlPanel.h"
#include "gui_app/BasicGLPane.h"
#include "gui_app/ImagePanel.h"
#ifdef _MSC_VER
#include "third_party/msvc/Stopwatch.h"
#else
#include "third_party/Stopwatch.h"
#endif
BEGIN_EVENT_TABLE(MainFrame, wxFrame)
EVT_TIMER(ID_TIMER, MainFrame::OnTimer)
EVT_IDLE(MainFrame::OnIdle)
END_EVENT_TABLE()
// MainFrame::MainFrame(const wxString& title, int argc, wxChar* argv[])
//MainFrame::MainFrame(const wxString& title, int argc, char** argv)
MainFrame::MainFrame(const wxString& title, int argc, char* argv[])
:wxFrame(NULL, -1, title, wxPoint(0,0), wxSize(1000,1000)),
m_nTimer(this, ID_TIMER),
isTrackingFinished(true)
{
// read configuration file
ReadConfigurationFile(argc,argv);
// set up imagesourceEngine and tracking engine
SetupInputAndTracker();
wxGetApp().m_pMainFrame = this;
// splitter the Panel to controlPanel and rightPanel
wxSplitterWindow* splittermain = new wxSplitterWindow(this, wxID_ANY);
splittermain->SetSashGravity(0);
splittermain->SetMinimumPaneSize(210);
m_pControlPanel = new controlPanel(splittermain);
wxPanel* rightPanel = new wxPanel(splittermain);
splittermain->SplitVertically(m_pControlPanel, rightPanel);
splittermain->SetSashPosition(200);
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(splittermain, 1, wxEXPAND, 0);
this->SetSizer(sizer);
sizer->SetSizeHints(this);
// split the rightPanel to glPanel and imagePanel
wxSplitterWindow* splitterRenderImage = new wxSplitterWindow(rightPanel, wxID_ANY);
splitterRenderImage->SetSashGravity(0.5);
wxBoxSizer* rightSizer = new wxBoxSizer(wxVERTICAL);
rightSizer->Add(splitterRenderImage,1,wxEXPAND);
rightPanel->SetSizer(rightSizer);
wxPanel* glPanel = new wxPanel(splitterRenderImage);
wxPanel* imagePanel = new wxPanel(splitterRenderImage);
splitterRenderImage->SplitVertically(glPanel, imagePanel);
// do something on glPanel
int args[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, 0};
m_pGLPane = new BasicGLPane(glPanel, args);
m_pGLPane->setImageHeight(m_nHeight);
m_pGLPane->setImageWidth(m_nWidth);
m_pGLPane->setIntrinsicMatrix(KK);
m_pGLPane->setProjectionMatrix();
// update the opengl panel pointer in control panel
m_pControlPanel->m_pGLPane = m_pGLPane;
wxBoxSizer* glSizer = new wxBoxSizer(wxVERTICAL);
//wxBoxSizer* glSizer = new wxBoxSizer(wxHORIZONTAL);
glSizer->Add(m_pGLPane,1,wxEXPAND);
glPanel->SetSizer(glSizer);
// splitter the imagePanel vertically to inputImagePanel and overlayPanel
wxSplitterWindow* splitterImage = new wxSplitterWindow(imagePanel, wxID_ANY);
splitterImage->SetSashGravity(0.5);
wxPanel* inputImagePanel = new wxPanel(splitterImage);
wxPanel* overlayPanel = new wxPanel(splitterImage);
splitterImage->SplitHorizontally(inputImagePanel, overlayPanel);
// splitterImage->SplitVertically(inputImagePanel, overlayPanel);
// do something on imagePanel
// m_pOverlayPane = new wxPanel(inputImagePanel);
// m_pImagePane = new wxPanel(overlayPanel);
m_pImagePane = new wxImagePanel(inputImagePanel,m_pColorImageRGB,m_nWidth,m_nHeight, false);
m_pOverlayPane = new wxImagePanel(overlayPanel,m_pColorImageRGB,m_nWidth,m_nHeight, true);
m_pOverlayPane->setMainFrame(this);
m_pImagePane->setMainFrame(this);
m_pOverlayPane->setNumPnts(m_nWidth*m_nHeight*shapeLoadingSettings.shapeSamplingScale*
shapeLoadingSettings.shapeSamplingScale);
m_pImagePane->setNumPnts(m_nWidth*m_nHeight*shapeLoadingSettings.shapeSamplingScale*
shapeLoadingSettings.shapeSamplingScale);
// wxBoxSizer* imagePaneSizer = new wxBoxSizer(wxHORIZONTAL);
// wxBoxSizer* OverlayPaneSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* imagePaneSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer* OverlayPaneSizer = new wxBoxSizer(wxVERTICAL);
imagePaneSizer->Add(m_pImagePane,1,wxEXPAND,0);
OverlayPaneSizer->Add(m_pOverlayPane,1,wxEXPAND,0);
inputImagePanel->SetSizer(imagePaneSizer);
overlayPanel->SetSizer(OverlayPaneSizer);
// wxBoxSizer* imageSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* imageSizer = new wxBoxSizer(wxVERTICAL);
imageSizer->Add(splitterImage, 1, wxEXPAND);
imagePanel->SetSizer(imageSizer);
if(trackerSettings.showWindow)
{
this->SetAutoLayout(true);
this->Show(true);
this->Maximize(true);
}
else
{
// wxCommandEvent dummyEvent;
// m_pControlPanel->ProcessWholeSequence(dummyEvent);
cout << "not showing window " << endl;
while(m_nCurrentFrame <= m_NumTrackingFrames)
{
//m_nCurrentFrame++;
m_nCurrentFrame += m_nFrameStep;
ProcessOneFrame(m_nCurrentFrame);
}
}
}
MainFrame::~MainFrame()
{
if(m_nTimer.IsRunning())
m_nTimer.Stop();
if(threadTracking.get_id() != boost::thread::id())
threadTracking.join();
}
bool MainFrame::ProcessOneFrame(int nFrame)
{
// if(trackingType != DEFORMNRSFM && m_pControlPanel->m_nCurrentFrame == nFrame && m_nCurrentFrame == nFrame)
// return true;
isTrackingFinished = false;
cout << "processing frame: " << nFrame << endl;
// // read input
// TICK("getInput");
// if(!GetInput(nFrame))
// return false;
// TOCK("getInput");
// // do tracking
// TICK("tracking");
// if(!m_pTrackingEngine->trackFrame(nFrame, m_pColorImageRGB, &pOutputInfo))
// {
// cout << "tracking failed: " << endl;
// return false;
// }
// TOCK("tracking");
if(!MainEngine::ProcessOneFrame(nFrame))
return false;
// update imagePanel
TICK("update2DRendering");
m_pOverlayPane->updateImage(m_pColorImageRGB, m_nWidth, m_nHeight);
m_pImagePane->updateImage(m_pColorImageRGB, m_nWidth, m_nHeight);
TOCK("update2DRendering");
isTrackingFinished = true;
Stopwatch::getInstance().printAll();
return true;
}
void MainFrame::OnTimer(wxTimerEvent& event)
{
if(m_nCurrentFrame + m_nFrameStep <= m_NumTrackingFrames)
threadTracking = boost::thread(&MainFrame::ProcessNextFrame, this);
else
m_nTimer.Stop();
}
void MainFrame::OnIdle(wxIdleEvent& event)
{
// do nothing if we are loading sequencea
if(trackingType == DEFORMNRSFM || trackingType == MESHPYRAMID)
{
m_pControlPanel->m_nCurrentFrame = m_nCurrentFrame;
m_pControlPanel->Update(true);
// cout << "frame number " << m_pControlPanel->m_nCurrentFrame << endl;
}
m_pGLPane->Refresh();
}
void MainFrame::UpdateVisibilityMask(double toleranceRatio)
{
vector<bool> visibilityMask;
UpdateVisibilityMaskGL(outputInfo, visibilityMask, KK, outputInfo.camPose,
m_nWidth, m_nHeight, toleranceRatio);
}
void MainFrame::UpdateRenderingLevel(int nRenderLevel, bool renderType)
{
// update the rendering level
if(trackingType == DEFORMNRSFM || trackingType == MESHPYRAMID)
{
m_pTrackingEngine->updateRenderingLevel(&pOutputInfo, nRenderLevel, renderType);
}
}
void MainFrame::SaveImage()
{
cout<<"save image"<<endl;
static unsigned int image_index=0;
GLint l_ViewPort[4];
glGetIntegerv(GL_VIEWPORT, l_ViewPort);
for (int i = 0; i != 4; ++i)
l_ViewPort[i]-=l_ViewPort[i]%4;
int width= (l_ViewPort[2] - l_ViewPort[0]);
int height=(l_ViewPort[3] - l_ViewPort[1]);
cout<<"l_Viewport[0] is "<<l_ViewPort[0]<<endl;
cout<<"l_Viewport[1] is "<<l_ViewPort[1]<<endl;
cout<<"l_Viewport[2] is "<<l_ViewPort[2]<<endl;
cout<<"l_Viewport[3] is "<<l_ViewPort[3]<<endl;
glReadBuffer(GL_BACK);
glFinish();
glPixelStorei(GL_PACK_ALIGNMENT, 3);
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
unsigned char *glBitmapData = new unsigned char [3 * width * height];
unsigned char *glBitmapData_flip = new unsigned char [3 * width * height];
// glReadPixels((GLint)0, (GLint)0, (GLint)width, (GLint)height, GL_RGB, GL_BYTE, glBitmapData);
glReadPixels((GLint)0, (GLint)0, (GLint)width, (GLint)height, GL_RGB, GL_UNSIGNED_BYTE, glBitmapData);
for(int i=0;i<height;++i)
memcpy(&glBitmapData_flip[3*i*width],&glBitmapData[3*(height-i-1)*width],3*width);
//wxImage img (width, height, glBitmapData, true);
wxImage img (width, height, glBitmapData_flip, true);
cout<<"width is "<<width<<endl;
cout<<"height is "<<height<<endl;
wxInitAllImageHandlers();
//glReadPixels(l_ViewPort[0], l_ViewPort[1], l_ViewPort[2], l_ViewPort[3],
// GL_RGB,GL_UNSIGNED_BYTE,(GLvoid*)&(pixels[0]));
//wxImage img(width, height, &(pixels[0]),true);
//img.Mirror(false);
cout<<"outputed data"<<endl;
stringstream file;
file<<setfill('0');
// file<<path;
// file<<savefolder;
file<<"./";
file<<"Rendering";
file<<"/";
if(!bfs::exists(file.str().c_str()))
{
bfs::create_directory(file.str().c_str());
}
file<<"render"<<setw(4)<< m_nCurrentFrame <<".png";
//file<<"out"<<setw(3)<<image_index++<<".bmp";
cout<<"saving as "<<file.str()<<endl;
wxString mystring(file.str().c_str(),wxConvUTF8);
cout<<"made mystring"<<endl;
img.SaveFile(mystring,wxBITMAP_TYPE_PNG);
//img.SaveFile(mystring,wxBITMAP_TYPE_BMP);
cout<<"Saved"<<endl;
// // Second method:
delete [] glBitmapData;
delete [] glBitmapData_flip;
}
void MainFrame::SaveOverlay()
{
// save overlay image
// create a bitmap(the same size as image)
int width = m_nWidth;
int height = m_nHeight;
wxBitmap *overlay = new wxBitmap(width,height);
// Create a memory Device Context
wxMemoryDC memDC;
//Tell memDC to write on.
memDC.SelectObject( *overlay );
m_pOverlayPane->render(memDC);
memDC.SelectObject( wxNullBitmap );
stringstream file;
file<<setfill('0');
// file<<path;
// file<<savefolder;
file<<"./";
file<<"Overlay";
file<<"/";
if(!bfs::exists(file.str().c_str()))
{
bfs::create_directory(file.str().c_str());
}
file<<"overlay"<<setw(4)<< m_nCurrentFrame <<".png";
cout<<"saving as "<<file.str()<<endl;
wxString mystring(file.str().c_str(),wxConvUTF8);
overlay->SaveFile(mystring, wxBITMAP_TYPE_PNG, (wxPalette*)NULL );
delete overlay;
}
| 33.253165 | 113 | 0.688238 | [
"render",
"vector"
] |
f50bd8ae9e5721eae877c3ff8a213f6175b5c41e | 3,149 | cpp | C++ | openbr/plugins/imgproc/rndaffine.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 1,883 | 2015-01-04T07:04:24.000Z | 2022-03-30T13:33:37.000Z | openbr/plugins/imgproc/rndaffine.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 272 | 2015-01-02T09:53:20.000Z | 2022-03-29T08:04:33.000Z | openbr/plugins/imgproc/rndaffine.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 718 | 2015-01-02T18:51:07.000Z | 2022-03-29T08:10:53.000Z | #include <opencv2/imgproc/imgproc.hpp>
#include <openbr/plugins/openbr_internal.h>
#include <openbr/core/opencvutils.h>
using namespace cv;
namespace br
{
/*!
* \brief Perform a number of random transformations to the points in metadata as "Affine_0" and "Affine_1"
* \author Jordan Cheney \cite jcheney
* \br_property int numAffines The number of independent random transformations to perform. The result of each transform is stored as its own template in the output TemplateList
* \br_property float scaleFactor Controls the magnitude of the random changes to the affine points
* \br_property int maxAngle the maximum angle between the original line between the two affine points and the new line between the points.
*/
class RndAffineTransform : public UntrainableMetaTransform
{
Q_OBJECT
Q_PROPERTY(int numAffines READ get_numAffines WRITE set_numAffines RESET reset_numAffines STORED false)
Q_PROPERTY(float scaleFactor READ get_scaleFactor WRITE set_scaleFactor RESET reset_scaleFactor STORED false)
Q_PROPERTY(int maxAngle READ get_maxAngle WRITE set_maxAngle RESET reset_maxAngle STORED false)
BR_PROPERTY(int, numAffines, 0)
BR_PROPERTY(float, scaleFactor, 1.2)
BR_PROPERTY(int, maxAngle, 15)
void project(const Template &src, Template &dst) const
{
TemplateList temp;
project(TemplateList() << src, temp);
if (!temp.isEmpty()) dst = temp.first();
}
void project(const TemplateList &src, TemplateList &dst) const
{
foreach (const Template &t, src) {
QPointF affine_0 = t.file.get<QPointF>("Affine_0");
QPointF affine_1 = t.file.get<QPointF>("Affine_1");
if (affine_0 != QPoint(-1,-1) && affine_1 != QPoint(-1,-1)) {
// Append the original points
Template u = t;
u.file.setPoints(QList<QPointF>() << affine_0 << affine_1);
u.file.set("Affine_0", affine_0);
u.file.set("Affine_1", affine_1);
dst.append(u);
const double IPD = sqrt(pow(affine_0.x() - affine_1.x(), 2) + pow(affine_0.y() - affine_1.y(), 2));
if (IPD != 0) {
for (int i = 0; i < numAffines; i++) {
int angle = (rand() % (2*maxAngle)) - maxAngle;
int min = (int)(sqrt(1 / scaleFactor) * IPD);
int max = (int)(sqrt(scaleFactor) * IPD);
int dx = (rand() % (max - min)) + min;
int dy = (dx * sin(angle * CV_PI / 180))/2;
QPointF shiftedAffine_0 = QPointF(affine_1.x() - dx, affine_1.y() + dy);
Template u = t;
u.file.setPoints(QList<QPointF>() << shiftedAffine_0 << affine_1);
u.file.set("Affine_0", shiftedAffine_0);
u.file.set("Affine_1", affine_1);
dst.append(u);
}
}
}
}
}
};
BR_REGISTER(Transform, RndAffineTransform)
} // namespace br
#include "imgproc/rndaffine.moc"
| 40.371795 | 177 | 0.597968 | [
"transform"
] |
f51078386c0f6366142c304f1d11a1d7d87ee872 | 112,605 | cpp | C++ | third_party/mysql-connector-c++-1.1.4/test/test_common.cpp | cloudpbl-senrigan/combinator | 91a45ac5d471f4a7527375db29e06b0fda2eea0d | [
"MIT"
] | null | null | null | third_party/mysql-connector-c++-1.1.4/test/test_common.cpp | cloudpbl-senrigan/combinator | 91a45ac5d471f4a7527375db29e06b0fda2eea0d | [
"MIT"
] | null | null | null | third_party/mysql-connector-c++-1.1.4/test/test_common.cpp | cloudpbl-senrigan/combinator | 91a45ac5d471f4a7527375db29e06b0fda2eea0d | [
"MIT"
] | null | null | null | /*
Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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 <list>
#include <map>
#include <memory>
#include <iostream>
#include <sstream>
#include <string>
#ifndef _WIN32
#include <inttypes.h>
#endif
/*
__FUNCTION__/__func__ is not portable. We do not promise
that our example definition covers each and every compiler.
If not, it is up to you to find a different definition for
your setup.
*/
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2
# define CPPCONN_FUNC __FUNCTION__
# else
# define CPPCONN_FUNC "(function n/a)"
# endif
#elif defined(_MSC_VER)
# if _MSC_VER < 1300
# define CPPCONN_FUNC "(function n/a)"
# else
# define CPPCONN_FUNC __FUNCTION__
# endif
#elif (defined __func__)
# define CPPCONN_FUNC __func__
#else
# define CPPCONN_FUNC "(function n/a)"
#endif
#ifndef __LINE__
#define __LINE__ "(line number n/a)"
#endif
#define ensure(msg, stmt) do {++total_tests;if(!(stmt)){printf("\n# Error! line=%d: %s\n# ",__LINE__,msg);++total_errors;throw sql::SQLException("error");} else { printf(".");}} while (0)
#define ensure_equal(msg, op1, op2) do {++total_tests;if((op1)!=(op2)){printf("\n# Error! line=%d: %s\n# ",__LINE__,msg);++total_errors;throw sql::SQLException("error");} else { printf(".");}}while(0)
#define ensure_equal_int(msg, op1, op2) do {++total_tests;if((op1)!=(op2)){printf("\n# Error! line=%d: %s Op1=%d Op2=%d\n# ",__LINE__,msg,op1,op2);++total_errors;throw sql::SQLException("error");} else { printf(".");}}while(0)
#define ensure_equal_str(msg, op1, op2) do {++total_tests;if((op1)!=(op2)){printf("\n# Error! line=%d: %s Op1=%s Op2=%s\n# ",__LINE__,msg,op1.c_str(),op2.c_str());++total_errors;throw sql::SQLException("error");} else { printf(".");}}while(0)
#define ensure_equal_int64(msg, op1, op2) do {++total_tests;if((op1)!=(op2)){printf("\n# Error! line=%d: %s Op1=%lld Op2=%lld\n# ",__LINE__,msg,(long long)op1,(long long)op2);++total_errors;throw sql::SQLException("error");} else { printf(".");}}while(0)
#define ensure_equal_uint64(msg, op1, op2) do {++total_tests;if((op1)!=(op2)){printf("\n# Error! line=%d: %s Op1=%llu Op2=%llu\n# ",__LINE__,msg,(unsigned long long)op1,(unsigned long long)op2);++total_errors;throw sql::SQLException("error");} else { printf(".");}}while(0)
static int total_errors = 0;
static int total_tests = 0;
static int silent = 1;
#define USED_DATABASE "test"
#define ENTER_FUNCTION() if (!silent) printf("# >>>> %s\n# ", CPPCONN_FUNC);
#define LEAVE_FUNCTION() if (!silent) printf("# <<<< %s\n# ", CPPCONN_FUNC); else printf("\n# ");
#if defined(_WIN32) || defined(_WIN64)
#pragma warning(disable:4251)
#pragma warning(disable:4800)
#endif
#ifdef _WIN32
#include "my_global.h"
#endif
extern "C"
{
#include "mysql.h"
}
/* mysql.h introduces bool */
#undef bool
#if defined(_WIN32) || defined(_WIN64)
#pragma warning(disable:4251)
#endif
#include <stdio.h>
#ifndef L64
#ifdef _WIN32
#define L64(x) x##i64
#else
#define L64(x) x##LL
#endif
#endif
#ifndef UL64
#ifdef _WIN32
#define UL64(x) x##ui64
#else
#define UL64(x) x##ULL
#endif
#endif
/* {{{ */
static bool populate_blob_table(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
stmt->execute("USE " + database);
stmt->execute("DROP TABLE IF EXISTS test_blob");
if (true == stmt->execute("CREATE TABLE test_blob (a longblob) ENGINE=MYISAM")) {
return false;
}
return true;
}
/* }}} */
/* {{{ */
static bool populate_insert_data(sql::Statement * stmt)
{
return stmt->execute("INSERT INTO test_function (a,b,c,d,e) VALUES(1, 111, NULL, '222', 'xyz')");
}
/* }}} */
/* {{{ */
static bool populate_test_table(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
stmt->execute("USE " + database);
stmt->execute("DROP TABLE IF EXISTS test_function");
if (true == stmt->execute("CREATE TABLE test_function (a integer unsigned not null, b integer, c integer default null, d char(10), e varchar(10) character set utf8 collate utf8_bin) ENGINE=MYISAM")) {
return false;
}
if (true == populate_insert_data(stmt.get())) {
stmt->execute("DROP TABLE test_function");
return false;
}
return true;
}
/* }}} */
/* {{{ */
static bool populate_TX_insert_data(sql::Statement * stmt)
{
return stmt->execute("INSERT INTO test_function_tx (a,b,c,d,e) VALUES(1, 111, NULL, '222', 'xyz')");
}
/* }}} */
/* {{{ */
static bool populate_TX_test_table(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
stmt->execute("USE " + database);
stmt->execute("DROP TABLE IF EXISTS test_function_tx");
if (true == stmt->execute("CREATE TABLE test_function_tx(a integer unsigned not null, b integer, c integer default null, d char(10), e varchar(10) character set utf8 collate utf8_bin) engine = innodb")) {
return false;
}
if (true == populate_TX_insert_data(stmt.get())) {
stmt->execute("DROP TABLE test_function_tx");
return false;
}
stmt->getConnection()->commit();
return true;
}
/* }}} */
/* {{{ */
static bool populate_test_table_PS(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
stmt1->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("DROP TABLE IF EXISTS test_function"));
ensure("stmt2 is NULL", stmt2.get() != NULL);
stmt2->executeUpdate();
std::auto_ptr<sql::PreparedStatement> stmt3(conn->prepareStatement("CREATE TABLE test_function(a integer unsigned not null, b integer, c integer default null, d char(10), e varchar(10) character set utf8 collate utf8_bin)"));
ensure("stmt3 is NULL", stmt3.get() != NULL);
stmt3->executeUpdate();
std::auto_ptr<sql::PreparedStatement> stmt4(conn->prepareStatement("INSERT INTO test_function (a,b,c,d,e) VALUES(1, 111, NULL, '222', 'xyz')"));
ensure("stmt4 is NULL", stmt4.get() != NULL);
stmt4->executeUpdate();
return true;
}
/* }}} */
/* {{{ */
static bool populate_TX_test_table_PS(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt is NULL", stmt1.get() != NULL);
stmt1->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("DROP TABLE IF EXISTS test_function_tx"));
ensure("stmt2 is NULL", stmt2.get() != NULL);
stmt2->executeUpdate();
std::auto_ptr<sql::PreparedStatement> stmt3(conn->prepareStatement("CREATE TABLE test_function_tx(a integer unsigned not null, b integer, c integer default null, d char(10), e varchar(10) character set utf8 collate utf8_bin) engine = innodb"));
ensure("stmt3 is NULL", stmt3.get() != NULL);
stmt3->executeUpdate();
std::auto_ptr<sql::PreparedStatement> stmt4(conn->prepareStatement("INSERT INTO test_function_tx (a,b,c,d,e) VALUES(1, 111, NULL, '222', 'xyz')"));
ensure("stmt4 is NULL", stmt4.get() != NULL);
stmt4->executeUpdate();
return true;
}
/* }}} */
/* {{{ */
static bool populate_test_table_PS_integers(std::auto_ptr<sql::Connection> & conn, std::string database)
{
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
stmt1->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("DROP TABLE IF EXISTS test_function_int"));
ensure("stmt2 is NULL", stmt2.get() != NULL);
stmt2->executeUpdate();
std::auto_ptr<sql::PreparedStatement> stmt3(conn->prepareStatement("CREATE TABLE test_function_int(i integer, i_uns integer unsigned, b bigint, b_uns bigint unsigned)"));
ensure("stmt3 is NULL", stmt3.get() != NULL);
stmt3->executeUpdate();
return true;
}
/* }}} */
/* {{{ */
static void test_autocommit(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
conn->setAutoCommit(1);
ensure("AutoCommit", conn->getAutoCommit() == true);
conn->setAutoCommit(0);
ensure("AutoCommit", conn->getAutoCommit() == false);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_connection_0(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
char buff[64];
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT CONNECTION_ID()"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure("res1 is empty", rset1->next() != false);
ensure("connection is closed", !conn->isClosed());
sprintf(buff, "KILL %d", rset1->getInt(1));
try {
stmt1->execute(buff);
} catch (sql::SQLException &) {
/*
If this is mac, we will get an error.
MySQL on Mac closes the connection without sending response
*/
}
try {
std::auto_ptr<sql::ResultSet> rset2(stmt1->executeQuery("SELECT CONNECTION_ID()"));
ensure("no exception", false);
} catch (sql::SQLException &) {
ensure("Exception correctly thrown", true);
}
ensure("connection is still open", conn->isClosed() == true);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_connection_1(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure("connection is closed", !conn->isClosed());
conn->setAutoCommit(false);
ensure("Data not populated", true == populate_TX_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure("res1 is empty", rset1->next() != false);
int count_full_before = rset1->getInt(1);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
std::string savepointName("firstSavePoint");
std::auto_ptr<sql::Savepoint> savepoint(conn->setSavepoint(savepointName));
populate_TX_insert_data(stmt1.get());
std::auto_ptr<sql::ResultSet> rset2(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res2 is NULL", rset2.get() != NULL);
ensure_equal_int("res2 is empty", rset2->next(), true);
int count_full_after = rset2->getInt(1);
ensure_equal_int("res2 has more rows ", rset2->next(), false);
ensure_equal_int("wrong number of rows", count_full_after, (count_full_before * 2));
conn->rollback(savepoint.get());
std::auto_ptr<sql::ResultSet> rset3(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res3 is NULL", rset3.get() != NULL);
ensure_equal_int("res3 is empty", rset3->next(), true);
int count_full_after_rollback = rset3->getInt(1);
ensure_equal_int("res3 has more rows ", rset3->next(), false);
ensure_equal_int("wrong number of rows", count_full_after_rollback, count_full_before);
conn->releaseSavepoint(savepoint.get());
try {
/* The second call should throw an exception */
conn->releaseSavepoint(savepoint.get());
++total_errors;
} catch (sql::SQLException &) {}
/* Clean */
stmt1->execute("USE " + database);
stmt1->execute("DROP TABLE test_function_tx");
} catch (sql::MethodNotImplementedException &) {
printf("\n# SKIP: RELEASE SAVEPOINT not available in this MySQL version\n");
printf("# ");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_connection_2(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt1 is NULL", stmt.get() != NULL);
ensure("Wrong catalog", conn->getCatalog() == "def" || conn->getCatalog() == "");
stmt->execute("USE " + database);
std::string newCatalog(conn->getSchema());
ensure(std::string("Wrong catalog '" + newCatalog + "'/'" + database + "'").c_str(), newCatalog == std::string(database));
try {
conn->setCatalog(std::string("doesnt_actually_exist"));
// printf("\n# ERR: Accepting invalid catalog");
// ++total_errors;
} catch (sql::SQLException &) {}
conn->setSchema(std::string("information_schema"));
std::string newCatalog2(conn->getSchema());
ensure("Wrong catalog", newCatalog2 == std::string("information_schema"));
} catch (sql::SQLException &e) {
/* Error: 1049 SQLSTATE: 42000 (ER_BAD_DB_ERROR) - information_schema not available */
if (e.getErrorCode() != 1049) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_connection_3(std::auto_ptr<sql::Connection> & conn, std::string user)
{
ENTER_FUNCTION();
try {
sql::DatabaseMetaData * meta = conn->getMetaData();
ensure("getUserName() failed", user == meta->getUserName().substr(0, user.length()));
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_statement_0(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("AutoCommit", conn.get() == stmt->getConnection());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test simple update statement against statement object */
static void test_statement_1(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
if (false == stmt->execute("SELECT * FROM test_function"))
ensure("False returned for SELECT", false);
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test simple query against statement object */
static void test_statement_2(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
if (false == stmt->execute("SELECT * FROM test_function"))
ensure("False returned for SELECT", false);
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test executeQuery() - returning a result set*/
static void test_statement_3(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
/* Get a result set */
try {
std::auto_ptr<sql::ResultSet> rset(stmt->executeQuery("SELECT * FROM test_function"));
ensure("NULL returned for result set", rset.get() != NULL);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
++total_errors;
printf("# ");
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test executeQuery() - returning empty result set */
static void test_statement_4(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
/* Get a result set */
try {
std::auto_ptr<sql::ResultSet> rset(stmt->executeQuery("SELECT * FROM test_function WHERE 1=2"));
ensure("NULL returned for result set", rset.get() != NULL);
ensure_equal_int("Non-empty result set", false, rset->next());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test executeQuery() - use it for inserting, should generate an exception */
static void test_statement_5(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
/* Get a result set */
try {
std::auto_ptr<sql::ResultSet> rset(stmt->executeQuery("INSERT INTO test_function VALUES(2,200)"));
ensure("NULL returned for result set", rset.get() == NULL);
ensure_equal_int("Non-empty result set", false, rset->next());
} catch (sql::SQLException &) {
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test executeUpdate() - check the returned value */
static void test_statement_6(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
/* Get a result set */
try {
ensure("Number of updated rows", stmt->executeUpdate("UPDATE test_function SET a = 123") == 1);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
++total_errors;
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test executeUpdate() - execute a SELECT, should get an exception */
static void test_statement_7(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
/* Get a result set */
try {
stmt->executeUpdate("SELECT * FROM test_function");
ensure("No exception thrown", false);
} catch (sql::SQLException &) {
} catch (...) {
printf("\n# ERR: Incorrectly sql::SQLException ist not thrown\n");
printf("# ");
++total_errors;
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
#if 0
/* {{{ Test getFetchSize() - should return int value */
/* XXX: Test fails because getFetchSize() is not implemented*/
static void test_statement_xx(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("fetchSize is negative", stmt->getFetchSize() > 0);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test setFetchSize() - set and get the value */
/* XXX: Doesn't pass because setFetchSize() is unimplemented */
static void test_statement_xx(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
int setFetchSize = 50;
stmt->setFetchSize(setFetchSize);
ensure_equal("Non-equal", setFetchSize, stmt->getFetchSize());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
}
/* }}} */
/* {{{ Test setFetchSize() - set negative value and expect an exception */
/* XXX: Doesn't pass because setFetchSize() is unimplemented */
static void test_statement_xx(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
try {
stmt->setFetchSize(-1);
ensure("No exception", false);
} catch (sql::InvalidArgumentException) {
printf("INFO: Caught sql::InvalidArgumentException\n");
}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test setQueryTimeout() - set negative value and expect an exception */
/* XXX: Doesn't pass because setQueryTimeout() is unimplemented */
static void test_statement_xx(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
try {
stmt->setQueryTimeout(-1);
printf("\n# ERR:No exception\n");
} catch (sql::InvalidArgumentException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
#endif
/* {{{ Test getResultSet() - execute() a query and get the result set */
static void test_statement_8(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
ensure("sql::Statement::execute returned false", true == stmt->execute("SELECT * FROM test_function"));
std::auto_ptr<sql::ResultSet> rset(stmt->getResultSet());
ensure("rset is NULL", rset.get() != NULL);
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
}
/* }}} */
/* {{{ Test getResultSet() - execute() an update query and get the result set - should be empty */
static void test_statement_9(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
ensure("sql::Statement::execute returned true", false == stmt->execute("UPDATE test_function SET a = 222"));
std::auto_ptr<sql::ResultSet> rset(stmt->getResultSet());
ensure("rset is not NULL", rset.get() == NULL);
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test metadata usage after result set has been closed */
static void test_statement_10(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("stmt is NULL", stmt.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM test_function"));
ensure("ResultSet is empty", res->rowsCount() > 0);
sql::ResultSetMetaData * meta = res->getMetaData();
ensure("Error while reading a row ", res->next());
ensure_equal_str("Table name differs", meta->getTableName(1), std::string("test_function"));
res->close();
try {
ensure_equal_str("Table name differs", meta->getTableName(1), std::string("test_function"));
ensure("Exception not correctly thrown", false);
} catch (sql::SQLException &/*e*/) {
// exception correctly thrown
}
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
stmt2->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_result_set_0(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
ensure("AutoCommit", conn.get() == stmt->getConnection());
std::auto_ptr<sql::ResultSet> result(stmt->setResultSetType(sql::ResultSet::TYPE_SCROLL_INSENSITIVE)->executeQuery("SELECT 1, 2, 3"));
ensure_equal_int("isFirst", result->isFirst(), false);
ensure_equal_int("isLast", result->isLast(), false);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_result_set_1(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
stmt1->setResultSetType(sql::ResultSet::TYPE_SCROLL_INSENSITIVE);
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT 1"));
ensure("res1 is NULL", rset1.get() != NULL);
std::auto_ptr<sql::ResultSet> rset2(stmt1->executeQuery("SELECT 1"));
ensure("res2 is NULL", rset2.get() != NULL);
ensure("res1 is empty", rset1->next() != false);
ensure("res2 is empty", rset2->next() != false);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_result_set_2(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure("Data not populated", true == populate_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT 1"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure_equal_int("res1 is empty", rset1->next(), true);
ensure_equal_int("res1 is empty", rset1->next(), false);
ensure("No rows updated", stmt1->executeUpdate("UPDATE test_function SET a = 2") > 0);
stmt1->execute("DROP TABLE test_function");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
static void test_result_set_3(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure_equal("sql::Connection differs", conn.get(), stmt1->getConnection());
int old_commit_mode = conn->getAutoCommit();
conn->setAutoCommit(0);
ensure("Data not populated", true == populate_TX_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure("res1 is empty", rset1->next() != false);
int count_full_before = rset1->getInt(1);
ensure("res1 has more rows ", rset1->next() == false);
/* Let's delete and then rollback */
ensure_equal("Deleted less rows",
stmt1->executeUpdate("DELETE FROM test_function_tx WHERE 1"),
count_full_before);
std::auto_ptr<sql::ResultSet> rset2(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res2 is NULL", rset2.get() != NULL);
ensure("res2 is empty", rset2->next() != false);
ensure("Table not empty after delete", rset2->getInt(1) == 0);
ensure("res2 has more rows ", rset2->next() == false);
stmt1->getConnection()->rollback();
std::auto_ptr<sql::ResultSet> rset3(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res3 is NULL", rset3.get() != NULL);
ensure("res3 is empty", rset3->next() != false);
int count_full_after = rset3->getInt(1);
ensure("res3 has more rows ", rset3->next() == false);
ensure("Rollback didn't work", count_full_before == count_full_after);
/* Now let's delete and then commit */
ensure_equal("Deleted less rows",
stmt1->executeUpdate("DELETE FROM test_function_tx WHERE 1"),
count_full_before);
stmt1->getConnection()->commit();
std::auto_ptr<sql::ResultSet> rset4(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res4 is NULL", rset4.get() != NULL);
ensure("res4 is empty", rset4->next() != false);
ensure("Table not empty after delete", rset4->getInt(1) == 0);
ensure("res4 has more rows ", rset4->next() == false);
stmt1->execute("DROP TABLE test_function_tx");
conn->setAutoCommit(old_commit_mode);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test commit and rollback (autocommit on) */
static void test_result_set_4(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure_equal("sql::Connection differs", conn.get(), stmt1->getConnection());
int old_commit_mode = conn->getAutoCommit();
conn->setAutoCommit(true);
ensure_equal_int("Data not populated", true, populate_TX_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure_equal_int("res1 is empty", rset1->next(), true);
int count_full_before = rset1->getInt(1);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
/* Let's delete and then rollback */
ensure_equal_int("Deleted less rows",
stmt1->executeUpdate("DELETE FROM test_function_tx WHERE 1"),
count_full_before);
std::auto_ptr<sql::ResultSet> rset2(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res2 is NULL", rset2.get() != NULL);
ensure_equal_int("res2 is empty", rset2->next(), true);
ensure_equal_int("Table not empty after delete", rset2->getInt(1), 0);
ensure_equal_int("res2 has more rows ", rset2->next(), false);
/* In autocommit on, this is a no-op */
stmt1->getConnection()->rollback();
std::auto_ptr<sql::ResultSet> rset3(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res3 is NULL", rset3.get() != NULL);
ensure_equal_int("res3 is empty", rset3->next(), true);
ensure_equal_int("Rollback didn't work", rset3->getInt(1), 0);
ensure_equal_int("res3 has more rows ", rset3->next(), false);
ensure("Data not populated", true == populate_TX_test_table(conn, database));
/* Now let's delete and then commit */
ensure_equal("Deleted less rows",
stmt1->executeUpdate("DELETE FROM test_function_tx WHERE 1"),
count_full_before);
/* In autocommit on, this is a no-op */
stmt1->getConnection()->commit();
std::auto_ptr<sql::ResultSet> rset4(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res4 is NULL", rset4.get() != NULL);
ensure_equal_int("res4 is empty", rset4->next(), true);
ensure_equal_int("Table not empty after delete", rset4->getInt(1), 0);
ensure_equal_int("res4 has more rows ", rset4->next(), false);
conn->setAutoCommit(false);
ensure("Data not populated", true == populate_TX_test_table(conn, database));
ensure_equal("Deleted less rows",
stmt1->executeUpdate("DELETE FROM test_function_tx WHERE 1"),
count_full_before);
/* In autocommit iff, this is an op */
stmt1->getConnection()->rollback();
std::auto_ptr<sql::ResultSet> rset5(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx"));
ensure("res5 is NULL", rset5.get() != NULL);
ensure_equal_int("res5 is empty", rset5->next(), true);
ensure_equal_int("Table empty after delete", rset5->getInt(1), count_full_before);
ensure_equal_int("res5 has more rows ", rset5->next(), false);
stmt1->execute("DROP TABLE test_function_tx");
conn->setAutoCommit(old_commit_mode);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test multistatement off - send two queries in one call */
static void test_result_set_5(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
try {
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT COUNT(*) FROM test_function_tx; DELETE FROM test_function_tx"));
ensure("ERR: Exception not thrown", false);
} catch (sql::SQLException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_result_set_check_out_of_bound(sql::ResultSet *rset1)
{
ensure("res1 is empty", rset1->next() != false);
try {
rset1->getInt(0);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getInt(123);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getInt("no_such_column");
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getString(0);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getString(123);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getString("no_such_column");
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getDouble(0);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getDouble(123);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getDouble("no_such_column");
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->getInt(rset1->getInt(1) + 1000);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->isNull(0);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->isNull(123);
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
rset1->isNull("no_such_column");
ensure("ERR: No sql::InvalidArgumentException thrown", false);
} catch (sql::InvalidArgumentException &) {}
try {
ensure_equal_int("res1 has more rows ", rset1->getInt(1), 1);
ensure_equal_int("res1 has more rows ", rset1->getInt("count of rows"), 1);
// ensure("res1 has more rows ", rset1->getDouble(1) - 1 < 0.1);
// ensure("res1 has more rows ", rset1->getDouble("count of rows") - 1 < 0.1);
// with libmysq we don't support these conversions, on the fly :(
// ensure("res1 has more rows ", rset1->getString(1).compare("1"));
// ensure("res1 has more rows ", rset1->getString("count of rows").compare("1"));
ensure_equal_int("c is not null", rset1->isNull(1), false);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
}
/* {{{ Test out of bound extraction of data */
static void test_result_set_6(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure_equal("sql::Connection differs", conn.get(), stmt1->getConnection());
ensure("Data not populated", true == populate_TX_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT COUNT(*) AS 'count of rows' FROM test_function_tx"));
ensure("res1 is NULL", rset1.get() != NULL);
test_result_set_check_out_of_bound(rset1.get());
stmt1->execute("DROP TABLE test_function_tx");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test out of bound extraction of data - PS version */
static void test_result_set_7(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
ensure("Data not populated", true == populate_TX_test_table(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt1(conn->prepareStatement("SELECT COUNT(*) AS 'count of rows' FROM test_function_tx"));
ensure("stmt1 is NULL", stmt1.get() != NULL);
ensure_equal("sql::Connection differs", conn.get(), stmt1->getConnection());
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery());
ensure("res1 is NULL", rset1.get() != NULL);
test_result_set_check_out_of_bound(rset1.get());
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("DROP TABLE test_function_tx"));
stmt2->execute();
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test commit and rollback (autocommit on) - PS version */
static void test_result_set_8(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
int count_full_before;
std::auto_ptr<sql::PreparedStatement> stmt0(conn->prepareStatement("SELECT 1"));
ensure("stmt0 is NULL", stmt0.get() != NULL);
ensure_equal("sql::Connection differs", conn.get(), stmt0->getConnection());
int old_commit_mode = conn->getAutoCommit();
conn->setAutoCommit(true);
ensure("Data not populated", true == populate_TX_test_table_PS(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt1(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx"));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery());
ensure("res1 is NULL", rset1.get() != NULL);
ensure_equal_int("res1 is empty", rset1->next(), true);
count_full_before = rset1->getInt(1);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("DELETE FROM test_function_tx WHERE 1"));
/* Let's delete and then rollback */
ensure_equal_int("Deleted less rows", stmt2->executeUpdate(), count_full_before);
std::auto_ptr<sql::PreparedStatement> stmt3(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx"));
std::auto_ptr<sql::ResultSet> rset2(stmt3->executeQuery());
ensure("res2 is NULL", rset2.get() != NULL);
ensure_equal_int("res2 is empty", rset2->next(), true);
ensure_equal_int("Table not empty after delete", rset2->getInt(1), 0);
ensure_equal_int("res2 has more rows ", rset2->next(), false);
/* In autocommit on, this is a no-op */
stmt1->getConnection()->rollback();
std::auto_ptr<sql::PreparedStatement> stmt4(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx"));
std::auto_ptr<sql::ResultSet> rset3(stmt4->executeQuery());
ensure("res3 is NULL", rset3.get() != NULL);
ensure_equal_int("res3 is empty", rset3->next(), true);
ensure_equal_int("Rollback didn't work", rset3->getInt(1), 0);
ensure_equal_int("res3 has more rows ", rset3->next(), false);
ensure("Data not populated", true == populate_TX_test_table_PS(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt5(conn->prepareStatement("DELETE FROM test_function_tx WHERE 1"));
/* Let's delete and then rollback */
ensure_equal_int("Deleted less rows", stmt5->executeUpdate(), count_full_before);
/* In autocommit on, this is a no-op */
stmt1->getConnection()->commit();
std::auto_ptr<sql::PreparedStatement> stmt6(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx"));
std::auto_ptr<sql::ResultSet> rset4(stmt6->executeQuery());
ensure("res4 is NULL", rset4.get() != NULL);
ensure_equal_int("res4 is empty", rset4->next(), true);
ensure_equal_int("Rollback didn't work", rset4->getInt(1), 0);
ensure_equal_int("res4 has more rows ", rset4->next(), false);
conn->setAutoCommit(false);
ensure("Data not populated", true == populate_TX_test_table_PS(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt7(conn->prepareStatement("DELETE FROM test_function_tx WHERE 1"));
/* Let's delete and then rollback */
ensure("Deleted less rows", stmt7->executeUpdate() == count_full_before);
/* In autocommit iff, this is an op */
stmt1->getConnection()->rollback();
std::auto_ptr<sql::PreparedStatement> stmt8(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx"));
std::auto_ptr<sql::ResultSet> rset5(stmt8->executeQuery());
ensure("res5 is NULL", rset5.get() != NULL);
ensure_equal_int("res5 is empty", rset5->next(), true);
ensure_equal_int("Rollback didn't work", rset5->getInt(1), 0);
ensure_equal_int("res5 has more rows ", rset5->next(), false);
std::auto_ptr<sql::PreparedStatement> stmt9(conn->prepareStatement("DROP TABLE test_function_tx"));
stmt1->execute();
conn->setAutoCommit(old_commit_mode);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test multistatement off - send two queries in one call - PS version */
static void test_result_set_9(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
try {
std::auto_ptr<sql::PreparedStatement> stmt1(conn->prepareStatement("SELECT COUNT(*) FROM test_function_tx; DELETE FROM test_function_tx"));
ensure("ERR: Exception not thrown", false);
} catch (sql::SQLException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test multiresults - SP with normal and prepared statement */
static void test_result_set_10(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt0(conn->createStatement());
ensure("stmt0 is NULL", stmt0.get() != NULL);
stmt0->execute("USE " + database);
#if 0
/* Doesn't work with libmysql - a limitation of the library, might work with mysqlnd if it lies under */
{
/* Create procedure is not supported for preparing */
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
stmt1->execute("DROP PROCEDURE IF EXISTS CPP1");
stmt1->execute("CREATE PROCEDURE CPP1() SELECT 42");
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("CALL CPP1()"));
stmt2->execute();
std::auto_ptr<sql::ResultSet> rset1(stmt2->getResultSet());
ensure("res1 is NULL", rset1.get() != NULL);
ensure_equal_int("res1 is empty", rset1->next(), true);
eensure_equal_intsure("Wrong data", rset1->getInt(1), 42);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
/* Here comes the status result set*/
std::auto_ptr<sql::ResultSet> rset2(stmt2->getResultSet());
ensure("res2 is not NULL", rset2.get() == NULL);
/* drop procedure is not supported for preparing */
stmt1->execute("DROP PROCEDURE CPP1");
}
{
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
stmt1->execute("DROP PROCEDURE IF EXISTS CPP1");
stmt1->execute("CREATE PROCEDURE CPP1() SELECT 42");
stmt1->execute("CALL CPP1()");
std::auto_ptr<sql::ResultSet> rset1(stmt1->getResultSet());
ensure("res1 is NULL", rset1.get() != NULL);
ensure_equal_int("res1 is empty", rset1->next(), true);
ensure_equal_int("Wrong data", rset1->getInt(1), 42);
ensure_equal_int("res1 has more rows ", rset1->next(), false);
/* Here comes the status result set*/
std::auto_ptr<sql::ResultSet> rset2(stmt1->getResultSet());
ensure_equal_int("res2 is not NULL", rset2.get(), NULL);
stmt1->execute("DROP PROCEDURE CPP1");
}
#endif
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ getMetadata() */
static void test_result_set_11(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt1(conn->createStatement());
ensure("stmt1 is NULL", stmt1.get() != NULL);
stmt1->setResultSetType(sql::ResultSet::TYPE_SCROLL_INSENSITIVE);
ensure("Data not populated", true == populate_test_table(conn, database));
std::auto_ptr<sql::ResultSet> rset1(stmt1->executeQuery("SELECT * FROM test_function"));
ensure("res1 is NULL", rset1.get() != NULL);
ensure("res1 is empty", rset1->next() != false);
stmt1->execute("set @old_charset_res=@@session.character_set_results");
stmt1->execute("set character_set_results=NULL");
sql::ResultSetMetaData * meta1 = rset1->getMetaData();
ensure("column name differs", !meta1->getColumnName(1).compare("a"));
ensure("column name differs", !meta1->getColumnName(2).compare("b"));
ensure("column name differs", !meta1->getColumnName(3).compare("c"));
ensure("column name differs", !meta1->getColumnName(4).compare("d"));
ensure("column name differs", !meta1->getColumnName(5).compare("e"));
ensure_equal_int("bad case sensitivity", meta1->isCaseSensitive(1), false);
ensure_equal_int("bad case sensitivity", meta1->isCaseSensitive(2), false);
ensure_equal_int("bad case sensitivity", meta1->isCaseSensitive(3), false);
ensure_equal_int("bad case sensitivity", meta1->isCaseSensitive(4), false);
// ensure_equal_int("bad case sensitivity", meta1->isCaseSensitive(5), true);
ensure_equal_int("bad case sensitivity", meta1->isCurrency(1), false);
ensure_equal_int("bad case sensitivity", meta1->isCurrency(2), false);
ensure_equal_int("bad case sensitivity", meta1->isCurrency(3), false);
ensure_equal_int("bad case sensitivity", meta1->isCurrency(4), false);
ensure_equal_int("bad case sensitivity", meta1->isCurrency(5), false);
stmt1->execute("set character_set_results=@old_charset_res");
try {
meta1->getColumnName(0);
meta1->isCaseSensitive(0);
meta1->isCurrency(0);
ensure("Exception not correctly thrown", false);
} catch (sql::SQLException &) {
ensure("Exception correctly thrown", true);
}
try {
meta1->getColumnName(100);
meta1->isCaseSensitive(100);
meta1->isCurrency(100);
ensure("Exception not correctly thrown", false);
} catch (sql::SQLException &) {
ensure("Exception correctly thrown", true);
}
/*
a integer unsigned not null,
b integer,
c integer default null,
d char(10),
e varchar(10) character set utf8 collate utf8_bin
*/
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
#if 0
/* {{{ General test 0 */
static void test_general_0(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
sql::DatabaseMetaData * meta = conn->getMetaData();
std::auto_ptr<sql::ResultSet> rset(meta->getSchemata());
while (rset->next()) {
std::auto_ptr<sql::ResultSet> rset2(meta->getSchemaObjects("", rset->getString("schema_name")));
while (rset2->next()) {
rset2->getString("object_type").c_str();
rset2->getString("name").c_str();
rset2->getString("ddl").c_str();
}
}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ General test 1 */
static void test_general_1(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
stmt->execute("DROP TABLE IF EXISTS test.product");
stmt->execute("CREATE TABLE test.product(idproduct INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(80))");
conn->setAutoCommit(0);
std::auto_ptr<sql::PreparedStatement> prepStmt(conn->prepareStatement("INSERT INTO test.product (idproduct, name) VALUES(?, ?)"));
prepStmt->setInt(1, 1);
prepStmt->setString(2, "The answer is 42");
prepStmt->executeUpdate();
std::auto_ptr<sql::ResultSet> rset1(stmt->executeQuery("SELECT * FROM test.product"));
ensure_equal_int("Empty result set", rset1->next(), true);
ensure("Wrong data", !rset1->getString(2).compare("The answer is 42"));
ensure("Wrong data", !rset1->getString("name").compare("The answer is 42"));
ensure_equal_int("Non-Empty result set", rset1->next(), false);
conn->rollback();
std::auto_ptr<sql::ResultSet> rset2(stmt->executeQuery("SELECT * FROM test.product"));
ensure_equal_int("Non-Empty result set", rset1->next(), false);
stmt->execute("DROP TABLE IF EXISTS test.product");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
#endif
/* {{{ */
static void test_prep_statement_0(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
try {
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT 1"));
stmt->execute();
std::auto_ptr<sql::ResultSet> rset1(stmt->getResultSet());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
/* Bind but don't execute. There should be no leak */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?, ?, ?"));
stmt->setInt(1, 1);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
/* Bind two different types for the same column. There should be no leak */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
stmt->setString(1, "Hello MySQL");
stmt->setInt(1, 42);
stmt->execute();
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
/* Execute without fetching the result set. The connector should clean the wire */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?, ?, ?, ?"));
stmt->setInt(1, 1);
stmt->setDouble(2, 2.25);
stmt->setString(3, "Здрасти МySQL");
stmt->setDateTime(4, "2006-11-10 16:17:18");
stmt->execute();
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
#if 0
/* Bind one parameter less than needed - NULL should be sent to the server . Check also multibyte fetching. */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ? as \"Здравей_МySQL\" , ?, ?"));
stmt->setInt(3, 42);
stmt->setString(1, "Здравей МySQL! Как си?");
stmt->execute();
std::auto_ptr<sql::ResultSet> rset(stmt->getResultSet());
ensure("No result set", rset.get() != NULL);
ensure("Result set is empty", rset->next() != false);
ensure("Incorrect value for col 1", rset->getInt(2) == 0 && true == rset->wasNull());
ensure("Incorrect value for col 0", !rset->getString(1).compare("Здравей МySQL! Как си?") && false == rset->wasNull());
ensure("Incorrect value for col 0", !rset->getString("Здравей_МySQL").compare("Здравей МySQL! Как си?") && false == rset->wasNull());
ensure("Incorrect value for col 2", rset->getInt(3) == 42 && false == rset->wasNull());
ensure("Incorrect value for col 2", !rset->getString(3).compare("42") && false == rset->wasNull());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
#endif
/* try double ::execute() */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
stmt->setString(1, "Hello World");
for (int i = 0; i < 100; ++i) {
std::auto_ptr<sql::ResultSet> rset(stmt->executeQuery());
}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
/* Test clearParameters() */
{
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
stmt->setInt(1, 13);
std::auto_ptr<sql::ResultSet> rs(stmt->executeQuery());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
stmt->setInt(1, 13);
stmt->clearParameters();
std::auto_ptr<sql::ResultSet> rs(stmt->executeQuery());
ensure("Exception not thrown", false);
} catch (sql::SQLException &) {}
}
/* try clearParameters() call */
{
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?, ?, ?, NULL"));
try {
stmt->setInt(3, 42);
stmt->setString(1, "Hello MYSQL");
stmt->setDouble(2, 1.25);
std::auto_ptr<sql::ResultSet> rset(stmt->executeQuery());
ensure("No result set", rset.get() != NULL);
ensure("Result set is empty", rset->next() != false);
ensure("Non empty string returned for NULL", rset->getString(4).length() == 0);
ensure("wasNull() not properly set for NULL", rset->wasNull());
ensure("isNull() is wrong", rset->isNull(4));
ensure("Incorrect value for col 4", !rset->getString(4).compare("") && true == rset->wasNull());
ensure("Incorrect value for col 0", !rset->getString(1).compare("Hello MYSQL") && false == rset->wasNull());
ensure("Incorrect value for col 2", rset->getInt(3) == 42 && false == rset->wasNull());
// ensure("Incorrect value for col 2", !rset->getString(3).compare("42") && false == rset->wasNull());
ensure("Incorrect value for col 3", rset->getDouble(2) == 1.25 && false == rset->wasNull());
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
}
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT ?"));
stmt->setInt(1, 1);
stmt->execute();
std::auto_ptr<sql::ResultSet> rset(stmt->getResultSet());
} catch (sql::SQLException &) {
printf("\n# ERR: Caught sql::SQLException at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test simple update statement against statement object */
static void test_prep_statement_1(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, const std::string & database)
{
ENTER_FUNCTION();
try {
std::auto_ptr<sql::PreparedStatement> stmt0(conn->prepareStatement("SELECT 1, 2, 3"));
ensure("stmt0 is NULL", stmt0.get() != NULL);
ensure("Data not populated", true == populate_test_table_PS(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt1(conn->prepareStatement("SELECT * FROM test_function"));
ensure("stmt1 is NULL", stmt1.get() != NULL);
if (false == stmt1->execute()) {
ensure("False returned for SELECT", false);
}
std::auto_ptr<sql::ResultSet> rset(stmt1->getResultSet());
/* Clean */
std::auto_ptr<sql::Statement> stmt2(conn2->createStatement());
ensure("stmt2 is NULL", stmt2.get() != NULL);
stmt2->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt3(conn2->prepareStatement("DROP TABLE test_function"));
ensure("stmt3 is NULL", stmt3.get() != NULL);
stmt3->execute();
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test simple update statement against statement object */
static void test_prep_statement_2(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
populate_test_table_PS_integers(conn, database);
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT '1"));
ensure("ERR: Exception not thrown", false);
} catch (sql::SQLException &) {}
/* USE still cannot be prepared */
try {
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("USE " + database));
ensure("ERR: Exception not thrown", false);
} catch (sql::SQLException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Test simple update statement against statement object */
static void test_prep_statement_3(std::auto_ptr<sql::Connection> & conn, std::auto_ptr<sql::Connection> & conn2, const std::string & database)
{
ENTER_FUNCTION();
try {
int64_t r1_c1 = L64(2147483646),
r1_c2 = L64(2147483650),
r1_c3 = L64(9223372036854775806),
r2_c1 = L64(2147483647),
r2_c2 = L64(2147483649),
r2_c3 = L64(9223372036854775807);
uint64_t r1_c4 = UL64(9223372036854775810),
r2_c4 = UL64(18446744073709551615);
ensure("Data not populated", true == populate_test_table_PS_integers(conn, database));
std::auto_ptr<sql::PreparedStatement> stmt1(conn->prepareStatement("INSERT INTO test_function_int (i, i_uns, b, b_uns) VALUES(?,?,?,?)"));
ensure("stmt0 is NULL", stmt1.get() != NULL);
stmt1->clearParameters();
stmt1->setInt(1, static_cast<int>(r1_c1));
stmt1->setInt64(2, r1_c2);
stmt1->setInt64(3, r1_c3);
stmt1->setUInt64(4, r1_c4);
ensure("True returned for INSERT", false == stmt1->execute());
stmt1->clearParameters();
stmt1->setInt(1, static_cast<int>(r2_c1));
stmt1->setInt64(2, r2_c2);
stmt1->setInt64(3, r2_c3);
stmt1->setUInt64(4, r2_c4);
ensure("True returned for INSERT", false == stmt1->execute());
{
std::auto_ptr<sql::PreparedStatement> stmt2(conn->prepareStatement("SELECT i, i_uns, b, b_uns FROM test_function_int"));
ensure("stmt1 is NULL", stmt2.get() != NULL);
ensure("False returned for SELECT", stmt2->execute());
std::auto_ptr<sql::ResultSet> rset(stmt2->getResultSet());
ensure("No first line", rset->next());
ensure_equal_int64("Different data", rset->getInt("i"), r1_c1);
ensure_equal_int64("Different data", rset->getInt(1), r1_c1);
ensure_equal_int64("Different data", rset->getInt64("i_uns"), r1_c2);
ensure_equal_int64("Different data", rset->getInt64(2), r1_c2);
ensure_equal_int64("Different data", rset->getInt64("b"), r1_c3);
ensure_equal_int64("Different data", rset->getInt64(3), r1_c3);
ensure_equal_uint64("Different data", rset->getUInt64("b_uns"), r1_c4);
ensure_equal_uint64("Different data", rset->getUInt64(4), r1_c4);
ensure("No second line", rset->next());
ensure_equal_int64("Different data", rset->getInt("i"), r2_c1);
ensure_equal_int64("Different data", rset->getInt(1), r2_c1);
ensure_equal_int64("Different data", rset->getInt64("i_uns"), r2_c2);
ensure_equal_int64("Different data", rset->getInt64(2), r2_c2);
ensure_equal_int64("Different data", rset->getInt64("b"), r2_c3);
ensure_equal_int64("Different data", rset->getInt64(3), r2_c3);
ensure_equal_uint64("Different data", rset->getUInt64("b_uns"), r2_c4);
ensure_equal_uint64("Different data", rset->getUInt64(4), r2_c4);
ensure("Too many lines", rset->next() == false);
}
{
std::auto_ptr<sql::Statement> stmt2(conn->createStatement());
ensure("stmt1 is NULL", stmt2.get() != NULL);
ensure("False returned for SELECT", stmt2->execute("SELECT i, i_uns, b, b_uns FROM test_function_int"));
std::auto_ptr<sql::ResultSet> rset(stmt2->getResultSet());
ensure("No first line", rset->next());
ensure_equal_int64("Different data", rset->getInt("i"), r1_c1);
ensure_equal_int64("Different data", rset->getInt(1), r1_c1);
ensure_equal_int64("Different data", rset->getInt64("i_uns"), r1_c2);
ensure_equal_int64("Different data", rset->getInt64(2), r1_c2);
ensure_equal_int64("Different data", rset->getInt64("b"), r1_c3);
ensure_equal_int64("Different data", rset->getInt64(3), r1_c3);
ensure_equal_uint64("Different data", rset->getUInt64("b_uns"), r1_c4);
ensure_equal_uint64("Different data", rset->getUInt64(4), r1_c4);
ensure("No second line", rset->next());
ensure_equal_int64("Different data", rset->getInt("i"), r2_c1);
ensure_equal_int64("Different data", rset->getInt(1), r2_c1);
ensure_equal_int64("Different data", rset->getInt64("i_uns"), r2_c2);
ensure_equal_int64("Different data", rset->getInt64(2), r2_c2);
ensure_equal_int64("Different data", rset->getInt64("b"), r2_c3);
ensure_equal_int64("Different data", rset->getInt64(3), r2_c3);
ensure_equal_uint64("Different data", rset->getUInt64("b_uns"), r2_c4);
ensure_equal_uint64("Different data", rset->getUInt64(4), r2_c4);
ensure("Too many lines", rset->next() == false);
}
/* Clean */
std::auto_ptr<sql::Statement> stmt4(conn2->createStatement());
ensure("stmt4 is NULL", stmt4.get() != NULL);
stmt4->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt5(conn2->prepareStatement("DROP TABLE test_function_int"));
ensure("stmt5 is NULL", stmt5.get() != NULL);
stmt5->execute();
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ Tests blob with PS */
static void test_prep_statement_blob(std::auto_ptr<sql::Connection> & conn, std::string database)
{
ENTER_FUNCTION();
try {
populate_blob_table(conn, database);
/* USE still cannot be prepared */
std::auto_ptr<sql::Statement> use_stmt(conn->createStatement());
use_stmt->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("INSERT INTO test_blob VALUES(?)"));
std::string value("A\0B", sizeof("A\0B") - 1);
std::istringstream tmp_blob(value);
stmt->setBlob(1, &tmp_blob);
stmt->execute();
std::auto_ptr<sql::Statement> stmt2(conn->createStatement());
stmt2->execute("SELECT * FROM test_blob");
std::auto_ptr<sql::ResultSet> rset2(stmt2->getResultSet());
ensure("res2 is NULL", rset2.get() != NULL);
ensure_equal_int("res2 is empty", rset2->next(), true);
ensure_equal_str("Wrong data", rset2->getString(1), value);
std::auto_ptr<std::istream> blob(rset2->getBlob(1));
std::string::iterator it;
for (it = value.begin() ; it < value.end(); ++it) {
if ((blob->rdstate() & std::istream::eofbit)) {
ensure("premature eof", 0);
}
char ch;
blob->get(ch);
if ((blob->rdstate() & std::istream::badbit) != 0) {
ensure("badbit set", false);
} else if ((blob->rdstate() & std::istream::failbit) != 0) {
if ((blob->rdstate() & std::istream::eofbit) == 0) {
ensure("failbit set without eof being set", false);
}
}
if (*it != ch) {
ensure("character differ", false);
}
}
ensure("BLOB doesn't match, has more data", (blob->rdstate() & std::istream::eofbit) == 0);
ensure_equal_int("res2 has more rows ", rset2->next(), false);
stmt2->execute("DELETE FROM test_blob WHERE 1");
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
#define DEBUG_TABLE_PRIVS 0
/* {{{ Tests getTablePrivileges */
/* TODO - broken
static void test_get_table_privileges_1(const std::string & host, const std::string & user, const std::string & pass)
{
ENTER_FUNCTION();
int a;
char buf[20] = "p";
snprintf(buf+1, sizeof(buf) - 2, "%u", ((unsigned int) &a) % 10000);
std::string plain_user(std::string("tu").append(buf));
std::string plain_user_w_host(std::string("").append(plain_user).
#if A0
append("@%"));
#else
append("@localhost"));
#endif
std::string plain_user_db(std::string("test_someuser_db").append(buf));
std::string plain_user_table("table1");
std::string create_db(std::string("CREATE DATABASE `").append(plain_user_db).append("`"));
std::string create_table(std::string("CREATE TABLE `").append(plain_user_db).append("`.`").append(plain_user_table).append("`(a int)"));
std::string create_user(std::string("CREATE USER ").append(plain_user_w_host).append(" IDENTIFIED BY 'pass'"));
std::string grant_user1(std::string("GRANT ALL ON `").append(plain_user_db).append("`.`").
append(plain_user_table).append("` TO ").append(plain_user_w_host));
std::string grant_user2(std::string("GRANT DELETE ON `").append(plain_user_db).append("`.`").
append(plain_user_table).append("` TO ").append(plain_user_w_host));
std::string grant_user3(std::string("GRANT SELECT, INSERT ON `").append(plain_user_db).append("`.`").
append(plain_user_table).append("` TO ").append(plain_user_w_host));
std::string drop_user(std::string("DROP USER ").append(plain_user_w_host));
std::string drop_db(std::string("DROP DATABASE `").append(plain_user_db).append("`"));
std::list< std::string > grantsList;
grantsList.push_back(grant_user1);
grantsList.push_back(grant_user2);
grantsList.push_back(grant_user3);
std::list< std::list< std::string > > expectedPrivilegesList;
std::list< std::string > expectedPrivileges1;
expectedPrivileges1.push_back(std::string("ALTER"));
expectedPrivileges1.push_back(std::string("DELETE"));
expectedPrivileges1.push_back(std::string("DROP"));
expectedPrivileges1.push_back(std::string("INDEX"));
expectedPrivileges1.push_back(std::string("INSERT"));
expectedPrivileges1.push_back(std::string("LOCK TABLES"));
expectedPrivileges1.push_back(std::string("SELECT"));
expectedPrivileges1.push_back(std::string("UPDATE"));
expectedPrivilegesList.push_back(expectedPrivileges1);
std::list< std::string > expectedPrivileges2;
expectedPrivileges2.push_back(std::string("DELETE"));
expectedPrivilegesList.push_back(expectedPrivileges2);
std::list< std::string > expectedPrivileges3;
expectedPrivileges3.push_back(std::string("SELECT"));
expectedPrivileges3.push_back(std::string("INSERT"));
expectedPrivilegesList.push_back(expectedPrivileges3);
std::list< std::string >::const_iterator grantsList_it = grantsList.begin();
std::list< std::list< std::string > >::const_iterator expectedPrivilegesList_it = expectedPrivilegesList.begin();
try {
std::auto_ptr<sql::Connection> root_conn(get_connection(host, user, pass));
std::auto_ptr<sql::Statement> root_stmt(root_conn->createStatement());
#if DEBUG_TABLE_PRIVS
std::cout << std::endl << plain_user_w_host << std::endl;
#endif
for (; grantsList_it != grantsList.end(); ++grantsList_it, ++expectedPrivilegesList_it) {
root_stmt->execute(create_db);
root_stmt->execute(create_table);
root_stmt->execute(create_user);
root_stmt->execute(*grantsList_it);
Put it in a block, so the connection will be closed before we start dropping the user and the table
try {
std::auto_ptr<sql::Connection> user_conn(get_connection(host, plain_user, "pass"));
std::auto_ptr<sql::DatabaseMetaData> user_conn_meta(user_conn->getMetaData());
std::auto_ptr<sql::ResultSet> res(user_conn_meta->getTablePrivileges("", "%", "%"));
#if DEBUG_TABLE_PRIVS
printf("\tTABLE_CAT\tTABLE_SCHEM\tTABLE_NAME\tGRANTOR\tGRANTEE\tPRIVILEGE\tIS_GRANTABLE\n");
#endif
unsigned int found = 0, rows = 0;
while (res->next()) {
#if DEBUG_TABLE_PRIVS
for (int i = 1; i < 8; ++i) printf("\t[%s]", res->getString(i).c_str());
printf("\n");
#endif
std::list< std::string >::const_iterator it = expectedPrivilegesList_it->begin();
for (;it != expectedPrivilegesList_it->end(); ++it) {
if (!it->compare(res->getString("PRIVILEGE"))) {
++found;
}
// ensure_equal("Bad TABLE_CAT", std::string(""), res->getString("TABLE_CAT"));
// ensure_equal("Bad TABLE_SCHEM", plain_user_db, res->getString("TABLE_SCHEM"));
// ensure_equal("Bad TABLE_NAME", plain_user_table, res->getString("TABLE_NAME"));
// ensure_equal("Bad GRANTEE", plain_user_w_host, res->getString("GRANTEE"));
}
++rows;
}
#if DEBUG_TABLE_PRIVS
std::cout << "Found:" << found << " Rows:" << rows << "\n";
#endif
ensure_equal_int("Bad PRIVILEGE data(1)", found, expectedPrivilegesList_it->size());
ensure_equal_int("Bad PRIVILEGE data(2)", found, rows);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
root_stmt->execute(drop_user);
root_stmt->execute(drop_db);
}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
*/
/* {{{ Invoke as many "not implemented" methods as possible for better code coverage (and to make sure we keep CHANGES current) */
static void test_not_implemented_connection(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("bar");
int int_array[] = {1, 2, 3};
sql::SQLString string_array[] = {"a", "b", "c"};
try {
try {
++total_tests;
conn->isReadOnly();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// prepareStatement(const std::string& /* sql */, int /* autoGeneratedKeys */)
try {
++total_tests;
conn->prepareStatement(bar, 1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// prepareStatement(const std::string& /* sql */, int /* columnIndexes */ [])
try {
++total_tests;
conn->prepareStatement(bar, int_array);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// prepareStatement(const std::string& /* sql */, int /* resultSetType */, int /*
try {
++total_tests;
conn->prepareStatement(bar, 1, 1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// prepareStatement(const std::string& /* sql */, int /* resultSetType */, int /* resultSetConcurrency */, int /* resultSetHoldability */)
try {
++total_tests;
conn->prepareStatement(bar, 1, 1, 1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// prepareStatement(const std::string& /* sql */, std::string /* columnNames*/ [])
try {
++total_tests;
conn->prepareStatement(bar, string_array);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setHoldability(int /* holdability */)
try {
++total_tests;
conn->setHoldability(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setReadOnly(bool /* readOnly */)
try {
++total_tests;
conn->setReadOnly(true);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setSavepoint()
try {
++total_tests;
conn->setSavepoint();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_statement(std::auto_ptr<sql::Connection> & conn, const std::string & database)
{
ENTER_FUNCTION();
std::string bar("foo");
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
stmt->execute("USE " + database);
try {
// cancel()
try {
++total_tests;
stmt->cancel();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchSize()
try {
++total_tests;
stmt->getFetchSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setFetchSize(unsigned int)
try {
++total_tests;
stmt->setFetchSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setQueryTimeout(unsigned int)
try {
++total_tests;
stmt->setQueryTimeout(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getMaxFieldSize()
try {
++total_tests;
stmt->getMaxFieldSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getMaxRows()
try {
++total_tests;
stmt->getMaxRows();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getQueryTimeout()
try {
++total_tests;
stmt->getQueryTimeout();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setCursorName(const std::string &)
try {
++total_tests;
stmt->setCursorName(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setEscapeProcessing(bool)
try {
++total_tests;
stmt->setEscapeProcessing(true);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setMaxFieldSize(unsigned int)
try {
++total_tests;
stmt->setMaxFieldSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setMaxRows(unsigned int)
try {
++total_tests;
stmt->setMaxRows(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_conn_meta(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
sql::DatabaseMetaData * conn_meta = conn->getMetaData();
try {
// getURL()
try {
++total_tests;
conn_meta->getURL();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// locatorsUpdateCopy()
try {
++total_tests;
conn_meta->locatorsUpdateCopy();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// supportsIntegrityEnhancementFacility()
try {
++total_tests;
conn_meta->supportsIntegrityEnhancementFacility();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// supportsResultSetConcurrency(int /* type */, int /* concurrency */)
try {
++total_tests;
conn_meta->supportsResultSetConcurrency(1, 2);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_ps(std::auto_ptr<sql::Connection> & conn, const std::string & database)
{
ENTER_FUNCTION();
std::string bar("jedervernunft");
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
stmt->execute("USE " + database);
std::auto_ptr<sql::PreparedStatement> ps1(conn->prepareStatement("SELECT 1"));
std::auto_ptr<sql::PreparedStatement> ps2(conn->prepareStatement("SELECT ?"));
ps2->setInt(1, 2);
try {
// execute(const std::string&)
try {
++total_tests;
ps1->execute(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// executeQuery(const std::string&)
try {
++total_tests;
ps1->executeQuery(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// executeUpdate(const std::string&)
try {
++total_tests;
ps1->executeUpdate(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// cancel()
try {
++total_tests;
ps2->cancel();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchSize()
try {
++total_tests;
ps2->getFetchSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setFetchSize(unsigned int)
try {
++total_tests;
ps2->setFetchSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setQueryTimeout(unsigned int)
try {
++total_tests;
ps2->setQueryTimeout(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getMaxFieldSize()
try {
++total_tests;
ps2->getMaxFieldSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getMaxRows()
try {
++total_tests;
ps2->getMaxRows();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getMoreResult
try {
++total_tests;
ps2->getMoreResults();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getQueryTimeout()
try {
++total_tests;
ps2->getQueryTimeout();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getUpdateCount()
try {
++total_tests;
ps2->getUpdateCount();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setCursorName(const std::string &)
try {
++total_tests;
ps2->setCursorName(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setEscapeProcessing(bool)
try {
++total_tests;
ps2->setEscapeProcessing(true);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setMaxFieldSize(unsigned int)
try {
++total_tests;
ps2->setMaxFieldSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setMaxRows(unsigned int)
try {
++total_tests;
ps2->setMaxRows(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_resultset(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT 1 AS 'a'"));
try {
// cancelRowUpdates()
try {
++total_tests;
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getConcurrency()
try {
++total_tests;
res->getConcurrency();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getCursorName()
try {
++total_tests;
res->getCursorName();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchDirection()
try {
++total_tests;
res->getFetchDirection();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchSize()
try {
++total_tests;
res->getFetchSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getHoldability()
try {
++total_tests;
res->getHoldability();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(unsigned int)
try {
++total_tests;
res->getRowId(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(const std::string &)
try {
++total_tests;
res->getRowId(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// insertRow()
try {
++total_tests;
res->insertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToCurrentRow()
try {
++total_tests;
res->moveToCurrentRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToInsertRow()
try {
++total_tests;
res->moveToInsertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// refreshRow()
try {
++total_tests;
res->refreshRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowDeleted()
try {
++total_tests;
res->rowDeleted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowInserted()
try {
++total_tests;
res->rowInserted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowUpdated()
try {
++total_tests;
res->rowUpdated();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setFetchSize(size_t /* rows */)
try {
++total_tests;
res->setFetchSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_ps_resultset(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
std::auto_ptr<sql::PreparedStatement> stmt(conn->prepareStatement("SELECT 1 AS 'a'"));
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery());
try {
// cancelRowUpdates()
try {
++total_tests;
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getConcurrency()
try {
++total_tests;
res->getConcurrency();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getCursorName()
try {
++total_tests;
res->getCursorName();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchDirection()
try {
++total_tests;
res->getFetchDirection();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchSize()
try {
++total_tests;
res->getFetchSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getHoldability()
try {
++total_tests;
res->getHoldability();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(unsigned int)
try {
++total_tests;
res->getRowId(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(const std::string &)
try {
++total_tests;
res->getRowId(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// insertRow()
try {
++total_tests;
res->insertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToCurrentRow()
try {
++total_tests;
res->moveToCurrentRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToInsertRow()
try {
++total_tests;
res->moveToInsertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// refreshRow()
try {
++total_tests;
res->refreshRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowDeleted()
try {
++total_tests;
res->rowDeleted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowInserted()
try {
++total_tests;
res->rowInserted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowUpdated()
try {
++total_tests;
res->rowUpdated();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setFetchSize(size_t /* rows */)
try {
++total_tests;
res->setFetchSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_cs_resultset(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
sql::DatabaseMetaData * conn_meta = conn->getMetaData();
std::auto_ptr<sql::ResultSet> res(conn_meta->getSchemaObjectTypes());
try {
// cancelRowUpdates()
try {
++total_tests;
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getConcurrency()
try {
++total_tests;
res->getConcurrency();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getCursorName()
try {
++total_tests;
res->getCursorName();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchDirection()
try {
++total_tests;
res->getFetchDirection();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getFetchSize()
try {
++total_tests;
res->getFetchSize();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getHoldability()
try {
++total_tests;
res->getHoldability();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(unsigned int)
try {
++total_tests;
res->getRowId(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getRowId(const std::string &)
try {
++total_tests;
res->getRowId(bar);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// insertRow()
try {
++total_tests;
res->insertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToCurrentRow()
try {
++total_tests;
res->moveToCurrentRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// moveToInsertRow()
try {
++total_tests;
res->moveToInsertRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// refreshRow()
try {
++total_tests;
res->refreshRow();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowDeleted()
try {
++total_tests;
res->rowDeleted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowInserted()
try {
++total_tests;
res->rowInserted();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// rowUpdated()
try {
++total_tests;
res->rowUpdated();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// setFetchSize(size_t /* rows */)
try {
++total_tests;
res->setFetchSize(1);
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_rs_meta(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT 1 AS 'a'"));
try {
try {
++total_tests;
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
static void test_not_implemented_cs_rs_meta(std::auto_ptr<sql::Connection> & conn)
{
ENTER_FUNCTION();
std::string bar("foo");
sql::DatabaseMetaData * conn_meta = conn->getMetaData();
std::auto_ptr<sql::ResultSet> res(conn_meta->getSchemaObjectTypes());
sql::ResultSetMetaData * meta = res->getMetaData();
try {
// getColumnDisplaySize(unsigned int columnIndex)
try {
++total_tests;
meta->getColumnDisplaySize(1);
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getPrecision(unsigned int columnIndex)
try {
++total_tests;
meta->getPrecision(1);
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
// getScale(unsigned int columnIndex)
try {
++total_tests;
meta->getScale(1);
res->cancelRowUpdates();
ensure("ERR: Exception not thrown", false);
} catch (sql::MethodNotImplementedException &) {}
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
++total_errors;
} catch (...) {
printf("\n# ERR: Caught unknown exception at %s::%d\n", CPPCONN_FUNC, __LINE__);
printf("# ");
++total_errors;
}
LEAVE_FUNCTION();
}
/* }}} */
/* {{{ */
int run_tests(int argc, const char **argv)
{
printf("1..%d\n#\n", loops);
std::auto_ptr<sql::Connection> conn, conn2;
int last_error_total = 0;
int i;
const std::string user(argc >=3? argv[2]:"root");
const std::string pass(argc >=4? argv[3]:"root");
const std::string database(argc >=5? argv[4]:USED_DATABASE);
for (i = 0 ; i < loops; ++i) {
last_error_total = total_errors;
printf("# 0 - total_errors %d, last_error_total = %d\n", total_errors, last_error_total);
const std::string host(argc >=2? argv[1]:"tcp://127.0.0.1");
std::cout << "# Host=" << host << std::endl;
std::cout << "# User=" << user << std::endl;
std::string connect_method("unknown");
if (host.find("tcp://", (size_t)0) != std::string::npos) {
connect_method = "tcp";
} else if (host.find("unix://", (size_t)0) != std::string::npos) {
connect_method = "socket";
}
printf("#--------------- %d -----------------\n", i + 1);
printf("# ");
try {
conn.reset(get_connection(host, user, pass));
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("not ok\n");
return 1;
}
/* XXX : Doing upcast, not the best thing, but tests getMySQLVariable */
// ensure("Testing getSessionVariable",
// 0 == ((sql::mysql::MySQL_Connection *) conn)->getSessionVariable("version").compare(
// mysql_get_server_info(((sql::mysql::MySQL_Connection *) conn)->getMySQLHandle())
// )
// );
// printf("\n");
// printf("# Server %s\n", ((sql::mysql::MySQL_Connection *) conn)->getSessionVariable("version").c_str());
// printf("# ");
try {
std::auto_ptr<sql::Statement> stmt(conn->createStatement());
stmt->execute("SHOW ENGINES");
{
std::auto_ptr<sql::ResultSet> rset(stmt->getResultSet());
int found = 0;
while (rset->next()) {
if (rset->getString("Engine") == "InnoDB" && (rset->getString("Support") == "YES" || rset->getString("Support") == "DEFAULT")) {
found = 1;
break;
}
}
if (found == 0) {
printf("\n#ERR: InnoDB Storage engine not available or disabled\n");
printf("not ok\n");
return 1;
}
}
stmt->execute("USE " + database);
} catch (sql::SQLException &e) {
printf("\n# ERR: Caught sql::SQLException at %s::%d [%s] (%d/%s)\n", CPPCONN_FUNC, __LINE__, e.what(), e.getErrorCode(), e.getSQLStateCStr());
printf("# ");
return 1;
}
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_connection_0(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_connection_1(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_connection_2(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_connection_3(conn, user);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_autocommit(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_statement_0(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_1(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_2(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_3(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_4(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_5(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_6(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_7(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_8(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_9(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_statement_10(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_0(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_1(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_2(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_3(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_4(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_5(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_6(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_7(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_8(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_9(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_10(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_result_set_11(conn, database);
conn.reset(NULL);
#if 0
test_general_0(conn); delete conn;
test_general_1(conn); delete conn;
#endif
conn.reset(get_connection(host, user, pass));
test_prep_statement_0(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_prep_statement_1(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_prep_statement_2(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
conn2.reset(get_connection(host, user, pass));
test_prep_statement_3(conn, conn2, database);
conn.reset(NULL);
conn2.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_prep_statement_blob(conn, database);
conn.reset(NULL);
// test_get_table_privileges_1(host, user, pass);
conn.reset(get_connection(host, user, pass));
test_not_implemented_connection(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_statement(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_conn_meta(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_ps(conn, database);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_resultset(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_ps_resultset(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_cs_resultset(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_rs_meta(conn);
conn.reset(NULL);
conn.reset(get_connection(host, user, pass));
test_not_implemented_cs_rs_meta(conn);
conn.reset(NULL);
printf("\n#--------------- %d -----------------\n", i + 1);
if ((total_errors - last_error_total) == 0) {
printf("ok %d - %s_%s_loop%d\n", i + 1, TEST_COMMON_TAP_NAME, connect_method.c_str(), i + 1);
} else {
printf("not ok %d - %s_%s_loop%d\n", i + 1, TEST_COMMON_TAP_NAME, connect_method.c_str(), i + 1);
}
}
printf("\n# Loops=%2d Tests= %4d Failures= %3d \n", loops, total_tests, total_errors);
return 0;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| 33.917169 | 273 | 0.667253 | [
"object",
"3d"
] |
f5125c8c7cfbdf403302a8c5fa1853c4dd74d678 | 12,600 | cc | C++ | pmd_reader.cc | aoowweenn/MMDLoader | 6b9b4bcf3c3736d1ebe4e77125ef4c1671ba4027 | [
"BSD-3-Clause"
] | 95 | 2015-01-18T07:00:57.000Z | 2022-03-05T06:05:32.000Z | pmd_reader.cc | aoowweenn/MMDLoader | 6b9b4bcf3c3736d1ebe4e77125ef4c1671ba4027 | [
"BSD-3-Clause"
] | 15 | 2016-09-04T07:16:59.000Z | 2016-09-20T15:44:47.000Z | pmd_reader.cc | aoowweenn/MMDLoader | 6b9b4bcf3c3736d1ebe4e77125ef4c1671ba4027 | [
"BSD-3-Clause"
] | 25 | 2015-05-26T04:41:54.000Z | 2022-01-12T18:53:02.000Z | #include <cassert>
#include <cstring> // memcpy
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <iostream>
#include "pmd_reader.h"
#define MAX_BUF_LEN 20
struct sjis_table_rec_t
{
char unicode_name[MAX_BUF_LEN];
char ascii_name[MAX_BUF_LEN];
char sjis_name[MAX_BUF_LEN];
};
using namespace mmd;
// http://akemiwhy.deviantart.com/art/mmd-reference-japanese-bone-names-430962605
// http://ash.jp/code/unitbl21.htm
sjis_table_rec_t sjis_table[] = {
{"グルーブ", "groove", {0x83, 0x4F, 0x83, 0x8B, 0x81, 0x5B, 0x83, 0x75, 0x00}},
{"センター", "center", {0x83, 0x5A, 0x83, 0x93, 0x83, 0x5E, 0x81, 0x5B, 0x00}},
{"上半身", "upper_body", {0x8F, 0xE3, 0x94, 0xBC, 0x90, 0x67, 0x00}},
{"下半身", "lower_body", {0x89, 0xBA, 0x94, 0xBC, 0x90, 0x67, 0x00}},
{"両目", "eyes", {0x97, 0xBC, 0x96, 0xDA, 0x00}},
{"全ての親", "mother", {0x91, 0x53, 0x82, 0xC4, 0x82, 0xCC, 0x90, 0x65, 0x00}},
{"右つま先IK", "toe_IK_R", {0x89, 0x45, 0x82, 0xC2, 0x82, 0xDC, 0x90, 0xE6, 0x82, 0x68, 0x82, 0x6A, 0x00}},
{"右ひざ", "knee_R", {0x89, 0x45, 0x82, 0xD0, 0x82, 0xB4, 0x00}},
{"右ひじ", "elbow_R", {0x89, 0x45, 0x82, 0xD0, 0x82, 0xB6, 0x00}},
{"右中指1", "middle1_R", {0x89, 0x45, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"右中指2", "middle2_R", {0x89, 0x45, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"右中指3", "middle3_R", {0x89, 0x45, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"右人指1", "fore1_R", {0x89, 0x45, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"右人指2", "fore2_R", {0x89, 0x45, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"右人指3", "fore3_R", {0x89, 0x45, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"右小指1", "little1_R", {0x89, 0x45, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"右小指2", "little2_R", {0x89, 0x45, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"右小指3", "little3_R", {0x89, 0x45, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"右手首", "wrist_R", {0x89, 0x45, 0x8E, 0xE8, 0x8E, 0xF1, 0x00}},
{"右目", "eye_R", {0x89, 0x45, 0x96, 0xDA, 0x00}},
{"右肩", "shoulder_R", {0x89, 0x45, 0x8C, 0xA8, 0x00}},
{"右腕", "arm_R", {0x89, 0x45, 0x98, 0x72, 0x00}},
{"右薬指1", "third1_R", {0x89, 0x45, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"右薬指2", "third2_R", {0x89, 0x45, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"右薬指3", "third3_R", {0x89, 0x45, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"右袖", "sleeve_R", {0x89, 0x45, 0x91, 0xb3, 0x00}},
{"右袖先", "cuff_R", {0x89, 0x45, 0x91, 0xb3, 0x90, 0xe6, 0x00}},
{"右親指1", "thumb1_R", {0x89, 0x45, 0x90, 0x65, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"右親指2", "thumb2_R", {0x89, 0x45, 0x90, 0x65, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"右足", "leg_R", {0x89, 0x45, 0x91, 0xAB, 0x00}},
{"右足首", "ankle_R", {0x89, 0x45, 0x91, 0xAB, 0x8E, 0xF1, 0x00}},
{"右足IK", "leg_IK_R", {0x89, 0x45, 0x91, 0xAB, 0x82, 0x68, 0x82, 0x6A, 0x00}},
{"左つま先IK", "toe_IK_L", {0x8D, 0xB6, 0x82, 0xC2, 0x82, 0xDC, 0x90, 0xE6, 0x82, 0x68, 0x82, 0x6A, 0x00}},
{"左ひざ", "knee_L", {0x8D, 0xB6, 0x82, 0xD0, 0x82, 0xB4, 0x00}},
{"左ひじ", "elbow_L", {0x8D, 0xB6, 0x82, 0xD0, 0x82, 0xB6, 0x00}},
{"左中指1", "middle1_L", {0x8D, 0xB6, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"左中指2", "middle2_L", {0x8D, 0xB6, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"左中指3", "middle3_L", {0x8D, 0xB6, 0x92, 0x86, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"左人指1", "fore1_L", {0x8D, 0xB6, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"左人指2", "fore2_L", {0x8D, 0xB6, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"左人指3", "fore3_L", {0x8D, 0xB6, 0x90, 0x6C, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"左小指1", "little1_L", {0x8D, 0xB6, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"左小指2", "little2_L", {0x8D, 0xB6, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"左小指3", "little3_L", {0x8D, 0xB6, 0x8F, 0xAC, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"左手首", "wrist_L", {0x8D, 0xB6, 0x8E, 0xE8, 0x8E, 0xF1, 0x00}},
{"左目", "eye_L", {0x8D, 0xB6, 0x96, 0xDA, 0x00}},
{"左肩", "shoulder_L", {0x8D, 0xB6, 0x8C, 0xA8, 0x00}},
{"左腕", "arm_L", {0x8D, 0xB6, 0x98, 0x72, 0x00}},
{"左薬指1", "third1_L", {0x8D, 0xB6, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"左薬指2", "third2_L", {0x8D, 0xB6, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"左薬指3", "third3_L", {0x8D, 0xB6, 0x96, 0xF2, 0x8E, 0x77, 0x82, 0x52, 0x00}},
{"左袖", "sleeve_L", {0x8D, 0xB6, 0x91, 0xb3, 0x00}},
{"左袖先", "cuff_L", {0x8D, 0xB6, 0x91, 0xb3, 0x90, 0xe6, 0x00}},
{"左親指1", "thumb1_L", {0x8D, 0xB6, 0x90, 0x65, 0x8E, 0x77, 0x82, 0x50, 0x00}},
{"左親指2", "thumb2_L", {0x8D, 0xB6, 0x90, 0x65, 0x8E, 0x77, 0x82, 0x51, 0x00}},
{"左足", "leg_L", {0x8D, 0xB6, 0x91, 0xAB, 0x00}},
{"左足首", "ankle_L", {0x8D, 0xB6, 0x91, 0xAB, 0x8E, 0xF1, 0x00}},
{"左足IK", "leg_IK_L", {0x8D, 0xB6, 0x91, 0xAB, 0x82, 0x68, 0x82, 0x6A, 0x00}},
{"頭", "head", {0x93, 0xAA, 0x00}},
{"首", "neck", {0x8E, 0xF1, 0x00}},
};
typedef std::map<std::string, sjis_table_rec_t*> sjis_map_t;
sjis_map_t sjis_map;
std::set<std::string> unvisited_bones;
//
//
//
static bool ReadBytes(unsigned char *out_data, int size, FILE *fp) {
size_t sz;
sz = fread(out_data, 1, size, fp);
assert(sz == size);
return true;
}
static bool ParseBone(PMDModel *model, FILE *fp) {
unvisited_bones.clear();
for(sjis_map_t::iterator p = sjis_map.begin(); p != sjis_map.end(); p++) {
unvisited_bones.insert((*p).second->ascii_name);
}
// cp932 encoding of 'leg'(hi-za) in Japanese
const char kLegName[4 + 1] = {0x82, 0xd0, 0x82, 0xb4, 0x00}; // +1 for \0
unsigned short numBones;
ReadBytes(reinterpret_cast<unsigned char *>(&numBones),
sizeof(unsigned short), fp);
printf("[PMD] Num bones: %d\n", numBones);
assert(sizeof(PMDBone) == 39);
std::vector<PMDBone> pmdBones(numBones);
ReadBytes(reinterpret_cast<unsigned char *>(&(pmdBones[0])),
sizeof(PMDBone) * numBones, fp);
model->bones_.clear();
// Bone with name containing 'leg' in Japanese need special treatment
// when computing IK.
for (int i = 0; i < numBones; i++) {
Bone bone;
bone.parentIndex = pmdBones[i].parent_bone_index;
bone.tailIndex = pmdBones[i].tail_bone_index;
bone.type = pmdBones[i].bone_type;
bone.parentIndexIK = pmdBones[i].ik_parent_bone_index;
// printf("[PMD] [%d] parent %d, tail %d, ty %d, ik %d\n", i,
// pmdBones[i].parent_bone_index, pmdBones[i].tail_bone_index,
// pmdBones[i].bone_type, pmdBones[i].ik_parent_bone_index);
if (pmdBones[i].tail_bone_index == (unsigned short)(-1)) {
// skip
printf("[PMD] Bone [%d] is the tail. Skipping.\n", i);
continue;
}
bone.pos[0] = pmdBones[i].bone_pos[0];
bone.pos[1] = pmdBones[i].bone_pos[1];
bone.pos[2] = pmdBones[i].bone_pos[2];
bone.pos[3] = 1.0f;
char buf[21];
memcpy(buf, pmdBones[i].bone_name, 20);
buf[20] = '\0'; // add '\0' for safety
bone.name = std::string(buf);
if (bone.name.find(kLegName) != std::string::npos) {
printf("[PMD] Bone [%d] is leg\n", i);
bone.isLeg = true;
} else {
bone.isLeg = false;
}
sjis_map_t::iterator p = sjis_map.find(buf);
if (p != sjis_map.end()) {
bone.ascii_name = (*p).second->ascii_name;
std::set<std::string>::iterator q = unvisited_bones.find((*p).second->ascii_name);
if(q != unvisited_bones.end()) {
unvisited_bones.erase(q);
}
}
model->bones_.push_back(bone);
}
for(std::set<std::string>::iterator r = unvisited_bones.begin(); r != unvisited_bones.end(); r++) {
std::cout << "[PMD] Cannot find bone [ " << *r << " ] in PMD." << std::endl;
}
return true;
}
static bool ParseMorph(PMDModel *model, FILE *fp){
unsigned short numMorphs;
ReadBytes(reinterpret_cast<unsigned char *>(&numMorphs), sizeof(unsigned short),
fp);
printf("[PMD] Num Morphs: %d\n", numMorphs);
std::vector<Morph> morphs(numMorphs);
for (int i = 0; i < numMorphs; i++) {
PMDMorph pmdMorph;
ReadBytes(reinterpret_cast<unsigned char *>(&pmdMorph), sizeof(PMDMorph), fp);
std::vector<PMDMorphVertex> vertices(pmdMorph.vertex_count);
for (int j = 0; j < pmdMorph.vertex_count; j++){
ReadBytes(reinterpret_cast<unsigned char *>(&vertices[j]), sizeof(PMDMorphVertex), fp);
}
}
return true;
}
static bool ParseIK(PMDModel *model, FILE *fp) {
unsigned short numIKs;
ReadBytes(reinterpret_cast<unsigned char *>(&numIKs), sizeof(unsigned short),
fp);
printf("[PMD] Num IKs: %d\n", numIKs);
assert(sizeof(PMDIK) == 11);
std::vector<IK> iks(numIKs);
for (int i = 0; i < numIKs; i++) {
PMDIK pmdIK;
ReadBytes(reinterpret_cast<unsigned char *>(&pmdIK), sizeof(PMDIK), fp);
iks[i].boneIndex = pmdIK.bone_index;
iks[i].targetBoneIndex = pmdIK.target_bone_index;
iks[i].chainLength = pmdIK.chain_length;
iks[i].iterations = pmdIK.iterations;
iks[i].weight = pmdIK.weight;
iks[i].childBoneIndices.resize(iks[i].chainLength);
ReadBytes(reinterpret_cast<unsigned char *>(&(iks[i].childBoneIndices[0])),
sizeof(unsigned short) * iks[i].chainLength, fp);
}
model->iks_ = iks;
return true;
}
//
//
//
PMDReader::PMDReader() {
size_t n = sizeof(sjis_table)/sizeof(sjis_table_rec_t);
for(int i = 0; i < n; i++) {
// DBG
// wchar_t* unicode_name = (wchar_t*)sjis_table[i].unicode_name;
// char* ascii_name = sjis_table[i].ascii_name;
// wchar_t* sjis_name = (wchar_t*)sjis_table[i].sjis_name;
// printf("unicode_name: %ls, ascii_name: %s, sjis_name: %ls\n", unicode_name, ascii_name, sjis_name);
sjis_map.insert(sjis_map_t::value_type(sjis_table[i].sjis_name, &sjis_table[i]));
}
}
PMDReader::~PMDReader() {}
PMDModel *PMDReader::LoadFromFile(const std::string &filename) {
FILE *fp = fopen(filename.c_str(), "rb");
if (!fp) {
fprintf(stderr, "Can't read PMD file [ %s ]\n", filename.c_str());
return NULL;
}
PMDModel *model = new PMDModel();
// file header
{
const char kMagic[] = "Pmd";
const float kVersion = 1.0f; // 0x3F800000
char magic[3];
ReadBytes(reinterpret_cast<unsigned char *>(magic), 3, fp);
assert(magic[0] == kMagic[0]);
assert(magic[1] == kMagic[1]);
assert(magic[2] == kMagic[2]);
float version = 0.0f;
ReadBytes(reinterpret_cast<unsigned char *>(&version), 4, fp);
assert(version == kVersion);
model->version_ = version;
}
// name&comment
{
unsigned char name[20];
unsigned char comment[256];
ReadBytes(name, 20, fp);
ReadBytes(comment, 256, fp);
model->name_ = std::string(reinterpret_cast<char *>(name));
model->comment_ = std::string(reinterpret_cast<char *>(comment));
printf("[PMDReader] name = %s\n", model->name_.c_str());
printf("[PMDReader] comment = %s\n", model->comment_.c_str());
}
// Vertices
{
int numVertices;
ReadBytes(reinterpret_cast<unsigned char *>(&numVertices), 4, fp);
printf("[PMD] Num vertices: %d\n", numVertices);
assert(sizeof(PMDVertex) == 38);
model->vertices_.resize(numVertices);
ReadBytes(reinterpret_cast<unsigned char *>(&(model->vertices_[0])),
sizeof(PMDVertex) * numVertices, fp);
}
// Indices
{
int numIndices;
ReadBytes(reinterpret_cast<unsigned char *>(&numIndices), 4, fp);
printf("[PMD] Num indices: %d\n", numIndices);
model->indices_.resize(numIndices);
ReadBytes(reinterpret_cast<unsigned char *>(&(model->indices_[0])),
sizeof(unsigned short) * numIndices, fp);
// validate
for (int i = 0; i < numIndices; i++) {
assert(model->indices_[i] < model->vertices_.size());
}
}
// Materials
{
int numMaterials;
ReadBytes(reinterpret_cast<unsigned char *>(&numMaterials), 4, fp);
printf("[PMD] Num materials: %d\n", numMaterials);
assert(sizeof(PMDMaterial) == 70);
model->materials_.resize(numMaterials);
ReadBytes(reinterpret_cast<unsigned char *>(&(model->materials_[0])),
sizeof(PMDMaterial) * numMaterials, fp);
// validate
size_t sumVertexCount = 0;
for (int i = 0; i < numMaterials; i++) {
assert((model->materials_[i].vertex_count % 3) == 0);
sumVertexCount += model->materials_[i].vertex_count;
// DBG
// printf("mat[%d] texname = %s\n", i,
// model->materials_[i].texture_filename);
}
assert(sumVertexCount == model->indices_.size());
}
assert(ParseBone(model, fp));
assert(ParseIK(model, fp));
assert(ParseMorph(model, fp));
fclose(fp);
printf("[PMD] Load OK\n");
return model;
}
| 37.058824 | 107 | 0.614286 | [
"vector",
"model"
] |
f5142a0977201afa83279d974a71f963c152e290 | 60,945 | cc | C++ | src/processor/minidump_unittest.cc | TheOneRing/google-breakpad | 32f25a5c4a74578ce4f834f76f94fc706bfcdd9e | [
"BSD-3-Clause"
] | 1 | 2021-09-24T08:36:40.000Z | 2021-09-24T08:36:40.000Z | src/processor/minidump_unittest.cc | TheOneRing/google-breakpad | 32f25a5c4a74578ce4f834f76f94fc706bfcdd9e | [
"BSD-3-Clause"
] | 7 | 2020-04-12T05:15:59.000Z | 2022-01-24T20:48:53.000Z | src/processor/minidump_unittest.cc | TheOneRing/google-breakpad | 32f25a5c4a74578ce4f834f76f94fc706bfcdd9e | [
"BSD-3-Clause"
] | 2 | 2019-08-04T05:55:30.000Z | 2020-04-12T05:20:09.000Z | // Copyright (c) 2010, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Minidump. Uses a pre-generated minidump and
// verifies that certain streams are correct.
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <vector>
#include "breakpad_googletest_includes.h"
#include "common/using_std_string.h"
#include "google_breakpad/common/minidump_format.h"
#include "google_breakpad/processor/minidump.h"
#include "processor/logging.h"
#include "processor/synth_minidump.h"
namespace {
using google_breakpad::Minidump;
using google_breakpad::MinidumpContext;
using google_breakpad::MinidumpException;
using google_breakpad::MinidumpMemoryInfo;
using google_breakpad::MinidumpMemoryInfoList;
using google_breakpad::MinidumpMemoryList;
using google_breakpad::MinidumpMemoryRegion;
using google_breakpad::MinidumpModule;
using google_breakpad::MinidumpModuleList;
using google_breakpad::MinidumpSystemInfo;
using google_breakpad::MinidumpUnloadedModule;
using google_breakpad::MinidumpUnloadedModuleList;
using google_breakpad::MinidumpThread;
using google_breakpad::MinidumpThreadList;
using google_breakpad::SynthMinidump::Context;
using google_breakpad::SynthMinidump::Dump;
using google_breakpad::SynthMinidump::Exception;
using google_breakpad::SynthMinidump::Memory;
using google_breakpad::SynthMinidump::Module;
using google_breakpad::SynthMinidump::UnloadedModule;
using google_breakpad::SynthMinidump::Section;
using google_breakpad::SynthMinidump::Stream;
using google_breakpad::SynthMinidump::String;
using google_breakpad::SynthMinidump::SystemInfo;
using google_breakpad::SynthMinidump::Thread;
using google_breakpad::test_assembler::kBigEndian;
using google_breakpad::test_assembler::kLittleEndian;
using std::ifstream;
using std::istringstream;
using std::vector;
using ::testing::Return;
class MinidumpTest : public ::testing::Test {
public:
void SetUp() {
minidump_file_ = string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/processor/testdata/minidump2.dmp";
}
string minidump_file_;
};
TEST_F(MinidumpTest, TestMinidumpFromFile) {
Minidump minidump(minidump_file_);
ASSERT_EQ(minidump.path(), minidump_file_);
ASSERT_TRUE(minidump.Read());
const MDRawHeader* header = minidump.header();
ASSERT_NE(header, (MDRawHeader*)NULL);
ASSERT_EQ(header->signature, uint32_t(MD_HEADER_SIGNATURE));
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_module != NULL);
ASSERT_EQ("c:\\test_app.exe", md_module->code_file());
ASSERT_EQ("test_app.pdb", md_module->debug_file());
ASSERT_EQ("45D35F6C2d000", md_module->code_identifier());
ASSERT_EQ("5A9832E5287241C1838ED98914E9B7FF1", md_module->debug_identifier());
}
TEST_F(MinidumpTest, TestMinidumpFromStream) {
// read minidump contents into memory, construct a stringstream around them
ifstream file_stream(minidump_file_.c_str(), std::ios::in);
ASSERT_TRUE(file_stream.good());
vector<char> bytes;
file_stream.seekg(0, std::ios_base::end);
ASSERT_TRUE(file_stream.good());
bytes.resize(file_stream.tellg());
file_stream.seekg(0, std::ios_base::beg);
ASSERT_TRUE(file_stream.good());
file_stream.read(&bytes[0], bytes.size());
string str(&bytes[0], bytes.size());
istringstream stream(str);
ASSERT_TRUE(stream.good());
// now read minidump from stringstream
Minidump minidump(stream);
ASSERT_EQ(minidump.path(), "");
ASSERT_TRUE(minidump.Read());
const MDRawHeader* header = minidump.header();
ASSERT_NE(header, (MDRawHeader*)NULL);
ASSERT_EQ(header->signature, uint32_t(MD_HEADER_SIGNATURE));
//TODO: add more checks here
}
TEST(Dump, ReadBackEmpty) {
Dump dump(0);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream stream(contents);
Minidump minidump(stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(0U, minidump.GetDirectoryEntryCount());
}
TEST(Dump, ReadBackEmptyBigEndian) {
Dump big_minidump(0, kBigEndian);
big_minidump.Finish();
string contents;
ASSERT_TRUE(big_minidump.GetContents(&contents));
istringstream stream(contents);
Minidump minidump(stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(0U, minidump.GetDirectoryEntryCount());
}
TEST(Dump, OneStream) {
Dump dump(0, kBigEndian);
Stream stream(dump, 0xfbb7fa2bU);
stream.Append("stream contents");
dump.Add(&stream);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ(0xfbb7fa2bU, dir->stream_type);
uint32_t stream_length;
ASSERT_TRUE(minidump.SeekToStreamType(0xfbb7fa2bU, &stream_length));
ASSERT_EQ(15U, stream_length);
char stream_contents[15];
ASSERT_TRUE(minidump.ReadBytes(stream_contents, sizeof(stream_contents)));
EXPECT_EQ(string("stream contents"),
string(stream_contents, sizeof(stream_contents)));
EXPECT_FALSE(minidump.GetThreadList());
EXPECT_FALSE(minidump.GetModuleList());
EXPECT_FALSE(minidump.GetMemoryList());
EXPECT_FALSE(minidump.GetException());
EXPECT_FALSE(minidump.GetAssertion());
EXPECT_FALSE(minidump.GetSystemInfo());
EXPECT_FALSE(minidump.GetMiscInfo());
EXPECT_FALSE(minidump.GetBreakpadInfo());
}
TEST(Dump, OneMemory) {
Dump dump(0, kBigEndian);
Memory memory(dump, 0x309d68010bd21b2cULL);
memory.Append("memory contents");
dump.Add(&memory);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ((uint32_t) MD_MEMORY_LIST_STREAM, dir->stream_type);
MinidumpMemoryList *memory_list = minidump.GetMemoryList();
ASSERT_TRUE(memory_list != NULL);
ASSERT_EQ(1U, memory_list->region_count());
MinidumpMemoryRegion *region1 = memory_list->GetMemoryRegionAtIndex(0);
ASSERT_EQ(0x309d68010bd21b2cULL, region1->GetBase());
ASSERT_EQ(15U, region1->GetSize());
const uint8_t *region1_bytes = region1->GetMemory();
ASSERT_TRUE(memcmp("memory contents", region1_bytes, 15) == 0);
}
// One thread --- and its requisite entourage.
TEST(Dump, OneThread) {
Dump dump(0, kLittleEndian);
Memory stack(dump, 0x2326a0fa);
stack.Append("stack for thread");
MDRawContextX86 raw_context;
const uint32_t kExpectedEIP = 0x6913f540;
raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL;
raw_context.edi = 0x3ecba80d;
raw_context.esi = 0x382583b9;
raw_context.ebx = 0x7fccc03f;
raw_context.edx = 0xf62f8ec2;
raw_context.ecx = 0x46a6a6a8;
raw_context.eax = 0x6a5025e2;
raw_context.ebp = 0xd9fabb4a;
raw_context.eip = kExpectedEIP;
raw_context.cs = 0xbffe6eda;
raw_context.eflags = 0xb2ce1e2d;
raw_context.esp = 0x659caaa4;
raw_context.ss = 0x2e951ef7;
Context context(dump, raw_context);
Thread thread(dump, 0xa898f11b, stack, context,
0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL);
dump.Add(&stack);
dump.Add(&context);
dump.Add(&thread);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
MinidumpMemoryList *md_memory_list = minidump.GetMemoryList();
ASSERT_TRUE(md_memory_list != NULL);
ASSERT_EQ(1U, md_memory_list->region_count());
MinidumpMemoryRegion *md_region = md_memory_list->GetMemoryRegionAtIndex(0);
ASSERT_EQ(0x2326a0faU, md_region->GetBase());
ASSERT_EQ(16U, md_region->GetSize());
const uint8_t *region_bytes = md_region->GetMemory();
ASSERT_TRUE(memcmp("stack for thread", region_bytes, 16) == 0);
MinidumpThreadList *thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list != NULL);
ASSERT_EQ(1U, thread_list->thread_count());
MinidumpThread *md_thread = thread_list->GetThreadAtIndex(0);
ASSERT_TRUE(md_thread != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_thread->GetThreadID(&thread_id));
ASSERT_EQ(0xa898f11bU, thread_id);
MinidumpMemoryRegion *md_stack = md_thread->GetMemory();
ASSERT_TRUE(md_stack != NULL);
ASSERT_EQ(0x2326a0faU, md_stack->GetBase());
ASSERT_EQ(16U, md_stack->GetSize());
const uint8_t *md_stack_bytes = md_stack->GetMemory();
ASSERT_TRUE(memcmp("stack for thread", md_stack_bytes, 16) == 0);
MinidumpContext *md_context = md_thread->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_X86, md_context->GetContextCPU());
uint64_t eip;
ASSERT_TRUE(md_context->GetInstructionPointer(&eip));
EXPECT_EQ(kExpectedEIP, eip);
const MDRawContextX86 *md_raw_context = md_context->GetContextX86();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL),
(md_raw_context->context_flags
& (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL)));
EXPECT_EQ(0x3ecba80dU, raw_context.edi);
EXPECT_EQ(0x382583b9U, raw_context.esi);
EXPECT_EQ(0x7fccc03fU, raw_context.ebx);
EXPECT_EQ(0xf62f8ec2U, raw_context.edx);
EXPECT_EQ(0x46a6a6a8U, raw_context.ecx);
EXPECT_EQ(0x6a5025e2U, raw_context.eax);
EXPECT_EQ(0xd9fabb4aU, raw_context.ebp);
EXPECT_EQ(kExpectedEIP, raw_context.eip);
EXPECT_EQ(0xbffe6edaU, raw_context.cs);
EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags);
EXPECT_EQ(0x659caaa4U, raw_context.esp);
EXPECT_EQ(0x2e951ef7U, raw_context.ss);
}
TEST(Dump, ThreadMissingMemory) {
Dump dump(0, kLittleEndian);
Memory stack(dump, 0x2326a0fa);
// Stack has no contents.
MDRawContextX86 raw_context;
memset(&raw_context, 0, sizeof(raw_context));
raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL;
Context context(dump, raw_context);
Thread thread(dump, 0xa898f11b, stack, context,
0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL);
dump.Add(&stack);
dump.Add(&context);
dump.Add(&thread);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
// This should succeed even though the thread has no stack memory.
MinidumpThreadList* thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list != NULL);
ASSERT_EQ(1U, thread_list->thread_count());
MinidumpThread* md_thread = thread_list->GetThreadAtIndex(0);
ASSERT_TRUE(md_thread != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_thread->GetThreadID(&thread_id));
ASSERT_EQ(0xa898f11bU, thread_id);
MinidumpContext* md_context = md_thread->GetContext();
ASSERT_NE(reinterpret_cast<MinidumpContext*>(NULL), md_context);
MinidumpMemoryRegion* md_stack = md_thread->GetMemory();
ASSERT_EQ(reinterpret_cast<MinidumpMemoryRegion*>(NULL), md_stack);
}
TEST(Dump, ThreadMissingContext) {
Dump dump(0, kLittleEndian);
Memory stack(dump, 0x2326a0fa);
stack.Append("stack for thread");
// Context is empty.
Context context(dump);
Thread thread(dump, 0xa898f11b, stack, context,
0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL);
dump.Add(&stack);
dump.Add(&context);
dump.Add(&thread);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
// This should succeed even though the thread has no stack memory.
MinidumpThreadList* thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list != NULL);
ASSERT_EQ(1U, thread_list->thread_count());
MinidumpThread* md_thread = thread_list->GetThreadAtIndex(0);
ASSERT_TRUE(md_thread != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_thread->GetThreadID(&thread_id));
ASSERT_EQ(0xa898f11bU, thread_id);
MinidumpMemoryRegion* md_stack = md_thread->GetMemory();
ASSERT_NE(reinterpret_cast<MinidumpMemoryRegion*>(NULL), md_stack);
MinidumpContext* md_context = md_thread->GetContext();
ASSERT_EQ(reinterpret_cast<MinidumpContext*>(NULL), md_context);
}
TEST(Dump, OneUnloadedModule) {
Dump dump(0, kBigEndian);
String module_name(dump, "unloaded module");
String csd_version(dump, "Windows 9000");
SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version);
UnloadedModule unloaded_module(
dump,
0xa90206ca83eb2852ULL,
0xada542bd,
module_name,
0x34571371,
0xb1054d2a);
dump.Add(&unloaded_module);
dump.Add(&module_name);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(1);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ((uint32_t) MD_UNLOADED_MODULE_LIST_STREAM, dir->stream_type);
MinidumpUnloadedModuleList *md_unloaded_module_list =
minidump.GetUnloadedModuleList();
ASSERT_TRUE(md_unloaded_module_list != NULL);
ASSERT_EQ(1U, md_unloaded_module_list->module_count());
const MinidumpUnloadedModule *md_unloaded_module =
md_unloaded_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_unloaded_module != NULL);
ASSERT_EQ(0xa90206ca83eb2852ULL, md_unloaded_module->base_address());
ASSERT_EQ(0xada542bd, md_unloaded_module->size());
ASSERT_EQ("unloaded module", md_unloaded_module->code_file());
ASSERT_EQ("", md_unloaded_module->debug_file());
// time_date_stamp and size_of_image concatenated
ASSERT_EQ("B1054D2Aada542bd", md_unloaded_module->code_identifier());
ASSERT_EQ("", md_unloaded_module->debug_identifier());
const MDRawUnloadedModule *md_raw_unloaded_module =
md_unloaded_module->module();
ASSERT_TRUE(md_raw_unloaded_module != NULL);
ASSERT_EQ(0xb1054d2aU, md_raw_unloaded_module->time_date_stamp);
ASSERT_EQ(0x34571371U, md_raw_unloaded_module->checksum);
}
static const MDVSFixedFileInfo fixed_file_info = {
0xb2fba33a, // signature
0x33d7a728, // struct_version
0x31afcb20, // file_version_hi
0xe51cdab1, // file_version_lo
0xd1ea6907, // product_version_hi
0x03032857, // product_version_lo
0x11bf71d7, // file_flags_mask
0x5fb8cdbf, // file_flags
0xe45d0d5d, // file_os
0x107d9562, // file_type
0x5a8844d4, // file_subtype
0xa8d30b20, // file_date_hi
0x651c3e4e // file_date_lo
};
TEST(Dump, OneModule) {
Dump dump(0, kBigEndian);
String module_name(dump, "single module");
Section cv_info(dump);
cv_info
.D32(MD_CVINFOPDB70_SIGNATURE) // signature
// signature, a MDGUID
.D32(0xabcd1234)
.D16(0xf00d)
.D16(0xbeef)
.Append("\x01\x02\x03\x04\x05\x06\x07\x08")
.D32(1) // age
.AppendCString("c:\\foo\\file.pdb"); // pdb_file_name
String csd_version(dump, "Windows 9000");
SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version);
Module module(dump, 0xa90206ca83eb2852ULL, 0xada542bd,
module_name,
0xb1054d2a,
0x34571371,
fixed_file_info, // from synth_minidump_unittest_data.h
&cv_info, nullptr);
dump.Add(&module);
dump.Add(&module_name);
dump.Add(&cv_info);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(1);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ((uint32_t) MD_MODULE_LIST_STREAM, dir->stream_type);
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
ASSERT_EQ(1U, md_module_list->module_count());
const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_module != NULL);
ASSERT_EQ(0xa90206ca83eb2852ULL, md_module->base_address());
ASSERT_EQ(0xada542bd, md_module->size());
ASSERT_EQ("single module", md_module->code_file());
ASSERT_EQ("file.pdb", md_module->debug_file());
// time_date_stamp and size_of_image concatenated
ASSERT_EQ("B1054D2Aada542bd", md_module->code_identifier());
ASSERT_EQ("ABCD1234F00DBEEF01020304050607081", md_module->debug_identifier());
const MDRawModule *md_raw_module = md_module->module();
ASSERT_TRUE(md_raw_module != NULL);
ASSERT_EQ(0xb1054d2aU, md_raw_module->time_date_stamp);
ASSERT_EQ(0x34571371U, md_raw_module->checksum);
ASSERT_TRUE(memcmp(&md_raw_module->version_info, &fixed_file_info,
sizeof(fixed_file_info)) == 0);
}
// Test that a module with a MDCVInfoELF CV record is handled properly.
TEST(Dump, OneModuleCVELF) {
Dump dump(0, kLittleEndian);
String module_name(dump, "elf module");
Section cv_info(dump);
cv_info
.D32(MD_CVINFOELF_SIGNATURE) // signature
// build_id
.Append("\x5f\xa9\xcd\xb4\x10\x53\xdf\x1b\x86\xfa\xb7\x33\xb4\xdf"
"\x37\x38\xce\xa3\x4a\x87");
const MDRawSystemInfo linux_x86 = {
MD_CPU_ARCHITECTURE_X86, // processor_architecture
6, // processor_level
0xd08, // processor_revision
1, // number_of_processors
0, // product_type
0, // major_version
0, // minor_version
0, // build_number
MD_OS_LINUX, // platform_id
0xdeadbeef, // csd_version_rva
0x100, // suite_mask
0, // reserved2
{ // cpu
{ // x86_cpu_info
{ 0x756e6547, 0x49656e69, 0x6c65746e }, // vendor_id
0x6d8, // version_information
0xafe9fbff, // feature_information
0xffffffff // amd_extended_cpu_features
}
}
};
String csd_version(dump, "Literally Linux");
SystemInfo system_info(dump, linux_x86, csd_version);
Module module(dump, 0xa90206ca83eb2852ULL, 0xada542bd,
module_name,
0xb1054d2a,
0x34571371,
fixed_file_info, // from synth_minidump_unittest_data.h
&cv_info, nullptr);
dump.Add(&module);
dump.Add(&module_name);
dump.Add(&cv_info);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
ASSERT_EQ(1U, md_module_list->module_count());
const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_module != NULL);
ASSERT_EQ(0xa90206ca83eb2852ULL, md_module->base_address());
ASSERT_EQ(0xada542bd, md_module->size());
ASSERT_EQ("elf module", md_module->code_file());
// debug_file == code_file
ASSERT_EQ("elf module", md_module->debug_file());
// just the build_id, directly
ASSERT_EQ("5fa9cdb41053df1b86fab733b4df3738cea34a87",
md_module->code_identifier());
// build_id truncted to GUID length and treated as such, with zero
// age appended
ASSERT_EQ("B4CDA95F53101BDF86FAB733B4DF37380", md_module->debug_identifier());
const MDRawModule *md_raw_module = md_module->module();
ASSERT_TRUE(md_raw_module != NULL);
ASSERT_EQ(0xb1054d2aU, md_raw_module->time_date_stamp);
ASSERT_EQ(0x34571371U, md_raw_module->checksum);
ASSERT_TRUE(memcmp(&md_raw_module->version_info, &fixed_file_info,
sizeof(fixed_file_info)) == 0);
}
// Test that a build_id that's shorter than a GUID is handled properly.
TEST(Dump, CVELFShort) {
Dump dump(0, kLittleEndian);
String module_name(dump, "elf module");
Section cv_info(dump);
cv_info
.D32(MD_CVINFOELF_SIGNATURE) // signature
// build_id, shorter than a GUID
.Append("\x5f\xa9\xcd\xb4");
const MDRawSystemInfo linux_x86 = {
MD_CPU_ARCHITECTURE_X86, // processor_architecture
6, // processor_level
0xd08, // processor_revision
1, // number_of_processors
0, // product_type
0, // major_version
0, // minor_version
0, // build_number
MD_OS_LINUX, // platform_id
0xdeadbeef, // csd_version_rva
0x100, // suite_mask
0, // reserved2
{ // cpu
{ // x86_cpu_info
{ 0x756e6547, 0x49656e69, 0x6c65746e }, // vendor_id
0x6d8, // version_information
0xafe9fbff, // feature_information
0xffffffff // amd_extended_cpu_features
}
}
};
String csd_version(dump, "Literally Linux");
SystemInfo system_info(dump, linux_x86, csd_version);
Module module(dump, 0xa90206ca83eb2852ULL, 0xada542bd,
module_name,
0xb1054d2a,
0x34571371,
fixed_file_info, // from synth_minidump_unittest_data.h
&cv_info, nullptr);
dump.Add(&module);
dump.Add(&module_name);
dump.Add(&cv_info);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
ASSERT_EQ(1U, md_module_list->module_count());
const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_module != NULL);
// just the build_id, directly
ASSERT_EQ("5fa9cdb4", md_module->code_identifier());
// build_id expanded to GUID length and treated as such, with zero
// age appended
ASSERT_EQ("B4CDA95F0000000000000000000000000", md_module->debug_identifier());
}
// Test that a build_id that's very long is handled properly.
TEST(Dump, CVELFLong) {
Dump dump(0, kLittleEndian);
String module_name(dump, "elf module");
Section cv_info(dump);
cv_info
.D32(MD_CVINFOELF_SIGNATURE) // signature
// build_id, lots of bytes
.Append("\x5f\xa9\xcd\xb4\x10\x53\xdf\x1b\x86\xfa\xb7\x33\xb4\xdf"
"\x37\x38\xce\xa3\x4a\x87\x01\x02\x03\x04\x05\x06\x07\x08"
"\x09\x0a\x0b\x0c\x0d\x0e\x0f");
const MDRawSystemInfo linux_x86 = {
MD_CPU_ARCHITECTURE_X86, // processor_architecture
6, // processor_level
0xd08, // processor_revision
1, // number_of_processors
0, // product_type
0, // major_version
0, // minor_version
0, // build_number
MD_OS_LINUX, // platform_id
0xdeadbeef, // csd_version_rva
0x100, // suite_mask
0, // reserved2
{ // cpu
{ // x86_cpu_info
{ 0x756e6547, 0x49656e69, 0x6c65746e }, // vendor_id
0x6d8, // version_information
0xafe9fbff, // feature_information
0xffffffff // amd_extended_cpu_features
}
}
};
String csd_version(dump, "Literally Linux");
SystemInfo system_info(dump, linux_x86, csd_version);
Module module(dump, 0xa90206ca83eb2852ULL, 0xada542bd,
module_name,
0xb1054d2a,
0x34571371,
fixed_file_info, // from synth_minidump_unittest_data.h
&cv_info, nullptr);
dump.Add(&module);
dump.Add(&module_name);
dump.Add(&cv_info);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
ASSERT_EQ(1U, md_module_list->module_count());
const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0);
ASSERT_TRUE(md_module != NULL);
// just the build_id, directly
ASSERT_EQ(
"5fa9cdb41053df1b86fab733b4df3738cea34a870102030405060708090a0b0c0d0e0f",
md_module->code_identifier());
// build_id truncated to GUID length and treated as such, with zero
// age appended.
ASSERT_EQ("B4CDA95F53101BDF86FAB733B4DF37380", md_module->debug_identifier());
}
TEST(Dump, OneSystemInfo) {
Dump dump(0, kLittleEndian);
String csd_version(dump, "Petulant Pierogi");
SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ((uint32_t) MD_SYSTEM_INFO_STREAM, dir->stream_type);
MinidumpSystemInfo *md_system_info = minidump.GetSystemInfo();
ASSERT_TRUE(md_system_info != NULL);
ASSERT_EQ("windows", md_system_info->GetOS());
ASSERT_EQ("x86", md_system_info->GetCPU());
ASSERT_EQ("Petulant Pierogi", *md_system_info->GetCSDVersion());
ASSERT_EQ("GenuineIntel", *md_system_info->GetCPUVendor());
}
TEST(Dump, BigDump) {
Dump dump(0, kLittleEndian);
// A SystemInfo stream.
String csd_version(dump, "Munificent Macaque");
SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version);
dump.Add(&csd_version);
dump.Add(&system_info);
// Five threads!
Memory stack0(dump, 0x70b9ebfc);
stack0.Append("stack for thread zero");
MDRawContextX86 raw_context0;
raw_context0.context_flags = MD_CONTEXT_X86_INTEGER;
raw_context0.eip = 0xaf0709e4;
Context context0(dump, raw_context0);
Thread thread0(dump, 0xbbef4432, stack0, context0,
0xd0377e7b, 0xdb8eb0cf, 0xd73bc314, 0x09d357bac7f9a163ULL);
dump.Add(&stack0);
dump.Add(&context0);
dump.Add(&thread0);
Memory stack1(dump, 0xf988cc45);
stack1.Append("stack for thread one");
MDRawContextX86 raw_context1;
raw_context1.context_flags = MD_CONTEXT_X86_INTEGER;
raw_context1.eip = 0xe4f56f81;
Context context1(dump, raw_context1);
Thread thread1(dump, 0x657c3f58, stack1, context1,
0xa68fa182, 0x6f3cf8dd, 0xe3a78ccf, 0x78cc84775e4534bbULL);
dump.Add(&stack1);
dump.Add(&context1);
dump.Add(&thread1);
Memory stack2(dump, 0xc8a92e7c);
stack2.Append("stack for thread two");
MDRawContextX86 raw_context2;
raw_context2.context_flags = MD_CONTEXT_X86_INTEGER;
raw_context2.eip = 0xb336a438;
Context context2(dump, raw_context2);
Thread thread2(dump, 0xdf4b8a71, stack2, context2,
0x674c26b6, 0x445d7120, 0x7e700c56, 0xd89bf778e7793e17ULL);
dump.Add(&stack2);
dump.Add(&context2);
dump.Add(&thread2);
Memory stack3(dump, 0x36d08e08);
stack3.Append("stack for thread three");
MDRawContextX86 raw_context3;
raw_context3.context_flags = MD_CONTEXT_X86_INTEGER;
raw_context3.eip = 0xdf99a60c;
Context context3(dump, raw_context3);
Thread thread3(dump, 0x86e6c341, stack3, context3,
0x32dc5c55, 0x17a2aba8, 0xe0cc75e7, 0xa46393994dae83aeULL);
dump.Add(&stack3);
dump.Add(&context3);
dump.Add(&thread3);
Memory stack4(dump, 0x1e0ab4fa);
stack4.Append("stack for thread four");
MDRawContextX86 raw_context4;
raw_context4.context_flags = MD_CONTEXT_X86_INTEGER;
raw_context4.eip = 0xaa646267;
Context context4(dump, raw_context4);
Thread thread4(dump, 0x261a28d4, stack4, context4,
0x6ebd389e, 0xa0cd4759, 0x30168846, 0x164f650a0cf39d35ULL);
dump.Add(&stack4);
dump.Add(&context4);
dump.Add(&thread4);
// Three modules!
String module1_name(dump, "module one");
Module module1(dump, 0xeb77da57b5d4cbdaULL, 0x83cd5a37, module1_name);
dump.Add(&module1_name);
dump.Add(&module1);
String module2_name(dump, "module two");
Module module2(dump, 0x8675884adfe5ac90ULL, 0xb11e4ea3, module2_name);
dump.Add(&module2_name);
dump.Add(&module2);
String module3_name(dump, "module three");
Module module3(dump, 0x95fc1544da321b6cULL, 0x7c2bf081, module3_name);
dump.Add(&module3_name);
dump.Add(&module3);
// Unloaded modules!
uint64_t umodule1_base = 0xeb77da57b5d4cbdaULL;
uint32_t umodule1_size = 0x83cd5a37;
String umodule1_name(dump, "unloaded module one");
UnloadedModule unloaded_module1(dump, umodule1_base, umodule1_size,
umodule1_name);
dump.Add(&umodule1_name);
dump.Add(&unloaded_module1);
uint64_t umodule2_base = 0xeb77da57b5d4cbdaULL;
uint32_t umodule2_size = 0x83cd5a37;
String umodule2_name(dump, "unloaded module two");
UnloadedModule unloaded_module2(dump, umodule2_base, umodule2_size,
umodule2_name);
dump.Add(&umodule2_name);
dump.Add(&unloaded_module2);
uint64_t umodule3_base = 0xeb77da5839a20000ULL;
uint32_t umodule3_size = 0x83cd5a37;
String umodule3_name(dump, "unloaded module three");
UnloadedModule unloaded_module3(dump, umodule3_base, umodule3_size,
umodule3_name);
dump.Add(&umodule3_name);
dump.Add(&unloaded_module3);
// Add one more memory region, on top of the five stacks.
Memory memory5(dump, 0x61979e828040e564ULL);
memory5.Append("contents of memory 5");
dump.Add(&memory5);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(5U, minidump.GetDirectoryEntryCount());
// Check the threads.
MinidumpThreadList *thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list != NULL);
ASSERT_EQ(5U, thread_list->thread_count());
uint32_t thread_id;
ASSERT_TRUE(thread_list->GetThreadAtIndex(0)->GetThreadID(&thread_id));
ASSERT_EQ(0xbbef4432U, thread_id);
ASSERT_EQ(0x70b9ebfcU,
thread_list->GetThreadAtIndex(0)->GetMemory()->GetBase());
ASSERT_EQ(0xaf0709e4U,
thread_list->GetThreadAtIndex(0)->GetContext()->GetContextX86()
->eip);
ASSERT_TRUE(thread_list->GetThreadAtIndex(1)->GetThreadID(&thread_id));
ASSERT_EQ(0x657c3f58U, thread_id);
ASSERT_EQ(0xf988cc45U,
thread_list->GetThreadAtIndex(1)->GetMemory()->GetBase());
ASSERT_EQ(0xe4f56f81U,
thread_list->GetThreadAtIndex(1)->GetContext()->GetContextX86()
->eip);
ASSERT_TRUE(thread_list->GetThreadAtIndex(2)->GetThreadID(&thread_id));
ASSERT_EQ(0xdf4b8a71U, thread_id);
ASSERT_EQ(0xc8a92e7cU,
thread_list->GetThreadAtIndex(2)->GetMemory()->GetBase());
ASSERT_EQ(0xb336a438U,
thread_list->GetThreadAtIndex(2)->GetContext()->GetContextX86()
->eip);
ASSERT_TRUE(thread_list->GetThreadAtIndex(3)->GetThreadID(&thread_id));
ASSERT_EQ(0x86e6c341U, thread_id);
ASSERT_EQ(0x36d08e08U,
thread_list->GetThreadAtIndex(3)->GetMemory()->GetBase());
ASSERT_EQ(0xdf99a60cU,
thread_list->GetThreadAtIndex(3)->GetContext()->GetContextX86()
->eip);
ASSERT_TRUE(thread_list->GetThreadAtIndex(4)->GetThreadID(&thread_id));
ASSERT_EQ(0x261a28d4U, thread_id);
ASSERT_EQ(0x1e0ab4faU,
thread_list->GetThreadAtIndex(4)->GetMemory()->GetBase());
ASSERT_EQ(0xaa646267U,
thread_list->GetThreadAtIndex(4)->GetContext()->GetContextX86()
->eip);
// Check the modules.
MinidumpModuleList *md_module_list = minidump.GetModuleList();
ASSERT_TRUE(md_module_list != NULL);
ASSERT_EQ(3U, md_module_list->module_count());
EXPECT_EQ(0xeb77da57b5d4cbdaULL,
md_module_list->GetModuleAtIndex(0)->base_address());
EXPECT_EQ(0x8675884adfe5ac90ULL,
md_module_list->GetModuleAtIndex(1)->base_address());
EXPECT_EQ(0x95fc1544da321b6cULL,
md_module_list->GetModuleAtIndex(2)->base_address());
// Check unloaded modules
MinidumpUnloadedModuleList *md_unloaded_module_list =
minidump.GetUnloadedModuleList();
ASSERT_TRUE(md_unloaded_module_list != NULL);
ASSERT_EQ(3U, md_unloaded_module_list->module_count());
EXPECT_EQ(umodule1_base,
md_unloaded_module_list->GetModuleAtIndex(0)->base_address());
EXPECT_EQ(umodule2_base,
md_unloaded_module_list->GetModuleAtIndex(1)->base_address());
EXPECT_EQ(umodule3_base,
md_unloaded_module_list->GetModuleAtIndex(2)->base_address());
const MinidumpUnloadedModule *umodule =
md_unloaded_module_list->GetModuleForAddress(
umodule1_base + umodule1_size / 2);
EXPECT_EQ(umodule1_base, umodule->base_address());
umodule = md_unloaded_module_list->GetModuleAtSequence(0);
EXPECT_EQ(umodule1_base, umodule->base_address());
EXPECT_EQ(NULL, md_unloaded_module_list->GetMainModule());
}
TEST(Dump, OneMemoryInfo) {
Dump dump(0, kBigEndian);
Stream stream(dump, MD_MEMORY_INFO_LIST_STREAM);
// Add the MDRawMemoryInfoList header.
const uint64_t kNumberOfEntries = 1;
stream.D32(sizeof(MDRawMemoryInfoList)) // size_of_header
.D32(sizeof(MDRawMemoryInfo)) // size_of_entry
.D64(kNumberOfEntries); // number_of_entries
// Now add a MDRawMemoryInfo entry.
const uint64_t kBaseAddress = 0x1000;
const uint64_t kRegionSize = 0x2000;
stream.D64(kBaseAddress) // base_address
.D64(kBaseAddress) // allocation_base
.D32(MD_MEMORY_PROTECT_EXECUTE_READWRITE) // allocation_protection
.D32(0) // __alignment1
.D64(kRegionSize) // region_size
.D32(MD_MEMORY_STATE_COMMIT) // state
.D32(MD_MEMORY_PROTECT_EXECUTE_READWRITE) // protection
.D32(MD_MEMORY_TYPE_PRIVATE) // type
.D32(0); // __alignment2
dump.Add(&stream);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0);
ASSERT_TRUE(dir != NULL);
EXPECT_EQ((uint32_t) MD_MEMORY_INFO_LIST_STREAM, dir->stream_type);
MinidumpMemoryInfoList *info_list = minidump.GetMemoryInfoList();
ASSERT_TRUE(info_list != NULL);
ASSERT_EQ(1U, info_list->info_count());
const MinidumpMemoryInfo *info1 = info_list->GetMemoryInfoAtIndex(0);
ASSERT_EQ(kBaseAddress, info1->GetBase());
ASSERT_EQ(kRegionSize, info1->GetSize());
ASSERT_TRUE(info1->IsExecutable());
ASSERT_TRUE(info1->IsWritable());
// Should get back the same memory region here.
const MinidumpMemoryInfo *info2 =
info_list->GetMemoryInfoForAddress(kBaseAddress + kRegionSize / 2);
ASSERT_EQ(kBaseAddress, info2->GetBase());
ASSERT_EQ(kRegionSize, info2->GetSize());
}
TEST(Dump, OneExceptionX86) {
Dump dump(0, kLittleEndian);
MDRawContextX86 raw_context;
raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL;
raw_context.edi = 0x3ecba80d;
raw_context.esi = 0x382583b9;
raw_context.ebx = 0x7fccc03f;
raw_context.edx = 0xf62f8ec2;
raw_context.ecx = 0x46a6a6a8;
raw_context.eax = 0x6a5025e2;
raw_context.ebp = 0xd9fabb4a;
raw_context.eip = 0x6913f540;
raw_context.cs = 0xbffe6eda;
raw_context.eflags = 0xb2ce1e2d;
raw_context.esp = 0x659caaa4;
raw_context.ss = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_X86, md_context->GetContextCPU());
const MDRawContextX86 *md_raw_context = md_context->GetContextX86();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL),
(md_raw_context->context_flags
& (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL)));
EXPECT_EQ(0x3ecba80dU, raw_context.edi);
EXPECT_EQ(0x382583b9U, raw_context.esi);
EXPECT_EQ(0x7fccc03fU, raw_context.ebx);
EXPECT_EQ(0xf62f8ec2U, raw_context.edx);
EXPECT_EQ(0x46a6a6a8U, raw_context.ecx);
EXPECT_EQ(0x6a5025e2U, raw_context.eax);
EXPECT_EQ(0xd9fabb4aU, raw_context.ebp);
EXPECT_EQ(0x6913f540U, raw_context.eip);
EXPECT_EQ(0xbffe6edaU, raw_context.cs);
EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags);
EXPECT_EQ(0x659caaa4U, raw_context.esp);
EXPECT_EQ(0x2e951ef7U, raw_context.ss);
}
TEST(Dump, OneExceptionX86XState) {
Dump dump(0, kLittleEndian);
MDRawContextX86 raw_context;
raw_context.context_flags = MD_CONTEXT_X86_INTEGER |
MD_CONTEXT_X86_CONTROL | MD_CONTEXT_X86_XSTATE;
raw_context.edi = 0x3ecba80d;
raw_context.esi = 0x382583b9;
raw_context.ebx = 0x7fccc03f;
raw_context.edx = 0xf62f8ec2;
raw_context.ecx = 0x46a6a6a8;
raw_context.eax = 0x6a5025e2;
raw_context.ebp = 0xd9fabb4a;
raw_context.eip = 0x6913f540;
raw_context.cs = 0xbffe6eda;
raw_context.eflags = 0xb2ce1e2d;
raw_context.esp = 0x659caaa4;
raw_context.ss = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_X86, md_context->GetContextCPU());
const MDRawContextX86 *md_raw_context = md_context->GetContextX86();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL),
(md_raw_context->context_flags
& (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL)));
EXPECT_EQ(0x3ecba80dU, raw_context.edi);
EXPECT_EQ(0x382583b9U, raw_context.esi);
EXPECT_EQ(0x7fccc03fU, raw_context.ebx);
EXPECT_EQ(0xf62f8ec2U, raw_context.edx);
EXPECT_EQ(0x46a6a6a8U, raw_context.ecx);
EXPECT_EQ(0x6a5025e2U, raw_context.eax);
EXPECT_EQ(0xd9fabb4aU, raw_context.ebp);
EXPECT_EQ(0x6913f540U, raw_context.eip);
EXPECT_EQ(0xbffe6edaU, raw_context.cs);
EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags);
EXPECT_EQ(0x659caaa4U, raw_context.esp);
EXPECT_EQ(0x2e951ef7U, raw_context.ss);
}
// Testing that the CPU type can be loaded from a system info stream when
// the CPU flags are missing from the context_flags of an exception record
TEST(Dump, OneExceptionX86NoCPUFlags) {
Dump dump(0, kLittleEndian);
MDRawContextX86 raw_context;
// Intentionally not setting CPU type in the context_flags
raw_context.context_flags = 0;
raw_context.edi = 0x3ecba80d;
raw_context.esi = 0x382583b9;
raw_context.ebx = 0x7fccc03f;
raw_context.edx = 0xf62f8ec2;
raw_context.ecx = 0x46a6a6a8;
raw_context.eax = 0x6a5025e2;
raw_context.ebp = 0xd9fabb4a;
raw_context.eip = 0x6913f540;
raw_context.cs = 0xbffe6eda;
raw_context.eflags = 0xb2ce1e2d;
raw_context.esp = 0x659caaa4;
raw_context.ss = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
// Add system info. This is needed as an alternative source for CPU type
// information. Note, that the CPU flags were intentionally skipped from
// the context_flags and this alternative source is required.
String csd_version(dump, "Service Pack 2");
SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version);
dump.Add(&system_info);
dump.Add(&csd_version);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(2U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_X86, md_context->GetContextCPU());
const MDRawContextX86 *md_raw_context = md_context->GetContextX86();
ASSERT_TRUE(md_raw_context != NULL);
// Even though the CPU flags were missing from the context_flags, the
// GetContext call above is expected to load the missing CPU flags from the
// system info stream and set the CPU type bits in context_flags.
ASSERT_EQ((uint32_t) (MD_CONTEXT_X86), md_raw_context->context_flags);
EXPECT_EQ(0x3ecba80dU, raw_context.edi);
EXPECT_EQ(0x382583b9U, raw_context.esi);
EXPECT_EQ(0x7fccc03fU, raw_context.ebx);
EXPECT_EQ(0xf62f8ec2U, raw_context.edx);
EXPECT_EQ(0x46a6a6a8U, raw_context.ecx);
EXPECT_EQ(0x6a5025e2U, raw_context.eax);
EXPECT_EQ(0xd9fabb4aU, raw_context.ebp);
EXPECT_EQ(0x6913f540U, raw_context.eip);
EXPECT_EQ(0xbffe6edaU, raw_context.cs);
EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags);
EXPECT_EQ(0x659caaa4U, raw_context.esp);
EXPECT_EQ(0x2e951ef7U, raw_context.ss);
}
// This test covers a scenario where a dump contains an exception but the
// context record of the exception is missing the CPU type information in its
// context_flags. The dump has no system info stream so it is imposible to
// deduce the CPU type, hence the context record is unusable.
TEST(Dump, OneExceptionX86NoCPUFlagsNoSystemInfo) {
Dump dump(0, kLittleEndian);
MDRawContextX86 raw_context;
// Intentionally not setting CPU type in the context_flags
raw_context.context_flags = 0;
raw_context.edi = 0x3ecba80d;
raw_context.esi = 0x382583b9;
raw_context.ebx = 0x7fccc03f;
raw_context.edx = 0xf62f8ec2;
raw_context.ecx = 0x46a6a6a8;
raw_context.eax = 0x6a5025e2;
raw_context.ebp = 0xd9fabb4a;
raw_context.eip = 0x6913f540;
raw_context.cs = 0xbffe6eda;
raw_context.eflags = 0xb2ce1e2d;
raw_context.esp = 0x659caaa4;
raw_context.ss = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
// The context record of the exception is unusable because the context_flags
// don't have CPU type information and at the same time the minidump lacks
// system info stream so it is impossible to deduce the CPU type.
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_EQ(NULL, md_context);
}
TEST(Dump, OneExceptionARM) {
Dump dump(0, kLittleEndian);
MDRawContextARM raw_context;
raw_context.context_flags = MD_CONTEXT_ARM_INTEGER;
raw_context.iregs[0] = 0x3ecba80d;
raw_context.iregs[1] = 0x382583b9;
raw_context.iregs[2] = 0x7fccc03f;
raw_context.iregs[3] = 0xf62f8ec2;
raw_context.iregs[4] = 0x46a6a6a8;
raw_context.iregs[5] = 0x6a5025e2;
raw_context.iregs[6] = 0xd9fabb4a;
raw_context.iregs[7] = 0x6913f540;
raw_context.iregs[8] = 0xbffe6eda;
raw_context.iregs[9] = 0xb2ce1e2d;
raw_context.iregs[10] = 0x659caaa4;
raw_context.iregs[11] = 0xf0e0d0c0;
raw_context.iregs[12] = 0xa9b8c7d6;
raw_context.iregs[13] = 0x12345678;
raw_context.iregs[14] = 0xabcd1234;
raw_context.iregs[15] = 0x10203040;
raw_context.cpsr = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_ARM, md_context->GetContextCPU());
const MDRawContextARM *md_raw_context = md_context->GetContextARM();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_ARM_INTEGER,
(md_raw_context->context_flags
& MD_CONTEXT_ARM_INTEGER));
EXPECT_EQ(0x3ecba80dU, raw_context.iregs[0]);
EXPECT_EQ(0x382583b9U, raw_context.iregs[1]);
EXPECT_EQ(0x7fccc03fU, raw_context.iregs[2]);
EXPECT_EQ(0xf62f8ec2U, raw_context.iregs[3]);
EXPECT_EQ(0x46a6a6a8U, raw_context.iregs[4]);
EXPECT_EQ(0x6a5025e2U, raw_context.iregs[5]);
EXPECT_EQ(0xd9fabb4aU, raw_context.iregs[6]);
EXPECT_EQ(0x6913f540U, raw_context.iregs[7]);
EXPECT_EQ(0xbffe6edaU, raw_context.iregs[8]);
EXPECT_EQ(0xb2ce1e2dU, raw_context.iregs[9]);
EXPECT_EQ(0x659caaa4U, raw_context.iregs[10]);
EXPECT_EQ(0xf0e0d0c0U, raw_context.iregs[11]);
EXPECT_EQ(0xa9b8c7d6U, raw_context.iregs[12]);
EXPECT_EQ(0x12345678U, raw_context.iregs[13]);
EXPECT_EQ(0xabcd1234U, raw_context.iregs[14]);
EXPECT_EQ(0x10203040U, raw_context.iregs[15]);
EXPECT_EQ(0x2e951ef7U, raw_context.cpsr);
}
TEST(Dump, OneExceptionARMOldFlags) {
Dump dump(0, kLittleEndian);
MDRawContextARM raw_context;
// MD_CONTEXT_ARM_INTEGER, but with _OLD
raw_context.context_flags = MD_CONTEXT_ARM_OLD | 0x00000002;
raw_context.iregs[0] = 0x3ecba80d;
raw_context.iregs[1] = 0x382583b9;
raw_context.iregs[2] = 0x7fccc03f;
raw_context.iregs[3] = 0xf62f8ec2;
raw_context.iregs[4] = 0x46a6a6a8;
raw_context.iregs[5] = 0x6a5025e2;
raw_context.iregs[6] = 0xd9fabb4a;
raw_context.iregs[7] = 0x6913f540;
raw_context.iregs[8] = 0xbffe6eda;
raw_context.iregs[9] = 0xb2ce1e2d;
raw_context.iregs[10] = 0x659caaa4;
raw_context.iregs[11] = 0xf0e0d0c0;
raw_context.iregs[12] = 0xa9b8c7d6;
raw_context.iregs[13] = 0x12345678;
raw_context.iregs[14] = 0xabcd1234;
raw_context.iregs[15] = 0x10203040;
raw_context.cpsr = 0x2e951ef7;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // thread id
0xdcba4321, // exception code
0xf0e0d0c0, // exception flags
0x0919a9b9c9d9e9f9ULL); // exception address
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9c9d9e9f9ULL,
raw_exception->exception_record.exception_address);
MinidumpContext *md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_ARM, md_context->GetContextCPU());
const MDRawContextARM *md_raw_context = md_context->GetContextARM();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_ARM_INTEGER,
(md_raw_context->context_flags
& MD_CONTEXT_ARM_INTEGER));
EXPECT_EQ(0x3ecba80dU, raw_context.iregs[0]);
EXPECT_EQ(0x382583b9U, raw_context.iregs[1]);
EXPECT_EQ(0x7fccc03fU, raw_context.iregs[2]);
EXPECT_EQ(0xf62f8ec2U, raw_context.iregs[3]);
EXPECT_EQ(0x46a6a6a8U, raw_context.iregs[4]);
EXPECT_EQ(0x6a5025e2U, raw_context.iregs[5]);
EXPECT_EQ(0xd9fabb4aU, raw_context.iregs[6]);
EXPECT_EQ(0x6913f540U, raw_context.iregs[7]);
EXPECT_EQ(0xbffe6edaU, raw_context.iregs[8]);
EXPECT_EQ(0xb2ce1e2dU, raw_context.iregs[9]);
EXPECT_EQ(0x659caaa4U, raw_context.iregs[10]);
EXPECT_EQ(0xf0e0d0c0U, raw_context.iregs[11]);
EXPECT_EQ(0xa9b8c7d6U, raw_context.iregs[12]);
EXPECT_EQ(0x12345678U, raw_context.iregs[13]);
EXPECT_EQ(0xabcd1234U, raw_context.iregs[14]);
EXPECT_EQ(0x10203040U, raw_context.iregs[15]);
EXPECT_EQ(0x2e951ef7U, raw_context.cpsr);
}
TEST(Dump, OneExceptionMIPS) {
Dump dump(0, kLittleEndian);
MDRawContextMIPS raw_context;
raw_context.context_flags = MD_CONTEXT_MIPS_INTEGER;
raw_context.iregs[0] = 0x3ecba80d;
raw_context.iregs[1] = 0x382583b9;
raw_context.iregs[2] = 0x7fccc03f;
raw_context.iregs[3] = 0xf62f8ec2;
raw_context.iregs[4] = 0x46a6a6a8;
raw_context.iregs[5] = 0x6a5025e2;
raw_context.iregs[6] = 0xd9fabb4a;
raw_context.iregs[7] = 0x6913f540;
raw_context.iregs[8] = 0xbffe6eda;
raw_context.iregs[9] = 0xb2ce1e2d;
raw_context.iregs[10] = 0x659caaa4;
raw_context.iregs[11] = 0xf0e0d0c0;
raw_context.iregs[12] = 0xa9b8c7d6;
raw_context.iregs[13] = 0x12345678;
raw_context.iregs[14] = 0xabcd1234;
raw_context.iregs[15] = 0x10203040;
raw_context.iregs[16] = 0xa80d3ecb;
raw_context.iregs[17] = 0x83b93825;
raw_context.iregs[18] = 0xc03f7fcc;
raw_context.iregs[19] = 0x8ec2f62f;
raw_context.iregs[20] = 0xa6a846a6;
raw_context.iregs[21] = 0x25e26a50;
raw_context.iregs[22] = 0xbb4ad9fa;
raw_context.iregs[23] = 0xf5406913;
raw_context.iregs[24] = 0x6edabffe;
raw_context.iregs[25] = 0x1e2db2ce;
raw_context.iregs[26] = 0xaaa4659c;
raw_context.iregs[27] = 0xd0c0f0e0;
raw_context.iregs[28] = 0xc7d6a9b8;
raw_context.iregs[29] = 0x56781234;
raw_context.iregs[30] = 0x1234abcd;
raw_context.iregs[31] = 0x30401020;
Context context(dump, raw_context);
Exception exception(dump, context,
0x1234abcd, // Thread id.
0xdcba4321, // Exception code.
0xf0e0d0c0, // Exception flags.
0x0919a9b9); // Exception address.
dump.Add(&context);
dump.Add(&exception);
dump.Finish();
string contents;
ASSERT_TRUE(dump.GetContents(&contents));
istringstream minidump_stream(contents);
Minidump minidump(minidump_stream);
ASSERT_TRUE(minidump.Read());
ASSERT_EQ(1U, minidump.GetDirectoryEntryCount());
MinidumpException *md_exception = minidump.GetException();
ASSERT_TRUE(md_exception != NULL);
uint32_t thread_id;
ASSERT_TRUE(md_exception->GetThreadID(&thread_id));
ASSERT_EQ(0x1234abcdU, thread_id);
const MDRawExceptionStream* raw_exception = md_exception->exception();
ASSERT_TRUE(raw_exception != NULL);
EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code);
EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags);
EXPECT_EQ(0x0919a9b9U,
raw_exception->exception_record.exception_address);
MinidumpContext* md_context = md_exception->GetContext();
ASSERT_TRUE(md_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_MIPS, md_context->GetContextCPU());
const MDRawContextMIPS* md_raw_context = md_context->GetContextMIPS();
ASSERT_TRUE(md_raw_context != NULL);
ASSERT_EQ((uint32_t) MD_CONTEXT_MIPS_INTEGER,
(md_raw_context->context_flags & MD_CONTEXT_MIPS_INTEGER));
EXPECT_EQ(0x3ecba80dU, raw_context.iregs[0]);
EXPECT_EQ(0x382583b9U, raw_context.iregs[1]);
EXPECT_EQ(0x7fccc03fU, raw_context.iregs[2]);
EXPECT_EQ(0xf62f8ec2U, raw_context.iregs[3]);
EXPECT_EQ(0x46a6a6a8U, raw_context.iregs[4]);
EXPECT_EQ(0x6a5025e2U, raw_context.iregs[5]);
EXPECT_EQ(0xd9fabb4aU, raw_context.iregs[6]);
EXPECT_EQ(0x6913f540U, raw_context.iregs[7]);
EXPECT_EQ(0xbffe6edaU, raw_context.iregs[8]);
EXPECT_EQ(0xb2ce1e2dU, raw_context.iregs[9]);
EXPECT_EQ(0x659caaa4U, raw_context.iregs[10]);
EXPECT_EQ(0xf0e0d0c0U, raw_context.iregs[11]);
EXPECT_EQ(0xa9b8c7d6U, raw_context.iregs[12]);
EXPECT_EQ(0x12345678U, raw_context.iregs[13]);
EXPECT_EQ(0xabcd1234U, raw_context.iregs[14]);
EXPECT_EQ(0x10203040U, raw_context.iregs[15]);
EXPECT_EQ(0xa80d3ecbU, raw_context.iregs[16]);
EXPECT_EQ(0x83b93825U, raw_context.iregs[17]);
EXPECT_EQ(0xc03f7fccU, raw_context.iregs[18]);
EXPECT_EQ(0x8ec2f62fU, raw_context.iregs[19]);
EXPECT_EQ(0xa6a846a6U, raw_context.iregs[20]);
EXPECT_EQ(0x25e26a50U, raw_context.iregs[21]);
EXPECT_EQ(0xbb4ad9faU, raw_context.iregs[22]);
EXPECT_EQ(0xf5406913U, raw_context.iregs[23]);
EXPECT_EQ(0x6edabffeU, raw_context.iregs[24]);
EXPECT_EQ(0x1e2db2ceU, raw_context.iregs[25]);
EXPECT_EQ(0xaaa4659cU, raw_context.iregs[26]);
EXPECT_EQ(0xd0c0f0e0U, raw_context.iregs[27]);
EXPECT_EQ(0xc7d6a9b8U, raw_context.iregs[28]);
EXPECT_EQ(0x56781234U, raw_context.iregs[29]);
EXPECT_EQ(0x1234abcdU, raw_context.iregs[30]);
EXPECT_EQ(0x30401020U, raw_context.iregs[31]);
}
} // namespace
| 37.435504 | 80 | 0.714234 | [
"vector"
] |
f51828cc7e45e7649ecba0dcb4c909bad88b6547 | 12,273 | cc | C++ | NativePatcher_cef_binary_3.3626.1882.win32/BridgeBuilder/dev_snap/tests/cefclient/renderer/performance_test_tests.cc | prepare/Kneadium | 1eaed8b6554964577aec2c692299f88590e3de93 | [
"BSD-3-Clause"
] | 4 | 2017-08-29T02:24:04.000Z | 2019-02-26T09:44:36.000Z | NativePatcher_cef_binary_3.3626.1882.win32/BridgeBuilder/dev_snap/tests/cefclient/renderer/performance_test_tests.cc | prepare/Kneadium | 1eaed8b6554964577aec2c692299f88590e3de93 | [
"BSD-3-Clause"
] | 15 | 2017-08-31T22:07:48.000Z | 2019-03-22T05:09:28.000Z | NativePatcher_cef_binary_3.3626.1882.win32/BridgeBuilder/dev_snap/tests/cefclient/renderer/performance_test_tests.cc | prepare/Kneadium | 1eaed8b6554964577aec2c692299f88590e3de93 | [
"BSD-3-Clause"
] | 3 | 2017-04-06T21:06:38.000Z | 2017-06-09T18:19:31.000Z | //###_ORIGINAL D:\projects\cef_binary_3.3626.1882.win32\tests\cefclient\renderer//performance_test_tests.cc
// Copyright (c) 2012 The Chromium Embedded Framework 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 "include/cef_v8.h"
#include "tests/cefclient/renderer/performance_test.h"
#include "tests/cefclient/renderer/performance_test_setup.h"
namespace client {
namespace performance_test {
//###_BEGIN
#include "tests/cefclient/myext/mycef_buildconfig.h"
#if BUILD_TEST
//###_END
namespace {
// Test function implementations.
PERF_TEST_FUNC(V8NullCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateNull();
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8BoolCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateBool(true);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8IntCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateInt(-5);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8UIntCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateUInt(10);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8DoubleCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateDouble(12.432);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8DateCreate) {
static cef_time_t time = {2012, 1, 0, 1};
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateDate(time);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8StringCreate) {
CefString str = "test string";
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateString(str);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ArrayCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateArray(1);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ArraySetValue) {
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> array = CefV8Value::CreateArray(1);
array->SetValue(0, val);
PERF_ITERATIONS_START()
array->SetValue(0, val);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ArrayGetValue) {
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> array = CefV8Value::CreateArray(1);
array->SetValue(0, val);
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> ret = array->GetValue(0);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8FunctionCreate) {
class Handler : public CefV8Handler {
public:
Handler() {}
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return false;
}
IMPLEMENT_REFCOUNTING(Handler);
};
CefString name = "name";
CefRefPtr<CefV8Handler> handler = new Handler();
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateFunction(name, handler);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8FunctionExecute) {
class Handler : public CefV8Handler {
public:
Handler() {}
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
IMPLEMENT_REFCOUNTING(Handler);
};
CefString name = "name";
CefRefPtr<CefV8Handler> handler = new Handler();
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(name, handler);
CefRefPtr<CefV8Value> obj = CefV8Context::GetCurrentContext()->GetGlobal();
CefV8ValueList args;
PERF_ITERATIONS_START()
func->ExecuteFunction(obj, args);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8FunctionExecuteWithContext) {
class Handler : public CefV8Handler {
public:
Handler() {}
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
IMPLEMENT_REFCOUNTING(Handler);
};
CefString name = "name";
CefRefPtr<CefV8Handler> handler = new Handler();
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(name, handler);
CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext();
CefRefPtr<CefV8Value> obj = context->GetGlobal();
CefV8ValueList args;
PERF_ITERATIONS_START()
func->ExecuteFunctionWithContext(context, obj, args);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectCreate) {
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(NULL, NULL);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectCreateWithAccessor) {
class Accessor : public CefV8Accessor {
public:
Accessor() {}
virtual bool Get(const CefString& name,
const CefRefPtr<CefV8Value> object,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
virtual bool Set(const CefString& name,
const CefRefPtr<CefV8Value> object,
const CefRefPtr<CefV8Value> value,
CefString& exception) OVERRIDE {
return true;
}
IMPLEMENT_REFCOUNTING(Accessor);
};
CefRefPtr<CefV8Accessor> accessor = new Accessor();
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(accessor, NULL);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectCreateWithInterceptor) {
class Interceptor : public CefV8Interceptor {
public:
Interceptor() {}
virtual bool Get(const CefString& name,
const CefRefPtr<CefV8Value> object,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
virtual bool Get(int index,
const CefRefPtr<CefV8Value> object,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
virtual bool Set(const CefString& name,
const CefRefPtr<CefV8Value> object,
const CefRefPtr<CefV8Value> value,
CefString& exception) OVERRIDE {
return true;
}
virtual bool Set(int index,
const CefRefPtr<CefV8Value> object,
const CefRefPtr<CefV8Value> value,
CefString& exception) OVERRIDE {
return true;
}
IMPLEMENT_REFCOUNTING(Interceptor);
};
CefRefPtr<CefV8Interceptor> interceptor = new Interceptor();
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(NULL, interceptor);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectSetValue) {
CefString name = "name";
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(NULL, NULL);
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_START()
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectGetValue) {
CefString name = "name";
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(NULL, NULL);
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> ret = obj->GetValue(name);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectSetValueWithAccessor) {
class Accessor : public CefV8Accessor {
public:
Accessor() {}
virtual bool Get(const CefString& name,
const CefRefPtr<CefV8Value> object,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
return true;
}
virtual bool Set(const CefString& name,
const CefRefPtr<CefV8Value> object,
const CefRefPtr<CefV8Value> value,
CefString& exception) OVERRIDE {
val_ = value;
return true;
}
CefRefPtr<CefV8Value> val_;
IMPLEMENT_REFCOUNTING(Accessor);
};
CefRefPtr<CefV8Accessor> accessor = new Accessor();
CefString name = "name";
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(accessor, NULL);
obj->SetValue(name, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE);
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_START()
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ObjectGetValueWithAccessor) {
class Accessor : public CefV8Accessor {
public:
Accessor() : val_(CefV8Value::CreateBool(true)) {}
virtual bool Get(const CefString& name,
const CefRefPtr<CefV8Value> object,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
retval = val_;
return true;
}
virtual bool Set(const CefString& name,
const CefRefPtr<CefV8Value> object,
const CefRefPtr<CefV8Value> value,
CefString& exception) OVERRIDE {
return true;
}
CefRefPtr<CefV8Value> val_;
IMPLEMENT_REFCOUNTING(Accessor);
};
CefRefPtr<CefV8Accessor> accessor = new Accessor();
CefString name = "name";
CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true);
CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(accessor, NULL);
obj->SetValue(name, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE);
obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE);
PERF_ITERATIONS_START()
CefRefPtr<CefV8Value> ret = obj->GetValue(name);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ArrayBufferCreate) {
class ReleaseCallback : public CefV8ArrayBufferReleaseCallback {
public:
void ReleaseBuffer(void* buffer) override { std::free(buffer); }
IMPLEMENT_REFCOUNTING(ReleaseCallback);
};
size_t len = 1;
size_t byte_len = len * sizeof(float);
CefRefPtr<CefV8ArrayBufferReleaseCallback> callback = new ReleaseCallback();
PERF_ITERATIONS_START()
float* buffer = (float*)std::malloc(byte_len);
CefRefPtr<CefV8Value> ret =
CefV8Value::CreateArrayBuffer(buffer, byte_len, callback);
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ContextEnterExit) {
CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext();
PERF_ITERATIONS_START()
context->Enter();
context->Exit();
PERF_ITERATIONS_END()
}
PERF_TEST_FUNC(V8ContextEval) {
CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext();
CefString jsCode = "var i = 0;";
CefRefPtr<CefV8Value> retval;
CefRefPtr<CefV8Exception> exception;
PERF_ITERATIONS_START()
context->Eval(jsCode, CefString(), 0, retval, exception);
PERF_ITERATIONS_END()
}
} // namespace
// Test function entries.
const PerfTestEntry kPerfTests[] = {
PERF_TEST_ENTRY(V8NullCreate),
PERF_TEST_ENTRY(V8BoolCreate),
PERF_TEST_ENTRY(V8IntCreate),
PERF_TEST_ENTRY(V8UIntCreate),
PERF_TEST_ENTRY(V8DoubleCreate),
PERF_TEST_ENTRY(V8DateCreate),
PERF_TEST_ENTRY(V8StringCreate),
PERF_TEST_ENTRY(V8ArrayCreate),
PERF_TEST_ENTRY(V8ArraySetValue),
PERF_TEST_ENTRY(V8ArrayGetValue),
PERF_TEST_ENTRY(V8FunctionCreate),
PERF_TEST_ENTRY(V8FunctionExecute),
PERF_TEST_ENTRY(V8FunctionExecuteWithContext),
PERF_TEST_ENTRY(V8ObjectCreate),
PERF_TEST_ENTRY(V8ObjectCreateWithAccessor),
PERF_TEST_ENTRY(V8ObjectCreateWithInterceptor),
PERF_TEST_ENTRY(V8ObjectSetValue),
PERF_TEST_ENTRY(V8ObjectGetValue),
PERF_TEST_ENTRY(V8ObjectSetValueWithAccessor),
PERF_TEST_ENTRY(V8ObjectGetValueWithAccessor),
PERF_TEST_ENTRY(V8ArrayBufferCreate),
PERF_TEST_ENTRY(V8ContextEnterExit),
PERF_TEST_ENTRY(V8ContextEval),
};
const int kPerfTestsCount = (sizeof(kPerfTests) / sizeof(kPerfTests[0]));
//###_BEGIN
#endif //BUILD_TEST
//###_END
} // namespace performance_test
} // namespace client
| 30.454094 | 107 | 0.696162 | [
"object"
] |
f51d780b6e462a7b8cde9309929f8e0c904221f6 | 15,848 | cpp | C++ | src/solver.cpp | LJP-TW/Ponce | 384eb38fcc698a9f0aa0f2242db36e5457358f56 | [
"BSL-1.0"
] | null | null | null | src/solver.cpp | LJP-TW/Ponce | 384eb38fcc698a9f0aa0f2242db36e5457358f56 | [
"BSL-1.0"
] | null | null | null | src/solver.cpp | LJP-TW/Ponce | 384eb38fcc698a9f0aa0f2242db36e5457358f56 | [
"BSL-1.0"
] | null | null | null |
#include "solver.hpp"
#include "globals.hpp"
#include <dbg.hpp>
/* This function return a vector of Inputs. A vector is necesary since switch conditions may have multiple branch constraints*/
std::vector<Input> solve_formula(ea_t pc, size_t path_constraint_index)
{
auto pathConstrains = api.getPathConstraints();
std::vector<Input> solutions;
if (path_constraint_index > pathConstrains.size() - 1) {
msg("Error. Requested path constraint index %u is larger than PathConstraints vector size (%lu)\n", path_constraint_index, pathConstrains.size());
return solutions;
}
// Double check that the condition at the path constraint index is at the address the user selected
assert(std::get<1>(pathConstrains[path_constraint_index].getBranchConstraints()[0]) == pc);
auto ast = api.getAstContext();
// We are going to store here the constraints for the previous conditions
// We can not initializate this to null, so we do it to a true condition (based on code_coverage_crackme_xor.py from the triton project)
auto previousConstraints = ast->equal(ast->bvtrue(), ast->bvtrue());
// Add user define constraints (borrar en reejecuccion, poner mensaje if not sat,
if (ponce_table_chooser){
for (const auto& [id, constrain] : ponce_table_chooser->constrains) {
for (const auto& [abstract_node_constrain, str_constrain] : constrain) {
previousConstraints = ast->land(previousConstraints, abstract_node_constrain);
}
}
}
// First we iterate through the previous path constrains to add the predicates of the taken path
unsigned int j;
for (j = 0; j < path_constraint_index; j++)
{
if (cmdOptions.showExtraDebugInfo)
msg("[+] Keeping condition %d\n", j);
// We add to the previous constraints the predicate for the taken branch
auto predicate = pathConstrains[j].getTakenPredicate();
previousConstraints = ast->land(previousConstraints, predicate);
}
// Then we use the predicate for the non taken path so we "solve" that condition.
// We try to solve every non taken branch (more than one is possible under certain situations
for (auto const& [taken, srcAddr, dstAddr, constraint] : pathConstrains[path_constraint_index].getBranchConstraints()) {
if (!taken) {
// We concatenate the previous constraints for the taken path plus the non taken constrain of the user selected condition
triton::ast::SharedAbstractNode final_expr = ast->land(previousConstraints, constraint);
if (cmdOptions.showExtraDebugInfo) {
std::stringstream ss;
ss << "(set-logic QF_AUFBV)" << std::endl;
api.printSlicedExpressions(ss, api.newSymbolicExpression(final_expr), true);
msg("[+] Formula:\n%s\n\n", ss.str().c_str());
}
//Time to solve
api.setSolverTimeout(cmdOptions.solver_timeout);
triton::engines::solver::status_e solver_status;
auto model = api.getModel(final_expr, &solver_status);
if (solver_status == triton::engines::solver::status_e::TIMEOUT) {
msg("[!] Solver timed out after %d seconds\n", cmdOptions.solver_timeout / 1000);
}
else if (solver_status == triton::engines::solver::status_e::UNSAT) {
msg("[!] That formula cannnot be solved (UNSAT)\n");
}
else if (solver_status == triton::engines::solver::status_e::SAT) {
Input newinput;
//Clone object
newinput.path_constraint_index = path_constraint_index;
newinput.dstAddr = dstAddr;
newinput.srcAddr = srcAddr;
msg("[+] Solution found! Values:\n");
for (const auto& [symId, model] : model) {
triton::engines::symbolic::SharedSymbolicVariable symbVar = api.getSymbolicVariable(symId);
std::string symbVarComment = symbVar->getComment();
triton::uint512 model_value = model.getValue();
if (symbVar->getType() == triton::engines::symbolic::variable_e::MEMORY_VARIABLE) {
auto mem = triton::arch::MemoryAccess(symbVar->getOrigin(), symbVar->getSize() / 8);
newinput.memOperand.push_back(mem);
api.setConcreteMemoryValue(mem, model_value);
}
else if (symbVar->getType() == triton::engines::symbolic::variable_e::REGISTER_VARIABLE) {
auto reg = triton::arch::Register(*api.getCpuInstance(), (triton::arch::register_e)symbVar->getOrigin());
newinput.regOperand.push_back(reg);
api.setConcreteRegisterValue(reg, model_value);
}
switch (symbVar->getSize())
{
case 8:
msg(" - %s%s: %#02x %s\n",
model.getVariable()->getName().c_str(),
!symbVarComment.empty()? (" ("+symbVarComment+")").c_str():"",
model_value.convert_to<uchar>(),
isprint(model_value.convert_to<uchar>()) ? ("(" + std::string(1, model_value.convert_to<uchar>()) + ")").c_str() : "");
break;
case 16:
msg(" - %s%s: %#04x (%c%c)\n",
!symbVarComment.empty() ? (" (" + symbVarComment + ")").c_str() : "",
symbVarComment.c_str(),
model_value.convert_to<ushort>(),
model_value.convert_to<uchar>() == 0 ? ' ' : model_value.convert_to<uchar>(),
(unsigned char)(model_value.convert_to<ushort>() >> 8) == 0 ? ' ' : (unsigned char)(model_value.convert_to<ushort>() >> 8));
break;
case 32:
msg(" - %s%s: %#08x\n",
!symbVarComment.empty() ? (" (" + symbVarComment + ")").c_str() : "",
symbVarComment.c_str(),
model_value.convert_to<uint32>());
break;
case 64:
msg(" - %s%s: %#16llx\n",
model.getVariable()->getName().c_str(),
!symbVarComment.empty() ? (" (" + symbVarComment + ")").c_str() : "",
model_value.convert_to<uint64>());
break;
default:
msg("[!] Unsupported size for the symbolic variable: %s (%s)\n", model.getVariable()->getName().c_str(), symbVarComment.c_str()); // what about 128 - 512 registers?
}
}
solutions.push_back(newinput);
}
else {
msg("[!] You should not see this. If so report a bug :(\n");
}
}
}
return solutions;
}
/*This function identify the type of condition jmp and negate the flags to negate the jmp.
Probably it is possible to do this with the solver, adding more variable to the formula to
identify the flag of the conditions and get the values. But for now we are doing it in this way.*/
void negate_flag_condition(triton::arch::Instruction* triton_instruction)
{
switch (triton_instruction->getType())
{
case triton::arch::x86::ID_INS_JA:
{
uint64 cf;
get_reg_val("CF", &cf);
uint64 zf;
get_reg_val("ZF", &zf);
if (cf == 0 && zf == 0)
{
cf = 1;
zf = 1;
}
else
{
cf = 0;
zf = 0;
}
set_reg_val("ZF", zf);
set_reg_val("CF", cf);
break;
}
case triton::arch::x86::ID_INS_JAE:
{
uint64 cf;
get_reg_val("CF", &cf);
uint64 zf;
get_reg_val("ZF", &zf);
if (cf == 0 || zf == 0)
{
cf = 1;
zf = 1;
}
else
{
cf = 0;
zf = 0;
}
set_reg_val("ZF", zf);
set_reg_val("CF", cf);
break;
}
case triton::arch::x86::ID_INS_JB:
{
uint64 cf;
get_reg_val("CF", &cf);
cf = !cf;
set_reg_val("CF", cf);
break;
}
case triton::arch::x86::ID_INS_JBE:
{
uint64 cf;
get_reg_val("CF", &cf);
uint64 zf;
get_reg_val("ZF", &zf);
if (cf == 1 || zf == 1)
{
cf = 0;
zf = 0;
}
else
{
cf = 1;
zf = 1;
}
set_reg_val("ZF", zf);
set_reg_val("CF", cf);
break;
}
/* ToDo: Check this one
case triton::arch::x86::ID_INS_JCXZ:
{
break;
}*/
case triton::arch::x86::ID_INS_JE:
case triton::arch::x86::ID_INS_JNE:
{
uint64 zf;
auto old_value = get_reg_val("ZF", &zf);
zf = !zf;
set_reg_val("ZF", zf);
break;
}
//case triton::arch::x86::ID_INS_JRCXZ:
//case triton::arch::x86::ID_INS_JECXZ:
case triton::arch::x86::ID_INS_JG:
{
uint64 sf;
get_reg_val("SF", &sf);
uint64 of;
get_reg_val("OF", &of);
uint64 zf;
get_reg_val("ZF", &zf);
if (sf == of && zf == 0)
{
sf = !of;
zf = 1;
}
else
{
sf = of;
zf = 0;
}
set_reg_val("SF", sf);
set_reg_val("OF", of);
set_reg_val("ZF", zf);
break;
}
case triton::arch::x86::ID_INS_JGE:
{
uint64 sf;
get_reg_val("SF", &sf);
uint64 of;
get_reg_val("OF", &of);
uint64 zf;
get_reg_val("ZF", &zf);
if (sf == of || zf == 1)
{
sf = !of;
zf = 0;
}
else
{
sf = of;
zf = 1;
}
set_reg_val("SF", sf);
set_reg_val("OF", of);
set_reg_val("ZF", zf);
break;
}
case triton::arch::x86::ID_INS_JL:
{
uint64 sf;
get_reg_val("SF", &sf);
uint64 of;
get_reg_val("OF", &of);
if (sf == of)
{
sf = !of;
}
else
{
sf = of;
}
set_reg_val("SF", sf);
set_reg_val("OF", of);
break;
}
case triton::arch::x86::ID_INS_JLE:
{
uint64 sf;
get_reg_val("SF", &sf);
uint64 of;
get_reg_val("OF", &of);
uint64 zf;
get_reg_val("ZF", &zf);
if (sf != of || zf == 1)
{
sf = of;
zf = 0;
}
else
{
sf = !of;
zf = 1;
}
set_reg_val("SF", sf);
set_reg_val("OF", of);
set_reg_val("ZF", zf);
break;
}
case triton::arch::x86::ID_INS_JNO:
case triton::arch::x86::ID_INS_JO:
{
uint64 of;
get_reg_val("OF", &of);
of = !of;
set_reg_val("OF", of);
break;
}
case triton::arch::x86::ID_INS_JNP:
case triton::arch::x86::ID_INS_JP:
{
uint64 pf;
get_reg_val("PF", &pf);
pf = !pf;
set_reg_val("PF", pf);
break;
}
case triton::arch::x86::ID_INS_JNS:
case triton::arch::x86::ID_INS_JS:
{
uint64 sf;
get_reg_val("SF", &sf);
sf = !sf;
set_reg_val("SF", sf);
break;
}
default:
msg("[!] We cannot negate %s instruction\n", triton_instruction->getDisassembly().c_str());
}
}
/*We set the memory to the results we got and do the analysis from there*/
void set_SMT_solution(const Input& solution) {
/*To set the memory types*/
for (const auto& mem : solution.memOperand){
auto concreteValue = api.getConcreteMemoryValue(mem, false);
put_bytes((ea_t)mem.getAddress(), &concreteValue, mem.getSize());
api.setConcreteMemoryValue(mem, concreteValue);
if (cmdOptions.showExtraDebugInfo){
char ascii_value[5] = { 0 };
if(std::isprint(concreteValue.convert_to<unsigned char>()))
qsnprintf(ascii_value, sizeof(ascii_value), "(%c)", concreteValue.convert_to<char>());
std::stringstream stream;
stream << std::hex << concreteValue;
msg("[+] Memory " MEM_FORMAT " set with value 0x%s %s\n",
mem.getAddress(),
stream.str().c_str(),
std::isprint(concreteValue.convert_to<unsigned char>())? ascii_value :"");
}
}
/*To set the register types*/
for (const auto& reg : solution.regOperand) {
auto concreteRegValue = api.getConcreteRegisterValue(reg, false);
set_reg_val(reg.getName().c_str(), concreteRegValue.convert_to<uint64>());
api.setConcreteRegisterValue(reg, concreteRegValue);
if (cmdOptions.showExtraDebugInfo) {
char ascii_value[5] = { 0 };
if (std::isprint(concreteRegValue.convert_to<unsigned char>()))
qsnprintf(ascii_value, sizeof(ascii_value), "(%c)", concreteRegValue.convert_to<char>());
std::stringstream stream;
stream << std::hex << concreteRegValue;
msg("[+] Registers %s set with value 0x%s %s\n",
reg.getName().c_str(),
stream.str().c_str(),
std::isprint(concreteRegValue.convert_to<unsigned char>()) ? ascii_value : "");
}
}
if (cmdOptions.showDebugInfo)
msg("[+] Memory/Registers set with the SMT results\n");
}
void negate_inject_maybe_restore_solver(ea_t pc, int path_constraint_index, bool restore) {
auto solutions = solve_formula(pc, path_constraint_index);
Input* chosen_solution = nullptr;
if (solutions.size() > 0) {
if (solutions.size() == 1) {
chosen_solution = &solutions[0];
triton::ast::SharedAbstractNode new_constraint;
for (auto& [taken, srcAddr, dstAddr, constraint] : api.getPathConstraints().back().getBranchConstraints()) {
// Let's look for the constraint we have force to take wich is the a priori not taken one
if (!taken) {
new_constraint = constraint;
break;
}
}
// Once found we first pop the last path constraint
api.popPathConstraint();
// And replace it for the found previously
api.pushPathConstraint(new_constraint);
}
else {
// ToDo: what do we do if we are in a switch case and get several solutions? Just using the first one? Ask the user?
for (const auto& solution : solutions) {
// ask the user where he wants to go in popup or even better in the contextual menu
// chosen_solution = &solutions[0];
//We need to modify the last path constrain from api.getPathConstraints()
for (auto& [taken, srcAddr, dstAddr, constraint] : api.getPathConstraints().back().getBranchConstraints()) {
if (!taken) {
}
}
}
}
// We negate necesary flags to go over the other branch
negate_flag_condition(ponce_runtime_status.last_triton_instruction);
if (restore)
snapshot.restoreSnapshot();
set_SMT_solution(*chosen_solution);
}
} | 36.348624 | 189 | 0.523915 | [
"object",
"vector",
"model"
] |
f52043edc35b8aeb0db92c4eab1d38c161e8440c | 65,627 | cpp | C++ | src/condor_dagman/parse.cpp | neurodebian/htcondor | 113a5c9921a4fce8a21e3ab96b2c1ba47441bf39 | [
"Apache-2.0"
] | null | null | null | src/condor_dagman/parse.cpp | neurodebian/htcondor | 113a5c9921a4fce8a21e3ab96b2c1ba47441bf39 | [
"Apache-2.0"
] | null | null | null | src/condor_dagman/parse.cpp | neurodebian/htcondor | 113a5c9921a4fce8a21e3ab96b2c1ba47441bf39 | [
"Apache-2.0"
] | null | null | null | /***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
//----------------------------------------------------------------
// IMPORTANT NOTE: Any changes in the DAG file implemented here
// must also be reflected in Dag::Rescue().
// Except for the concept of splicing--when the spliciing is finished all of
// the nodes are merged into the main dag as if they had physically appeared
// in the main dag file with the correct names.
//----------------------------------------------------------------
#include "condor_common.h"
#include "job.h"
#include "parse.h"
#include "util.h"
#include "debug.h"
#include "list.h"
#include "util_lib_proto.h"
#include "dagman_commands.h"
#include "dagman_main.h"
#include "tmp_dir.h"
#include "basename.h"
#include "extArray.h"
#include "condor_string.h" /* for strnewp() */
#include "dagman_recursive_submit.h"
#include "condor_getcwd.h"
static const char COMMENT = '#';
static const char * DELIMITERS = " \t";
static ExtArray<char*> _spliceScope;
static bool _useDagDir = false;
static int _thisDagNum = -1;
static bool _mungeNames = true;
static bool parse_subdag( Dag *dag,
const char* nodeTypeKeyword,
const char* dagFile, int lineNum,
const char *directory);
static bool parse_node( Dag *dag,
const char* nodeTypeKeyword,
const char* dagFile, int lineNum,
const char *directory, const char *inlineOrExt,
const char *submitOrDagFile);
static bool parse_script(const char *endline, Dag *dag,
const char *filename, int lineNumber);
static bool parse_parent(Dag *dag,
const char *filename, int lineNumber);
static bool parse_retry(Dag *dag,
const char *filename, int lineNumber);
static bool parse_abort(Dag *dag,
const char *filename, int lineNumber);
static bool parse_dot(Dag *dag,
const char *filename, int lineNumber);
static bool parse_vars(Dag *dag,
const char *filename, int lineNumber,
std::list<std::string>* varq);
static bool parse_priority(Dag *dag,
const char *filename, int lineNumber);
static bool parse_category(Dag *dag, const char *filename, int lineNumber);
static bool parse_maxjobs(Dag *dag, const char *filename, int lineNumber);
static bool parse_splice(Dag *dag, const char *filename, int lineNumber);
static bool parse_node_status_file(Dag *dag, const char *filename,
int lineNumber);
static bool parse_reject(Dag *dag, const char *filename,
int lineNumber);
static bool parse_jobstate_log(Dag *dag, const char *filename,
int lineNumber);
static bool parse_pre_skip(Dag *dag, const char* filename,
int lineNumber);
static bool parse_done(Dag *dag, const char *filename, int lineNumber);
static MyString munge_job_name(const char *jobName);
static MyString current_splice_scope(void);
void exampleSyntax (const char * example) {
debug_printf( DEBUG_QUIET, "Example syntax is: %s\n", example);
}
bool
isReservedWord( const char *token )
{
static const char * keywords[] = { "PARENT", "CHILD" };
static const unsigned int numKeyWords = sizeof(keywords) /
sizeof(const char *);
for (unsigned int i = 0 ; i < numKeyWords ; i++) {
if (!strcasecmp (token, keywords[i])) return true;
}
return false;
}
bool
isDelimiter( char c ) {
char const* tmp = strchr( DELIMITERS, (int)c );
return tmp ? true : false;
}
//-----------------------------------------------------------------------------
void parseSetDoNameMunge(bool doit)
{
_mungeNames = doit;
}
//-----------------------------------------------------------------------------
void parseSetThisDagNum(int num)
{
_thisDagNum = num;
}
//-----------------------------------------------------------------------------
bool parse (Dag *dag, const char *filename, bool useDagDir) {
ASSERT( dag != NULL );
++_thisDagNum;
_useDagDir = useDagDir;
//
// If useDagDir is true, we have to cd into the directory so we can
// parse the submit files correctly.
//
MyString tmpDirectory("");
const char * tmpFilename = filename;
TmpDir dagDir;
if ( useDagDir ) {
// Use a MyString here so we don't have to manually free memory
// at all of the places we return.
char *dirname = condor_dirname( filename );
tmpDirectory = dirname;
free(dirname);
MyString errMsg;
if ( !dagDir.Cd2TmpDir( tmpDirectory.Value(), errMsg ) ) {
debug_printf( DEBUG_QUIET,
"ERROR: Could not change to DAG directory %s: %s\n",
tmpDirectory.Value(), errMsg.Value() );
return false;
}
tmpFilename = condor_basename( filename );
}
FILE *fp = safe_fopen_wrapper_follow(tmpFilename, "r");
if(fp == NULL) {
MyString cwd;
condor_getcwd( cwd );
debug_printf( DEBUG_QUIET, "ERROR: Could not open file %s for input "
"(cwd %s) (errno %d, %s)\n", tmpFilename,
cwd.Value(), errno, strerror(errno));
return false;
}
char *line;
int lineNumber = 0;
// Here we have a list to save VARS lines for which the corresponding
// node has not yet been defined when we first encounter the VARS
// line; such lines are saved and re-parsed at the end of the parsing
// process. (This is for gittrac #1780: VARS values in top-level DAG
// should be able to be applied to splices; job_dagman_splice-R tests
// this functionality.) Nathan Panike says that saving *all* of the
// VARS lines and parsing them at the end also causes problems.
// wenger 2014-09-21
std::list<std::string> vars_to_save;
//
// This loop will read every line of the input file
//
while ( ((line=getline_trim(fp, lineNumber)) != NULL) ) {
std::string varline(line);
//
// Find the terminating '\0'
//
char * endline = line;
while (*endline != '\0') endline++;
// Note that getline will truncate leading spaces (as defined by isspace())
// so we don't need to do that before checking for empty lines or comments.
if (line[0] == 0) continue; // Ignore blank lines
if (line[0] == COMMENT) continue; // Ignore comments
debug_printf( DEBUG_DEBUG_3, "Parsing line <%s>\n", line );
// Note: strtok() could be replaced by MyString::Tokenize(),
// which is much safer, but I don't want to deal with that
// right now. wenger 2005-02-02.
char *token = strtok(line, DELIMITERS);
if ( !token ) continue; // so Coverity is happy
bool parsed_line_successfully;
// Handle a Job spec
// Example Syntax is: JOB j1 j1.condor [DONE]
//
if(strcasecmp(token, "JOB") == 0) {
parsed_line_successfully = parse_node( dag,
token,
filename, lineNumber, tmpDirectory.Value(), "",
"submitfile" );
}
// Handle a Stork job spec
// Example Syntax is: DATA j1 j1.dapsubmit [DONE]
//
else if (strcasecmp(token, "DAP") == 0) { // DEPRECATED!
debug_printf( DEBUG_QUIET, "%s (line %d): "
"ERROR: the DAP token is no longer supported\n",
filename, lineNumber );
parsed_line_successfully = false;
}
else if (strcasecmp(token, "DATA") == 0) {
debug_printf( DEBUG_QUIET, "%s (line %d): "
"ERROR: the DATA token is no longer supported\n",
filename, lineNumber );
parsed_line_successfully = false;
}
// Handle a SUBDAG spec
else if (strcasecmp(token, "SUBDAG") == 0) {
parsed_line_successfully = parse_subdag( dag,
token, filename, lineNumber, tmpDirectory.Value() );
}
// Handle a FINAL spec
else if(strcasecmp(token, "FINAL") == 0) {
parsed_line_successfully = parse_node( dag,
token,
filename, lineNumber, tmpDirectory.Value(), "",
"submitfile" );
}
// Handle a SCRIPT spec
// Example Syntax is: SCRIPT (PRE|POST) [DEFER status time] JobName ScriptName Args ...
else if ( strcasecmp(token, "SCRIPT") == 0 ) {
parsed_line_successfully = parse_script(endline, dag,
filename, lineNumber);
}
// Handle a Dependency spec
// Example Syntax is: PARENT p1 p2 p3 ... CHILD c1 c2 c3 ...
else if (strcasecmp(token, "PARENT") == 0) {
parsed_line_successfully = parse_parent(dag, filename, lineNumber);
}
// Handle a Retry spec
// Example Syntax is: Retry JobName 3 UNLESS-EXIT 42
else if( strcasecmp( token, "RETRY" ) == 0 ) {
parsed_line_successfully = parse_retry(dag, filename, lineNumber);
}
// Handle an Abort spec
// Example Syntax is: ABORT-DAG-ON JobName 2
else if( strcasecmp( token, "ABORT-DAG-ON" ) == 0 ) {
parsed_line_successfully = parse_abort(dag, filename, lineNumber);
}
// Handle a Dot spec
// Example syntax is: Dot dotfile [UPDATE | DONT-UPDATE]
// [OVERWRITE | DONT-OVERWRITE]
// [INCLUDE dot-file-header]
else if( strcasecmp( token, "DOT" ) == 0 ) {
parsed_line_successfully = parse_dot(dag, filename, lineNumber);
}
// Handle a Vars spec
// Example syntax is: Vars JobName var1="val1" var2="val2"
else if(strcasecmp(token, "VARS") == 0) {
vars_to_save.push_back(varline);
// Note that we pop this line inside parse_vars() if we
// parse it successfully, so that we don't re-parse it at
// the end.
parsed_line_successfully = parse_vars(dag, filename, lineNumber, &vars_to_save);
}
// Handle a Priority spec
// Example syntax is: Priority JobName 2
else if(strcasecmp(token, "PRIORITY") == 0) {
parsed_line_successfully = parse_priority(dag, filename,
lineNumber);
}
// Handle a Category spec
// Example syntax is: Category JobName Simulation
else if(strcasecmp(token, "CATEGORY") == 0) {
parsed_line_successfully = parse_category(dag, filename,
lineNumber);
}
// Handle a MaxJobs spec
// Example syntax is: MaxJobs Category 10
else if(strcasecmp(token, "MAXJOBS") == 0) {
parsed_line_successfully = parse_maxjobs(dag, filename,
lineNumber);
}
// Allow a CONFIG spec, but ignore it here because it
// is actually parsed by condor_submit_dag (config
// files must be processed before any other code runs)
else if(strcasecmp(token, "CONFIG") == 0) {
parsed_line_successfully = true;
}
// Handle a Splice spec
else if(strcasecmp(token, "SPLICE") == 0) {
parsed_line_successfully = parse_splice(dag, filename,
lineNumber);
}
// Handle a NODE_STATUS_FILE spec
else if(strcasecmp(token, "NODE_STATUS_FILE") == 0) {
parsed_line_successfully = parse_node_status_file(dag,
filename, lineNumber);
}
// Handle a REJECT spec
else if(strcasecmp(token, "REJECT") == 0) {
parsed_line_successfully = parse_reject(dag,
filename, lineNumber);
}
// Handle a JOBSTATE_LOG spec
else if(strcasecmp(token, "JOBSTATE_LOG") == 0) {
parsed_line_successfully = parse_jobstate_log(dag,
filename, lineNumber);
}
// Handle a PRE_SKIP
else if(strcasecmp(token, "PRE_SKIP") == 0) {
parsed_line_successfully = parse_pre_skip(dag,
filename, lineNumber);
}
// Handle a DONE spec
else if(strcasecmp(token, "DONE") == 0) {
parsed_line_successfully = parse_done(dag,
filename, lineNumber);
}
// None of the above means that there was bad input.
else {
debug_printf( DEBUG_QUIET, "%s (line %d): "
"ERROR: expected JOB, DATA, SUBDAG, SCRIPT, PARENT, RETRY, "
"ABORT-DAG-ON, DOT, VARS, PRIORITY, CATEGORY, MAXJOBS, "
"CONFIG, SPLICE, FINAL, NODE_STATUS_FILE, or PRE_SKIP token\n",
filename, lineNumber );
parsed_line_successfully = false;
}
if (!parsed_line_successfully) {
fclose(fp);
return false;
}
}
fclose(fp);
// always remember which were the inital and final nodes for this dag.
// If this dag is used as a splice, then this information is very
// important to preserve when building dependancy links.
dag->LiftSplices(SELF);
dag->RecordInitialAndFinalNodes();
// Okay, here we re-parse any VARS lines that didn't have corresponding
// node when we first read them.
for ( std::list<std::string>::iterator p = vars_to_save.begin();
p != vars_to_save.end(); ++p ) {
char* varline = strnewp( p->c_str() );
char * token = strtok( varline, DELIMITERS ); // Drop the VARS token
ASSERT( token );
bool parsed_line_successfully = parse_vars( dag,filename, 0, 0 );
if ( !parsed_line_successfully ) {
delete[] varline;
return false;
}
delete[] varline;
}
if ( useDagDir ) {
MyString errMsg;
if ( !dagDir.Cd2MainDir( errMsg ) ) {
debug_printf( DEBUG_QUIET,
"ERROR: Could not change to original directory: %s\n",
errMsg.Value() );
return false;
}
}
return true;
}
static bool
parse_subdag( Dag *dag,
const char* nodeTypeKeyword,
const char* dagFile, int lineNum, const char *directory )
{
const char *inlineOrExt = strtok( NULL, DELIMITERS );
if ( !inlineOrExt ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): SUBDAG needs "
"EXTERNAL keyword\n", dagFile, lineNum);
return false;
}
if ( !strcasecmp( inlineOrExt, "EXTERNAL" ) ) {
return parse_node( dag, nodeTypeKeyword, dagFile,
lineNum, directory, " EXTERNAL", "dagfile" );
}
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): only SUBDAG "
"EXTERNAL is supported at this time\n", dagFile, lineNum);
return false;
}
static bool
parse_node( Dag *dag,
const char* nodeTypeKeyword,
const char* dagFile, int lineNum, const char *directory,
const char *inlineOrExt, const char *submitOrDagFile)
{
MyString example;
MyString whynot;
bool done = false;
Dag *tmp = NULL;
MyString expectedSyntax;
expectedSyntax.formatstr( "Expected syntax: %s%s nodename %s "
"[DIR directory] [NOOP] [DONE]", nodeTypeKeyword, inlineOrExt,
submitOrDagFile );
// NOTE: fear not -- any missing tokens resulting in NULL
// strings will be error-handled correctly by AddNode()
// first token is the node name
const char *nodeName = strtok( NULL, DELIMITERS );
if ( !nodeName ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): no node name "
"specified\n", dagFile, lineNum );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
MyString tmpNodeName = munge_job_name(nodeName);
nodeName = tmpNodeName.Value();
// next token is the submit file name
const char *submitFile = strtok( NULL, DELIMITERS );
if ( !submitFile ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): no submit file "
"specified\n", dagFile, lineNum );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
// next token (if any) is "DIR" "NOOP", or "DONE" (in that order)
TmpDir nodeDir;
const char* nextTok = strtok( NULL, DELIMITERS );
if ( nextTok ) {
if (strcasecmp(nextTok, "DIR") == 0) {
if ( strcmp(directory, "") ) {
debug_printf( DEBUG_QUIET, "ERROR: DIR specification in node "
"lines not allowed with -UseDagDir command-line "
"argument\n");
return false;
}
directory = strtok( NULL, DELIMITERS );
if ( !directory ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): no directory "
"specified after DIR keyword\n", dagFile, lineNum );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
MyString errMsg;
if ( !nodeDir.Cd2TmpDir(directory, errMsg) ) {
debug_printf( DEBUG_QUIET,
"ERROR: can't change to directory %s: %s\n",
directory, errMsg.Value() );
return false;
}
nextTok = strtok( NULL, DELIMITERS );
} else {
// Fall through to check for NOOP.
}
}
bool noop = false;
if ( nextTok ) {
if ( strcasecmp( nextTok, "NOOP" ) == 0 ) {
noop = true;
nextTok = strtok( NULL, DELIMITERS );
} else {
// Fall through to check for DONE.
}
}
if ( nextTok ) {
if ( strcasecmp( nextTok, "DONE" ) == 0 ) {
done = true;
} else {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): invalid "
"parameter \"%s\"\n", dagFile, lineNum, nextTok );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
nextTok = strtok( NULL, DELIMITERS );
}
// anything else is garbage
if ( nextTok ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): invalid "
"parameter \"%s\"\n", dagFile, lineNum, nextTok );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
// check to see if this node name is also a splice name for this dag.
if (dag->LookupSplice(MyString(nodeName), tmp) == 0) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): "
"Node name '%s' must not also be a splice name.\n",
dagFile, lineNum, nodeName );
return false;
}
// If this is a "SUBDAG" line, generate the real submit file name.
MyString nestedDagFile("");
MyString dagSubmitFile(""); // must be outside if so it stays in scope
if ( strcasecmp( nodeTypeKeyword, "SUBDAG" ) == MATCH ) {
// Save original DAG file name (needed for rescue DAG).
nestedDagFile = submitFile;
// Generate the "real" submit file name (append ".condor.sub"
// to the DAG file name).
dagSubmitFile = submitFile;
dagSubmitFile += DAG_SUBMIT_FILE_SUFFIX;
submitFile = dagSubmitFile.Value();
} else if ( strstr( submitFile, DAG_SUBMIT_FILE_SUFFIX) ) {
// If the submit file name ends in ".condor.sub", we assume
// that this node is a nested DAG, and set the DAG filename
// accordingly.
nestedDagFile = submitFile;
nestedDagFile.replaceString( DAG_SUBMIT_FILE_SUFFIX, "" );
debug_printf( DEBUG_NORMAL, "Warning: the use of the JOB "
"keyword for nested DAGs is deprecated; please "
"use SUBDAG EXTERNAL instead\n" );
check_warning_strictness( DAG_STRICT_3 );
}
// looks ok, so add it
bool isFinal = strcasecmp( nodeTypeKeyword, "FINAL" ) == MATCH;
if( !AddNode( dag, nodeName, directory,
submitFile, noop, done, isFinal, whynot ) )
{
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): %s\n",
dagFile, lineNum, whynot.Value() );
debug_printf( DEBUG_QUIET, "%s\n", expectedSyntax.Value() );
return false;
}
if ( nestedDagFile != "" ) {
if ( !SetNodeDagFile( dag, nodeName, nestedDagFile.Value(),
whynot ) ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): %s\n",
dagFile, lineNum, whynot.Value() );
return false;
}
}
MyString errMsg;
if ( !nodeDir.Cd2MainDir(errMsg) ) {
debug_printf( DEBUG_QUIET,
"ERROR: can't change to original directory: %s\n",
errMsg.Value() );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_script
// Purpose: Parse a line of the format:
// SCRIPT [DEFER status time] (PRE|POST) JobName ScriptName Args ...
//
//-----------------------------------------------------------------------------
static bool
parse_script(
const char *endline,
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "SCRIPT [DEFER status time] (PRE|POST) JobName Script Args ...";
Job * job = NULL;
MyString whynot;
//
// Second keyword is either PRE, POST or DEFER
//
char * prepost = strtok( NULL, DELIMITERS );
if ( !prepost ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing PRE, POST, or DEFER\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
int defer_status = SCRIPT_DEFER_STATUS_NONE;
int defer_time = 0;
if ( !strcasecmp( prepost, "DEFER" ) ) {
// Our script has a defer statement.
char *token = strtok( NULL, DELIMITERS );
if ( token == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing DEFER status value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
char *tmp;
defer_status = (int)strtol( token, &tmp, 10 );
if ( tmp == token || defer_status <= 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid DEFER status value \"%s\"\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
token = strtok( NULL, DELIMITERS );
if ( token == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing DEFER time value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
defer_time = (int)strtol( token, &tmp, 10 );
if ( tmp == token || defer_time < 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid DEFER time value \"%s\"\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
// The next token must be PRE or POST.
prepost = strtok( NULL, DELIMITERS );
if ( !prepost ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing PRE or POST\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
}
bool post;
if ( !strcasecmp (prepost, "PRE" ) ) {
post = false;
} else if ( !strcasecmp (prepost, "POST") ) {
post = true;
} else {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): "
"After specifying \"SCRIPT\", you must "
"indicate if you want \"PRE\" or \"POST\" "
"(or DEFER)\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
//
// Next token is the JobName
//
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
const char *jobNameOrig = jobName; // for error output
const char *rest = jobName; // For subsequent tokens
if ( isReservedWord( jobName ) ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): JobName cannot be a reserved word\n",
filename, lineNumber );
exampleSyntax (example);
return false;
} else {
debug_printf(DEBUG_DEBUG_1, "jobName: %s\n", jobName);
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
job = dag->FindNodeByName( jobName );
if (job == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
}
//
// The rest of the line is the script and args
//
// first, skip over the token we already read...
while (*rest != '\0') rest++;
// if we're not at the end of the line, move forward
// one character so we're looking at the rest of the
// line...
if( rest < endline ) {
rest++;
} else {
// if we're already at the end of the line, they
// must not have given us any path to the script,
// arguments, etc.
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): "
"You named a %s script for node %s but "
"didn't provide a script filename\n",
filename, lineNumber, post ? "POST" : "PRE",
jobNameOrig );
exampleSyntax( example );
return false;
}
// quick hack to get this working for extra
// whitespace: make sure the "rest" of the line isn't
// starting with any delimiter...
while( rest[0] && isDelimiter(rest[0]) ) {
rest++;
}
if( ! rest[0] ) {
// this means we only saw whitespace after the
// script. however, because of how getline()
// works and our comparison to endline above, we
// should never hit this case.
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): "
"You named a %s script for node %s but "
"didn't provide a script filename\n",
filename, lineNumber, post ? "POST" : "PRE",
jobNameOrig );
exampleSyntax( example );
return false;
}
if( !job->AddScript( post, rest, defer_status, defer_time, whynot ) ) {
debug_printf( DEBUG_SILENT, "ERROR: %s (line %d): "
"failed to add %s script to node %s: %s\n",
filename, lineNumber, post ? "POST" : "PRE",
jobNameOrig, whynot.Value() );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_parent
// Purpose: parse a line of the format PARENT node-name+ CHILD node-name+
// where there can be one or more parent nodes and one or more
// children nodes.
//
//-----------------------------------------------------------------------------
static bool
parse_parent(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "PARENT p1 [p2 p3 ...] CHILD c1 [c2 c3 ...]";
Dag *splice_dag;
List<Job> parents;
ExtArray<Job*> *splice_initial;
ExtArray<Job*> *splice_final;
int i;
Job *job;
const char *jobName;
// get the job objects for the parents
while ((jobName = strtok (NULL, DELIMITERS)) != NULL &&
strcasecmp (jobName, "CHILD") != 0) {
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name(jobName);
const char *jobName2 = tmpJobName.Value();
// if splice name then deal with that first...
if (dag->LookupSplice(jobName2, splice_dag) == 0) {
// grab all of the final nodes of the splice and make them parents
// for this job.
splice_final = splice_dag->FinalRecordedNodes();
// now add each final node as a parent
for (i = 0; i < splice_final->length(); i++) {
job = (*splice_final)[i];
parents.Append(job);
}
} else {
// orig code
// if the name is not a splice, then see if it is a true node name.
job = dag->FindNodeByName( jobName2 );
if (job == NULL) {
// oops, it was neither a splice nor a parent name, bail
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
parents.Append (job);
}
}
// There must be one or more parent job names before
// the CHILD token
if (parents.Number() < 1) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): "
"Missing Parent Job names\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
if (jobName == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Expected CHILD token\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
List<Job> children;
// get the job objects for the children
while ((jobName = strtok (NULL, DELIMITERS)) != NULL) {
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name(jobName);
const char *jobName2 = tmpJobName.Value();
// if splice name then deal with that first...
if (dag->LookupSplice(jobName2, splice_dag) == 0) {
// grab all of the initial nodes of the splice and make them
// children for this job.
debug_printf( DEBUG_DEBUG_1, "%s (line %d): "
"Detected splice %s as a child....\n", filename, lineNumber,
jobName2);
splice_initial = splice_dag->InitialRecordedNodes();
debug_printf( DEBUG_DEBUG_1, "Adding %d initial nodes\n",
splice_initial->length());
// now add each initial node as a child
for (i = 0; i < splice_initial->length(); i++) {
job = (*splice_initial)[i];
children.Append(job);
}
} else {
// orig code
// if the name is not a splice, then see if it is a true node name.
job = dag->FindNodeByName( jobName2 );
if (job == NULL) {
// oops, it was neither a splice nor a child name, bail
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
children.Append (job);
}
}
if (children.Number() < 1) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing Child Job names\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
//
// Now add all the dependencies
//
Job *parent;
parents.Rewind();
while ((parent = parents.Next()) != NULL) {
Job *child;
children.Rewind();
while ((child = children.Next()) != NULL) {
if (!dag->AddDependency (parent, child)) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d) failed"
" to add dependency between parent"
" node \"%s\" and child node \"%s\"\n",
filename, lineNumber,
parent->GetJobName(), child->GetJobName() );
return false;
}
debug_printf( DEBUG_DEBUG_3,
"Added Dependency PARENT: %s CHILD: %s\n",
parent->GetJobName(), child->GetJobName() );
}
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_retry
// Purpose: Parse a line of the format "Retry jobname num-times [UNLESS-EXIT 42]"
//
//-----------------------------------------------------------------------------
static bool
parse_retry(
Dag *dag,
const char *filename,
int lineNumber)
{
const char *example = "Retry JobName 3 [UNLESS-EXIT 42]";
const char *jobName = strtok( NULL, DELIMITERS );
if( jobName == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
Job *job = dag->FindNodeByName( jobName );
if( job == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
if ( job->GetFinal() ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Final job %s cannot have retries\n",
filename, lineNumber, jobNameOrig );
return false;
}
char *token = strtok( NULL, DELIMITERS );
if( token == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing Retry value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
char *tmp;
job->retry_max = (int)strtol( token, &tmp, 10 );
if( tmp == token ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid Retry value \"%s\"\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
if ( job->retry_max < 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid Retry value \"%d\" "
"(cannot be negative)\n",
filename, lineNumber, job->retry_max );
exampleSyntax( example );
return false;
}
// Check for optional retry-abort value
token = strtok( NULL, DELIMITERS );
if ( token != NULL ) {
if ( strcasecmp ( token, "UNLESS-EXIT" ) != 0 ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d) Invalid retry option: %s\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
else {
token = strtok( NULL, DELIMITERS );
if ( token == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d) Missing parameter for UNLESS-EXIT\n",
filename, lineNumber);
exampleSyntax( example );
return false;
}
char *unless_exit_end;
int unless_exit = strtol( token, &unless_exit_end, 10 );
if (*unless_exit_end != 0) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d) Bad parameter for UNLESS-EXIT: %s\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
job->have_retry_abort_val = true;
job->retry_abort_val = unless_exit;
debug_printf( DEBUG_DEBUG_1, "Retry Abort Value for %s is %d\n",
jobName, job->retry_abort_val );
}
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_abort
// Purpose: Parse a line of the format
// "ABORT-DAG-ON jobname node_exit_value [RETURN dag_return_value]"
//
//-----------------------------------------------------------------------------
static bool
parse_abort(
Dag *dag,
const char *filename,
int lineNumber)
{
const char *example = "ABORT-DAG-ON JobName 3 [RETURN 1]";
// Job name.
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
Job *job = dag->FindNodeByName( jobName );
if( job == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
if ( job->GetFinal() ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Final job %s cannot have ABORT-DAG-ON specification\n",
filename, lineNumber, jobNameOrig );
return false;
}
// Node abort value.
char *abortValStr = strtok( NULL, DELIMITERS );
if ( abortValStr == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing ABORT-ON node value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
int abortVal;
char *tmp;
abortVal = (int)strtol( abortValStr, &tmp, 10 );
if( tmp == abortValStr ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid ABORT-ON node value \"%s\"\n",
filename, lineNumber, abortValStr );
exampleSyntax( example );
return false;
}
// RETURN keyword.
bool haveReturnVal = false;
int returnVal = 9999; // assign value to avoid compiler warning
const char *nextWord = strtok( NULL, DELIMITERS );
if ( nextWord != NULL ) {
if ( strcasecmp ( nextWord, "RETURN" ) != 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d) Invalid ABORT-ON option: %s\n",
filename, lineNumber, nextWord);
exampleSyntax( example );
return false;
} else {
// DAG return value.
haveReturnVal = true;
nextWord = strtok( NULL, DELIMITERS );
if ( nextWord == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d) Missing parameter for ABORT-ON\n",
filename, lineNumber);
exampleSyntax( example );
return false;
}
returnVal = strtol(nextWord, &tmp, 10);
if ( tmp == nextWord ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d) Bad parameter for ABORT_ON: %s\n",
filename, lineNumber, nextWord);
exampleSyntax( example );
return false;
} else if ( (returnVal < 0) || (returnVal > 255) ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d) Bad return value for ABORT_ON "
"(must be between 0 and 255): %s\n",
filename, lineNumber, nextWord);
return false;
}
}
}
job->abort_dag_val = abortVal;
job->have_abort_dag_val = true;
job->abort_dag_return_val = returnVal;
job->have_abort_dag_return_val = haveReturnVal;
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_dot
// Purpose: Parse a line of the format:
// Dot dotfile [UPDATE | DONT-UPDATE] [OVERWRITE | DONT-OVERWRITE]
// [INCLUDE dot-file-header]
// This command will tell DAGMan to generate dot files the show the
// state of the DAG.
//
//-----------------------------------------------------------------------------
static bool parse_dot(Dag *dag, const char *filename, int lineNumber)
{
const char *example = "Dot dotfile [UPDATE | DONT-UPDATE] "
"[OVERWRITE | DONT-OVERWRITE] "
"[INCLUDE <dot-file-header>]";
char *dot_file_name = strtok( NULL, DELIMITERS );
if ( dot_file_name == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing dot file name,\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
char *token;
while ( (token = strtok( NULL, DELIMITERS ) ) != NULL ) {
if (strcasecmp(token, "UPDATE") == 0) {
dag->SetDotFileUpdate(true);
} else if (strcasecmp(token, "DONT-UPDATE") == 0) {
dag->SetDotFileUpdate(false);
} else if (strcasecmp(token, "OVERWRITE") == 0) {
dag->SetDotFileOverwrite(true);
} else if (strcasecmp(token, "DONT-OVERWRITE") == 0) {
dag->SetDotFileOverwrite(false);
} else if (strcasecmp(token, "INCLUDE") == 0) {
token = strtok(NULL, DELIMITERS);
if (token == NULL) {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): Missing include"
" file name.\n", filename, lineNumber);
exampleSyntax(example);
return false;
} else {
dag->SetDotIncludeFileName(token);
}
}
}
dag->SetDotFileName(dot_file_name);
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_vars
// Purpose: Parses a line of named variables that will be made available to a job's
// submit description file
// The format of this line must be
// Vars JobName VarName1="value1" VarName2="value2" etc
// Whitespace surrounding the = sign is permissible
//-----------------------------------------------------------------------------
static bool parse_vars(Dag *dag, const char *filename, int lineNumber, std::list<std::string>* varq) {
const char* example = "Vars JobName VarName1=\"value1\" VarName2=\"value2\"";
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): Missing job name\n",
filename, lineNumber);
exampleSyntax(example);
return false;
}
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
Job *job = dag->FindNodeByName( jobName );
if(job == NULL) {
debug_printf(DEBUG_QUIET, "%s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig);
if(varq) {
debug_printf(DEBUG_QUIET, "Queueing this line up to try later\n");
return true;
} else {
return false;
}
} else {
// The line we are searching for should be at the back of the list
// unless we have lifted, in which case it is empty
if(varq && !varq->empty()) {
varq->pop_back();
}
}
char *str = strtok( NULL, "\n" ); // just get all the rest -- we'll be doing this by hand
int numPairs;
for ( numPairs = 0; ; numPairs++ ) { // for each name="value" pair
if ( str == NULL ) { // this happens when the above strtok returns NULL
break;
}
// Fix PR 854 (multiple macronames per VARS line don't work).
MyString varName( "" );
MyString varValue( "" );
while ( isspace( *str ) ) {
str++;
}
if ( *str == '\0' ) {
break;
}
// copy name char-by-char until we hit a symbol or whitespace
// names are limited to alphanumerics and underscores (except
// that '+' is legal as the first character)
int varnamestate = 0; // 0 means not within a varname
while( isalnum(*str) || *str == '_' || *str == '+' ) {
if (*str == '+' ) {
if ( varnamestate != 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): '+' can only be first character of macroname (%s)\n",
filename, lineNumber, varName.Value() );
return false;
}
}
varnamestate = 1;
varName += *str++;
}
if(varName.Length() == '\0') { // no alphanumeric symbols at all were written into name,
// just something weird, which we'll print
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): Unexpected symbol: \"%c\"\n", filename,
lineNumber, *str);
return false;
}
if ( varName == "+" ) {
debug_printf(DEBUG_QUIET,
"ERROR: %s (line %d): macroname (%s) must contain at least one alphanumeric character\n",
filename, lineNumber, varName.Value() );
return false;
}
// burn through any whitespace there may be afterwards
while(isspace(*str))
str++;
if(*str != '=') {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Illegal character (%c) in or after macroname %s\n", filename, lineNumber, *str, varName.Value() );
return false;
}
str++;
while(isspace(*str))
str++;
if(*str != '"') {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): %s's value must be quoted\n", filename,
lineNumber, varName.Value());
return false;
}
// now it's time to read in all the data until the next double quote, while handling
// the two escape sequences: \\ and \"
bool stillInQuotes = true;
bool escaped = false;
do {
varValue += *(++str);
if(*str == '\0') {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): Missing end quote\n", filename,
lineNumber);
return false;
}
if(!escaped) {
if(*str == '"') {
// we don't want that last " in the string
varValue.setChar( varValue.Length() - 1, '\0' );
stillInQuotes = false;
} else if(*str == '\\') {
// on the next pass it will be filled in appropriately
varValue.setChar( varValue.Length() - 1, '\0' );
escaped = true;
continue;
}
} else {
if(*str != '\\' && *str != '"') {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): Unknown escape sequence "
"\"\\%c\"\n", filename, lineNumber, *str);
return false;
}
escaped = false; // being escaped only lasts for one character
}
} while(stillInQuotes);
str++;
// Check for illegal variable name.
MyString tmpName(varName);
tmpName.lower_case();
if ( tmpName.find( "queue" ) == 0 ) {
debug_printf(DEBUG_QUIET, "ERROR: Illegal variable name: %s; variable "
"names cannot begin with \"queue\"\n", varName.Value() );
return false;
}
// This will be inefficient for jobs with lots of variables
// As in O(N^2)
job->varsFromDag->Rewind();
while(Job::NodeVar *var = job->varsFromDag->Next()){
if ( varName == var->_name ) {
debug_printf(DEBUG_NORMAL,"Warning: VAR \"%s\" "
"is already defined in job \"%s\" "
"(Discovered at file \"%s\", line %d)\n",
varName.Value(), job->GetJobName(), filename,
lineNumber);
check_warning_strictness( DAG_STRICT_2 );
debug_printf(DEBUG_NORMAL,"Warning: Setting VAR \"%s\" "
"= \"%s\"\n", varName.Value(), varValue.Value());
job->varsFromDag->DeleteCurrent();
}
}
debug_printf(DEBUG_DEBUG_1,
"Argument added, Name=\"%s\"\tValue=\"%s\"\n",
varName.Value(), varValue.Value());
Job::NodeVar *var = new Job::NodeVar();
var->_name = varName;
var->_value = varValue;
bool appendResult;
appendResult = job->varsFromDag->Append( var );
ASSERT( appendResult );
}
if(numPairs == 0) {
debug_printf(DEBUG_QUIET, "ERROR: %s (line %d): No valid name-value pairs\n", filename, lineNumber);
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_priority
// Purpose: Parses a line specifying the priority of a node
// The format of this line must be
// Priority <JobName> <Value>
//-----------------------------------------------------------------------------
static bool
parse_priority(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "PRIORITY JobName Value";
Job * job = NULL;
//
// Next token is the JobName
//
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
const char *jobNameOrig = jobName; // for error output
if ( isReservedWord( jobName ) ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): JobName cannot be a reserved word\n",
filename, lineNumber );
exampleSyntax( example );
return false;
} else {
debug_printf(DEBUG_DEBUG_1, "jobName: %s\n", jobName);
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
job = dag->FindNodeByName( jobName );
if (job == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
}
if ( job->GetFinal() ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Final job %s cannot have priority\n",
filename, lineNumber, jobNameOrig );
return false;
}
//
// Next token is the priority value.
//
const char *valueStr = strtok(NULL, DELIMITERS);
if ( valueStr == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing PRIORITY value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
int priorityVal;
char *tmp;
priorityVal = (int)strtol( valueStr, &tmp, 10 );
if( tmp == valueStr ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid PRIORITY value \"%s\"\n",
filename, lineNumber, valueStr );
exampleSyntax( example );
return false;
}
//
// Check for illegal extra tokens.
//
valueStr = strtok(NULL, DELIMITERS);
if ( valueStr != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on PRIORITY line\n",
filename, lineNumber, valueStr );
exampleSyntax( example );
return false;
}
if ( job->_hasNodePriority && job->_nodePriority != priorityVal ) {
debug_printf( DEBUG_NORMAL, "Warning: new priority %d for node %s "
"overrides old value %d\n", priorityVal,
job->GetJobName(), job->_nodePriority );
check_warning_strictness( DAG_STRICT_2 );
}
job->_hasNodePriority = true;
job->_nodePriority = priorityVal;
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_category
// Purpose: Parses a line specifying the type of a node
// The format of this line must be
// Category <JobName> <Category>
// No whitespace is allowed in the category name
//-----------------------------------------------------------------------------
static bool
parse_category(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "CATEGORY JobName TypeName";
Job * job = NULL;
//
// Next token is the JobName
//
const char *jobName = strtok(NULL, DELIMITERS);
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax (example);
return false;
}
const char *jobNameOrig = jobName; // for error output
if (isReservedWord(jobName)) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): JobName cannot be a reserved word\n",
filename, lineNumber );
exampleSyntax (example);
return false;
} else {
debug_printf(DEBUG_DEBUG_1, "jobName: %s\n", jobName);
MyString tmpJobName = munge_job_name(jobName);
jobName = tmpJobName.Value();
job = dag->FindNodeByName( jobName );
if (job == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
}
if ( job->GetFinal() ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Final job %s cannot have category\n",
filename, lineNumber, jobNameOrig );
return false;
}
//
// Next token is the category name.
//
const char *categoryName = strtok(NULL, DELIMITERS);
if ( categoryName == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing CATEGORY name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
//
// Check for illegal extra tokens.
//
const char *tmpStr = strtok(NULL, DELIMITERS);
if ( tmpStr != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on CATEGORY line\n",
filename, lineNumber, tmpStr );
exampleSyntax( example );
return false;
}
job->SetCategory( categoryName, dag->_catThrottles );
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_splice
// Purpose: Parses a splice (subdag internal) line.
// The format of this line must be
// SPLICE <SpliceName> <SpliceFileName> [DIR <directory>]
//-----------------------------------------------------------------------------
static bool
parse_splice(
Dag *dag,
const char *filename,
int lineNumber)
{
const char *example = "SPLICE SpliceName SpliceFileName [DIR directory]";
Dag *splice_dag = NULL;
MyString errMsg;
//
// Next token is the splice name
//
MyString spliceName = strtok( NULL, DELIMITERS );
// Note: this if is true if strtok() returns NULL. wenger 2014-10-07
if ( spliceName == "" ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing SPLICE name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
// Check to make sure we don't already have a node with the name of the
// splice.
if ( dag->NodeExists(spliceName.Value()) ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): "
" Splice name '%s' must not also be a node name.\n",
filename, lineNumber, spliceName.Value() );
return false;
}
/* "push" it onto the scoping "stack" which will be used later to
munge the names of the nodes to have the splice name in them so
the same splice dag file with different splice names don't conflict.
*/
_spliceScope.add(strdup(munge_job_name(spliceName.Value()).Value()));
//
// Next token is the splice file name
//
MyString spliceFile = strtok( NULL, DELIMITERS );
// Note: this if is true if strtok() returns NULL. wenger 2014-10-07
if ( spliceFile == "" ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing SPLICE file name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
//
// next token (if any) is "DIR"
//
TmpDir spliceDir;
MyString dirTok = strtok( NULL, DELIMITERS );
MyString directory = ".";
MyString dirTokOrig = dirTok;
dirTok.upper_case();
// Note: this if is okay even if strtok() returns NULL. wenger 2014-10-07
if ( dirTok == "DIR" ) {
// parse the directory name
directory = strtok( NULL, DELIMITERS );
// Note: this if is true if strtok() returns NULL. wenger 2014-10-07
if ( directory == "" ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): DIR requires a directory "
"specification\n", filename, lineNumber);
exampleSyntax( example );
return false;
}
} else if ( dirTok != "" ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): illegal token (%s) on SPLICE line\n",
filename, lineNumber, dirTokOrig.Value() );
exampleSyntax( example );
return false;
}
//
// anything else is garbage
//
MyString garbage = strtok( 0, DELIMITERS );
// Note: this if is true if strtok() returns NULL. wenger 2014-10-07
if( garbage != "" ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): invalid "
"parameter \"%s\"\n", filename, lineNumber,
garbage.Value() );
exampleSyntax( example );
return false;
}
/* make a new dag to put everything into */
/* parse increments this number, however, we want the splice nodes to
be munged into the numeric identification of the invoking dag, so
decrement it here so when it is incremented, nothing happened. */
--_thisDagNum;
// This "copy" is tailored to be correct according to Dag::~Dag()
// We can pass in NULL for submitDagOpts because the splice DAG
// object will never actually do a submit. wenger 2010-03-25
splice_dag = new Dag( dag->DagFiles(),
dag->MaxJobsSubmitted(),
dag->MaxPreScripts(),
dag->MaxPostScripts(),
dag->AllowLogError(),
dag->UseDagDir(),
dag->MaxIdleJobProcs(),
dag->RetrySubmitFirst(),
dag->RetryNodeFirst(),
dag->CondorRmExe(),
dag->DAGManJobId(),
dag->ProhibitMultiJobs(),
dag->SubmitDepthFirst(),
dag->DefaultNodeLog(),
dag->GenerateSubdagSubmits(),
NULL, // this Dag will never submit a job
true, /* we are a splice! */
current_splice_scope() );
// initialize whatever the DIR line was, or defaults to, here.
splice_dag->SetDirectory(directory);
debug_printf(DEBUG_VERBOSE, "Parsing Splice %s in directory %s with "
"file %s\n", spliceName.Value(), directory.Value(),
spliceFile.Value());
// CD into the DIR directory so we can continue parsing.
// This must be done AFTER the DAG is created due to the DAG object
// doing its own chdir'ing while looking for log files.
if ( !spliceDir.Cd2TmpDir(directory.Value(), errMsg) ) {
debug_printf( DEBUG_QUIET,
"ERROR: can't change to directory %s: %s\n",
directory.Value(), errMsg.Value() );
return false;
}
// parse the splice file into a separate dag.
if (!parse(splice_dag, spliceFile.Value(), _useDagDir)) {
debug_error(1, DEBUG_QUIET, "ERROR: Failed to parse splice %s in file %s\n",
spliceName.Value(), spliceFile.Value());
return false;
}
// CD back to main dir to keep processing.
if ( !spliceDir.Cd2MainDir(errMsg) ) {
debug_printf( DEBUG_QUIET,
"ERROR: can't change to original directory: %s\n",
errMsg.Value() );
return false;
}
// Splices cannot have final nodes.
if ( splice_dag->HasFinalNode() ) {
debug_printf( DEBUG_QUIET, "ERROR: splice %s has a final node; "
"splices cannot have final nodes\n", spliceName.Value() );
return false;
}
// munge the splice name
spliceName = munge_job_name(spliceName.Value());
// XXX I'm not sure this goes here quite yet....
debug_printf(DEBUG_DEBUG_1, "Splice scope is: %s\n",
current_splice_scope().Value());
splice_dag->PrefixAllNodeNames(MyString(current_splice_scope()));
splice_dag->_catThrottles.PrefixAllCategoryNames(
MyString(current_splice_scope()));
// Print out a useful piece of debugging...
if( DEBUG_LEVEL( DEBUG_DEBUG_1 ) ) {
splice_dag->PrintJobList();
}
// associate the splice_dag with its name in _this_ dag, later I'll merge
// the nodes from this splice into _this_ dag.
if (dag->InsertSplice(spliceName, splice_dag) == -1) {
debug_printf( DEBUG_QUIET, "ERROR: Splice name '%s' used for multiple "
"splices. Splice names must be unique per dag file.\n",
spliceName.Value());
return false;
}
debug_printf(DEBUG_DEBUG_1, "Done parsing splice %s\n", spliceName.Value());
// pop the just pushed value off of the end of the ext array
free(_spliceScope[_spliceScope.getlast()]);
_spliceScope.truncate(_spliceScope.getlast() - 1);
debug_printf(DEBUG_DEBUG_1, "_spliceScope has length %d\n", _spliceScope.length());
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_maxjobs
// Purpose: Parses a line specifying the maximum number of jobs for
// a given node category.
// The format of this line must be
// MaxJobs <Category> <Value>
// No whitespace is allowed in the category name
//-----------------------------------------------------------------------------
static bool
parse_maxjobs(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "MAXJOBS TypeName Value";
//
// Next token is the category name.
//
const char *categoryName = strtok(NULL, DELIMITERS);
if ( categoryName == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing MAXJOBS category name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
//
// Next token is the maxjobs value.
//
const char *valueStr = strtok(NULL, DELIMITERS);
if ( valueStr == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing MAXJOBS value\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
int maxJobsVal;
char *tmp;
maxJobsVal = (int)strtol( valueStr, &tmp, 10 );
if( tmp == valueStr ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid MAXJOBS value \"%s\"\n",
filename, lineNumber, valueStr );
exampleSyntax( example );
return false;
}
if ( maxJobsVal < 0 ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): MAXJOBS value must be non-negative\n",
filename, lineNumber );
return false;
}
//
// Check for illegal extra tokens.
//
valueStr = strtok(NULL, DELIMITERS);
if ( valueStr != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on MAXJOBS line\n",
filename, lineNumber, valueStr );
exampleSyntax( example );
return false;
}
MyString tmpName( categoryName );
dag->_catThrottles.SetThrottle( &tmpName, maxJobsVal );
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_node_status_file
// Purpose: Parses a line specifying the a node_status_file for the DAG.
// The format of this line must be
// NODE_STATUS_FILE <filename> [min update time]
// No whitespace is allowed in the file name
//-----------------------------------------------------------------------------
static bool
parse_node_status_file(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "NODE_STATUS_FILE StatusFile [min update time] [ALWAYS-UPDATE]";
char *statusFileName = strtok(NULL, DELIMITERS);
if (statusFileName == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing node status file name,\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
int minUpdateTime = 0;
char *minUpdateStr = strtok(NULL, DELIMITERS);
if ( minUpdateStr != NULL ) {
char *tmp;
minUpdateTime = (int)strtol( minUpdateStr, &tmp, 10 );
if ( tmp == minUpdateStr ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid min update time value \"%s\"\n",
filename, lineNumber, minUpdateStr );
exampleSyntax( example );
return false;
}
}
bool alwaysUpdate = false;
char *alwaysUpdateStr = strtok( NULL, DELIMITERS );
if ( alwaysUpdateStr != NULL ) {
if ( strcasecmp( alwaysUpdateStr, "ALWAYS-UPDATE" ) == 0) {
alwaysUpdate = true;
} else {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): invalid "
"parameter \"%s\"\n", filename, lineNumber,
alwaysUpdateStr );
exampleSyntax( example );
return false;
}
}
//
// Check for illegal extra tokens.
//
char *token = strtok( NULL, DELIMITERS );
if ( token != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on NODE_STATUS_FILE line\n",
filename, lineNumber, token );
exampleSyntax( example );
return false;
}
dag->SetNodeStatusFileName( statusFileName, minUpdateTime, alwaysUpdate );
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_reject
// Purpose: Parses a line specifying the REJECT directive for a DAG.
// The format of this line must be
// REJECT
//-----------------------------------------------------------------------------
static bool
parse_reject(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "REJECT";
char *token = strtok(NULL, DELIMITERS);
if ( token != NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): REJECT should have "
"no additional tokens.\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
MyString location;
location.formatstr( "%s (line %d)", filename, lineNumber );
debug_printf( DEBUG_QUIET, "REJECT specification at %s "
"will cause this DAG to fail\n", location.Value() );
dag->SetReject( location );
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_jobstate_log
// Purpose: Parses a line specifying the a jobstate.log for the DAG.
// The format of this line must be
// JOBSTATE_LOG <filename>
// No whitespace is allowed in the file name
//-----------------------------------------------------------------------------
static bool
parse_jobstate_log(
Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "JOBSTATE_LOG JobstateLogFile";
char *logFileName = strtok(NULL, DELIMITERS);
if (logFileName == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing jobstate log file name,\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
//
// Check for illegal extra tokens.
//
char *extraTok = strtok( NULL, DELIMITERS );
if ( extraTok != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on JOBSTATE_LOG line\n",
filename, lineNumber, extraTok );
exampleSyntax( example );
return false;
}
dag->SetJobstateLogFileName( logFileName );
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_pre_skip
// Purpose: Tell dagman to skip execution if the PRE script exits with a
// a certain code
//-----------------------------------------------------------------------------
bool
parse_pre_skip( Dag *dag,
const char *filename,
int lineNumber)
{
const char * example = "PRE_SKIP JobName Exitcode";
Job * job = NULL;
MyString whynot;
//
// second token is the JobName
//
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
const char *jobNameOrig = jobName; // for error output
if ( isReservedWord(jobName) ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): JobName cannot be a reserved word\n",
filename, lineNumber );
exampleSyntax( example );
return false;
} else {
debug_printf( DEBUG_DEBUG_1, "jobName: %s\n", jobName );
MyString tmpJobName = munge_job_name( jobName );
jobName = tmpJobName.Value();
job = dag->FindNodeByName( jobName );
if (job == NULL) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return false;
}
}
//
// The rest of the line consists of the exitcode
//
const char *exitCodeStr = strtok( NULL, DELIMITERS );
if ( exitCodeStr == NULL ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): Missing exit code\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
char *tmp;
int exitCode = (int)strtol( exitCodeStr, &tmp, 10 );
if ( tmp == exitCodeStr ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Invalid exit code \"%s\"\n",
filename, lineNumber, exitCodeStr );
exampleSyntax( example );
return false;
}
//
// Anything else is garbage
//
const char *nextTok = strtok( NULL, DELIMITERS );
if ( nextTok ) {
debug_printf( DEBUG_QUIET, "ERROR: %s (line %d): invalid "
"parameter \"%s\"\n", filename, lineNumber, nextTok );
exampleSyntax( example );
return false;
}
if ( !job->AddPreSkip( exitCode, whynot ) ) {
debug_printf( DEBUG_SILENT, "ERROR: %s (line %d): failed to add "
"PRE_SKIP note to node %s: %s\n",
filename, lineNumber, jobNameOrig,
whynot.Value() );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//
// Function: parse_done
// Purpose: Parse a line of the format "Done jobname"
//
//-----------------------------------------------------------------------------
static bool
parse_done(
Dag *dag,
const char *filename,
int lineNumber)
{
const char *example = "Done JobName";
const char *jobName = strtok( NULL, DELIMITERS );
if ( jobName == NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Missing job name\n",
filename, lineNumber );
exampleSyntax( example );
return false;
}
const char *jobNameOrig = jobName; // for error output
MyString tmpJobName = munge_job_name( jobName );
jobName = tmpJobName.Value();
//
// Check for illegal extra tokens.
//
char *extraTok = strtok( NULL, DELIMITERS );
if ( extraTok != NULL ) {
debug_printf( DEBUG_QUIET,
"ERROR: %s (line %d): Extra token (%s) on DONE line\n",
filename, lineNumber, extraTok );
exampleSyntax( example );
return false;
}
Job *job = dag->FindNodeByName( jobName );
if( job == NULL ) {
debug_printf( DEBUG_QUIET,
"Warning: %s (line %d): Unknown Job %s\n",
filename, lineNumber, jobNameOrig );
return !check_warning_strictness( DAG_STRICT_1, false );
}
if ( job->GetFinal() ) {
debug_printf( DEBUG_QUIET,
"Warning: %s (line %d): FINAL Job %s cannot be set to DONE\n",
filename, lineNumber, jobNameOrig );
return !check_warning_strictness( DAG_STRICT_1, false );
}
job->SetStatus( Job::STATUS_DONE );
return true;
}
static MyString munge_job_name(const char *jobName)
{
//
// Munge the node name if necessary.
//
MyString newName;
if ( _mungeNames ) {
newName = MyString(_thisDagNum) + "." + jobName;
} else {
newName = jobName;
}
return newName;
}
static MyString current_splice_scope(void)
{
MyString tmp;
MyString scope;
if(_spliceScope.length() > 0) {
// While a natural choice might have been : as a splice scoping
// separator, this character was chosen because it is a valid character
// on all the file systems we use (whereas : can't be a file system
// character on windows). The plus, and really anything other than :,
// isn't the best choice. Sorry.
tmp = _spliceScope[_spliceScope.length() - 1];
scope = tmp + "+";
}
return scope;
}
| 29.884791 | 150 | 0.618953 | [
"object"
] |
f52076e7dc32a0f32e0480b5ab84f6df3822e133 | 3,487 | hpp | C++ | src/engine/gui.hpp | Stephen-Seo/SwapShop | 994ae8dae15c79710b4a91e451784ae546043acb | [
"MIT"
] | 1 | 2019-11-22T15:56:43.000Z | 2019-11-22T15:56:43.000Z | src/engine/gui.hpp | Stephen-Seo/SFML_GameEngine | d80189e866d42b81bb508de41107b38c2024aa92 | [
"MIT"
] | null | null | null | src/engine/gui.hpp | Stephen-Seo/SFML_GameEngine | d80189e866d42b81bb508de41107b38c2024aa92 | [
"MIT"
] | null | null | null |
#ifndef GAME_GUI_HPP
#define GAME_GUI_HPP
#include <functional>
#include <vector>
#include <SFML/Graphics.hpp>
class GuiObject : public sf::Drawable
{
public:
GuiObject();
virtual void update(sf::Time dt) = 0;
virtual void handleEvent(const sf::Event& event) = 0;
void registerCallback(std::function<void(float)> function);
void clearCallbacks();
void setPosition(float x, float y);
void setPosition(const sf::Vector2f& pos);
void setRotation(float angle);
void setScale(float factorX, float factorY);
void setScale(const sf::Vector2f& factors);
void setOrigin(float x, float y);
void setOrigin(const sf::Vector2f& origin);
const sf::Vector2f& getPosition() const;
float getRotation() const;
const sf::Vector2f& getScale() const;
const sf::Vector2f& getOrigin() const;
void move(float offsetX, float offsetY);
void move(const sf::Vector2f& offset);
void rotate(float angle);
void scale(float factorX, float factorY);
void scale(const sf::Vector2f& factor);
const sf::Transform& getTransform() const;
const sf::Transform& getInverseTransform() const;
protected:
std::vector<std::function<void(float)> > callbacks;
bool transformDirty;
private:
sf::Transformable transformable;
};
class GuiButton : public GuiObject
{
public:
GuiButton(bool usingTexture = false);
void update(sf::Time dt);
void handleEvent(const sf::Event& event);
void setSize(const sf::Vector2f& size);
const sf::Vector2f& getSize();
void setPassiveFillColor(sf::Color color);
void setPassiveOutlineColor(sf::Color color);
void setHoveringFillColor(sf::Color color);
void setHoveringOutlineColor(sf::Color color);
void setActiveFillColor(sf::Color color);
void setActiveOutlineColor(sf::Color color);
void setPassiveTexture(sf::Texture& texture);
void setHoveringTexture(sf::Texture& texture);
void setActiveTexture(sf::Texture& texture);
private:
enum MouseState
{
PASSIVE,
HOVERING,
ACTIVE,
AWAY_CLICKED_ON
};
bool usingTexture;
MouseState currentState;
sf::Color passiveFillColor;
sf::Color passiveOutlineColor;
sf::Color hoveringFillColor;
sf::Color hoveringOutlineColor;
sf::Color activeFillColor;
sf::Color activeOutlineColor;
sf::Texture* passiveTexture;
sf::Texture* hoveringTexture;
sf::Texture* activeTexture;
sf::RectangleShape rectangleShape;
sf::Vector2f coords[4];
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
};
class GuiSlider : public GuiObject
{
public:
GuiSlider(bool usingTexture = false);
void update(sf::Time dt);
void handleEvent(const sf::Event& event);
void setBgSize(const sf::Vector2f& size);
void setKnobSize(const sf::Vector2f& size);
void setBgFillColor(sf::Color);
void setBgOutlineColor(sf::Color);
void setKnobFillColor(sf::Color);
void setKnobOutlineColor(sf::Color);
void setBgTexture(sf::Texture& texture);
void setKnobTexture(sf::Texture& texture);
private:
sf::Uint8 status;
/*
0000 0000 - passive
0000 0001 - active
1000 0000 - using texture
*/
sf::RectangleShape bg;
sf::RectangleShape knob;
float knobLocation;
sf::Vector2f coords[4];
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
void centerKnobOnBg(float location);
};
#endif
| 23.402685 | 71 | 0.688271 | [
"vector",
"transform"
] |
f52103e7390f60cea516cf8311e4371dfb7ed721 | 8,117 | cpp | C++ | build-QTCPServer-Desktop_Qt_5_14_2_GCC_64bit-Debug/moc_mainwindow.cpp | sun6202/lab4-team | 57b4cce6d6b4546d89d376daa1027ef66f9a5195 | [
"MIT"
] | null | null | null | build-QTCPServer-Desktop_Qt_5_14_2_GCC_64bit-Debug/moc_mainwindow.cpp | sun6202/lab4-team | 57b4cce6d6b4546d89d376daa1027ef66f9a5195 | [
"MIT"
] | null | null | null | build-QTCPServer-Desktop_Qt_5_14_2_GCC_64bit-Debug/moc_mainwindow.cpp | sun6202/lab4-team | 57b4cce6d6b4546d89d376daa1027ef66f9a5195 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../QTCPServer/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[19];
char stringdata0[280];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 10), // "newMessage"
QT_MOC_LITERAL(2, 22, 0), // ""
QT_MOC_LITERAL(3, 23, 13), // "newConnection"
QT_MOC_LITERAL(4, 37, 18), // "appendToSocketList"
QT_MOC_LITERAL(5, 56, 11), // "QTcpSocket*"
QT_MOC_LITERAL(6, 68, 6), // "socket"
QT_MOC_LITERAL(7, 75, 10), // "readSocket"
QT_MOC_LITERAL(8, 86, 13), // "discardSocket"
QT_MOC_LITERAL(9, 100, 12), // "displayError"
QT_MOC_LITERAL(10, 113, 28), // "QAbstractSocket::SocketError"
QT_MOC_LITERAL(11, 142, 11), // "socketError"
QT_MOC_LITERAL(12, 154, 14), // "displayMessage"
QT_MOC_LITERAL(13, 169, 3), // "str"
QT_MOC_LITERAL(14, 173, 11), // "sendMessage"
QT_MOC_LITERAL(15, 185, 14), // "sendAttachment"
QT_MOC_LITERAL(16, 200, 8), // "filePath"
QT_MOC_LITERAL(17, 209, 33), // "on_pushButton_sendMessage_cli..."
QT_MOC_LITERAL(18, 243, 36) // "on_pushButton_sendAttachment_..."
},
"MainWindow\0newMessage\0\0newConnection\0"
"appendToSocketList\0QTcpSocket*\0socket\0"
"readSocket\0discardSocket\0displayError\0"
"QAbstractSocket::SocketError\0socketError\0"
"displayMessage\0str\0sendMessage\0"
"sendAttachment\0filePath\0"
"on_pushButton_sendMessage_clicked\0"
"on_pushButton_sendAttachment_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
11, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 69, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 72, 2, 0x08 /* Private */,
4, 1, 73, 2, 0x08 /* Private */,
7, 0, 76, 2, 0x08 /* Private */,
8, 0, 77, 2, 0x08 /* Private */,
9, 1, 78, 2, 0x08 /* Private */,
12, 1, 81, 2, 0x08 /* Private */,
14, 1, 84, 2, 0x08 /* Private */,
15, 2, 87, 2, 0x08 /* Private */,
17, 0, 92, 2, 0x08 /* Private */,
18, 0, 93, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 2,
// slots: parameters
QMetaType::Void,
QMetaType::Void, 0x80000000 | 5, 6,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void, QMetaType::QString, 13,
QMetaType::Void, 0x80000000 | 5, 6,
QMetaType::Void, 0x80000000 | 5, QMetaType::QString, 6, 16,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->newMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 1: _t->newConnection(); break;
case 2: _t->appendToSocketList((*reinterpret_cast< QTcpSocket*(*)>(_a[1]))); break;
case 3: _t->readSocket(); break;
case 4: _t->discardSocket(); break;
case 5: _t->displayError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 6: _t->displayMessage((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 7: _t->sendMessage((*reinterpret_cast< QTcpSocket*(*)>(_a[1]))); break;
case 8: _t->sendAttachment((*reinterpret_cast< QTcpSocket*(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
case 9: _t->on_pushButton_sendMessage_clicked(); break;
case 10: _t->on_pushButton_sendAttachment_clicked(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QTcpSocket* >(); break;
}
break;
case 5:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAbstractSocket::SocketError >(); break;
}
break;
case 7:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QTcpSocket* >(); break;
}
break;
case 8:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QTcpSocket* >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (MainWindow::*)(QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MainWindow::newMessage)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { {
QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(),
qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
}
return _id;
}
// SIGNAL 0
void MainWindow::newMessage(QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 36.236607 | 127 | 0.598127 | [
"object"
] |
f525f11ee6542ab51f1e3a5b4f486bf7f789d10c | 2,007 | cpp | C++ | codeforces/A - Balance the Bits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/A - Balance the Bits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/A - Balance the Bits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Apr/03/2021 20:43
* solution_verdict: Accepted language: GNU C++17 (64)
* run_time: 31 ms memory_used: 1300 KB
* problem: https://codeforces.com/contest/1503/problem/A
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
#include<chrono>
#include<stack>
#include<deque>
#include<random>
#define long long long
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N=1e6,inf=1e9,mod=1e9+7;
bool ck(string s)
{
int bl=0;
for(int i=0;i<(int)s.size();i++)
{
if(s[i]=='(')bl++;
else bl--;
if(bl<0)return false;
}
return (bl==0);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;
string s;cin>>s;
int cnt=0;
for(int i=0;i<n;i++)
if(s[i]=='0')cnt++;
if(cnt%2)
{
cout<<"NO\n";continue;
}
int one=n-cnt;
string a,b;
for(int i=0;i<n;i++)a.push_back('a'),b.push_back('a');
int f=0,now=0;
for(int i=0;i<n;i++)
{
if(s[i]=='0')
{
if(f)a[i]=')',b[i]='(';
else a[i]='(',b[i]=')';
f^=1;
}
else
{
if(now<one/2)
{
a[i]='(',b[i]='(';
now++;
}
else a[i]=')',b[i]=')';
}
}
if(ck(a) && ck(b))
{
cout<<"YES\n";
cout<<a<<'\n';
cout<<b<<'\n';
}
else cout<<"NO\n";
}
return 0;
} | 23.337209 | 111 | 0.430992 | [
"vector"
] |
f52cf6cbf2ab03c2252d539321bbf2328928350d | 2,237 | cpp | C++ | sources/dansandu/ballotin/container.test.cpp | dansandu/ballotin | e92aac53153ca85759bc412a86937b28c5dbfc4c | [
"MIT"
] | null | null | null | sources/dansandu/ballotin/container.test.cpp | dansandu/ballotin | e92aac53153ca85759bc412a86937b28c5dbfc4c | [
"MIT"
] | null | null | null | sources/dansandu/ballotin/container.test.cpp | dansandu/ballotin | e92aac53153ca85759bc412a86937b28c5dbfc4c | [
"MIT"
] | null | null | null | #include "dansandu/ballotin/container.hpp"
#include "catchorg/catch/catch.hpp"
#include <map>
#include <sstream>
#include <string>
#include <vector>
using dansandu::ballotin::container::contains;
using dansandu::ballotin::container::pop;
using dansandu::ballotin::container::uniquePushBack;
using dansandu::ballotin::container::operator<<;
TEST_CASE("container")
{
SECTION("pop")
{
auto stack = std::vector<int>{{7, 11, 13}};
REQUIRE(pop(stack) == 13);
REQUIRE(pop(stack) == 11);
REQUIRE(pop(stack) == 7);
}
SECTION("contains")
{
auto container = std::vector<int>{{3, 5, 7, 10}};
REQUIRE(contains(container, 5));
REQUIRE(!contains(container, 8));
}
SECTION("unique push back")
{
auto container = std::vector<int>{{1, 3, 5, 7}};
SECTION("unique")
{
uniquePushBack(container, 0);
REQUIRE(container == std::vector<int>{{1, 3, 5, 7, 0}});
}
SECTION("duplicate")
{
uniquePushBack(container, 3);
REQUIRE(container == std::vector<int>{{1, 3, 5, 7}});
}
}
SECTION("pretty print")
{
auto stream = std::stringstream{};
SECTION("empty vector")
{
stream << std::vector<int>{};
REQUIRE(stream.str() == "[]");
}
SECTION("singleton vector")
{
stream << std::vector<int>{1};
REQUIRE(stream.str() == "[1]");
}
SECTION("many elements vector")
{
stream << std::vector<int>{{1, 2, 3, 4}};
REQUIRE(stream.str() == "[1, 2, 3, 4]");
}
SECTION("empty map")
{
stream << std::map<std::string, int>{};
REQUIRE(stream.str() == "{}");
}
SECTION("singleton map")
{
stream << std::map<std::string, int>{{{"key", 17}}};
REQUIRE(stream.str() == "{key: 17}");
}
SECTION("many elements map")
{
stream << std::map<std::string, int>{{{"key", 17}, {"other", 20}, {"another", 23}}};
REQUIRE(stream.str() == "{another: 23, key: 17, other: 20}");
}
}
}
| 23.302083 | 96 | 0.493965 | [
"vector"
] |
f539ccb5946f8053136b28c2f50309f45d448938 | 3,893 | cpp | C++ | chromium/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/third_party/WebKit/Source/modules/credentialmanager/PasswordCredential.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/credentialmanager/PasswordCredential.h"
#include "bindings/core/v8/Dictionary.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/URLSearchParams.h"
#include "core/html/FormData.h"
#include "modules/credentialmanager/FormDataOptions.h"
#include "modules/credentialmanager/PasswordCredentialData.h"
#include "platform/credentialmanager/PlatformPasswordCredential.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "public/platform/WebCredential.h"
#include "public/platform/WebPasswordCredential.h"
namespace blink {
PasswordCredential* PasswordCredential::create(WebPasswordCredential* webPasswordCredential)
{
return new PasswordCredential(webPasswordCredential);
}
PasswordCredential* PasswordCredential::create(const PasswordCredentialData& data, ExceptionState& exceptionState)
{
KURL iconURL = parseStringAsURL(data.iconURL(), exceptionState);
if (exceptionState.hadException())
return nullptr;
return new PasswordCredential(data.id(), data.password(), data.name(), iconURL);
}
PasswordCredential::PasswordCredential(WebPasswordCredential* webPasswordCredential)
: Credential(webPasswordCredential->platformCredential())
, m_idName("username")
, m_passwordName("password")
{
}
PasswordCredential::PasswordCredential(const String& id, const String& password, const String& name, const KURL& icon)
: Credential(PlatformPasswordCredential::create(id, password, name, icon))
, m_idName("username")
, m_passwordName("password")
{
}
PassRefPtr<EncodedFormData> PasswordCredential::encodeFormData(String& contentType) const
{
if (m_additionalData.isURLSearchParams()) {
// If |additionalData| is a 'URLSearchParams' object, build a urlencoded response.
URLSearchParams* params = URLSearchParams::create(URLSearchParamsInit());
URLSearchParams* additionalData = m_additionalData.getAsURLSearchParams();
for (const auto& param : additionalData->params()) {
const String& name = param.first;
if (name != idName() && name != passwordName())
params->append(name, param.second);
}
params->append(idName(), id());
params->append(passwordName(), password());
contentType = AtomicString("application/x-www-form-urlencoded;charset=UTF-8", AtomicString::ConstructFromLiteral);
return params->encodeFormData();
}
// Otherwise, we'll build a multipart response.
FormData* formData = FormData::create(nullptr);
if (m_additionalData.isFormData()) {
FormData* additionalData = m_additionalData.getAsFormData();
for (const FormData::Entry* entry : additionalData->entries()) {
const String& name = formData->decode(entry->name());
if (name == idName() || name == passwordName())
continue;
if (entry->blob())
formData->append(name, entry->blob(), entry->filename());
else
formData->append(name, formData->decode(entry->value()));
}
}
formData->append(idName(), id());
formData->append(passwordName(), password());
RefPtr<EncodedFormData> encodedData = formData->encodeMultiPartFormData();
contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + encodedData->boundary().data();
return encodedData.release();
}
const String& PasswordCredential::password() const
{
return static_cast<PlatformPasswordCredential*>(m_platformCredential.get())->password();
}
DEFINE_TRACE(PasswordCredential)
{
Credential::trace(visitor);
visitor->trace(m_additionalData);
}
} // namespace blink
| 38.166667 | 134 | 0.71513 | [
"object"
] |
f53a64eb420e1cc1b05df7f90f78a5520f12466c | 47,877 | cxx | C++ | VelodyneHDL/vtkVelodyneHDLReader.cxx | yajin1126/C-Users-yajin-Documents-veloview | aa1286abf5232827a3fac625146f69cbdb72a97a | [
"Apache-2.0"
] | null | null | null | VelodyneHDL/vtkVelodyneHDLReader.cxx | yajin1126/C-Users-yajin-Documents-veloview | aa1286abf5232827a3fac625146f69cbdb72a97a | [
"Apache-2.0"
] | null | null | null | VelodyneHDL/vtkVelodyneHDLReader.cxx | yajin1126/C-Users-yajin-Documents-veloview | aa1286abf5232827a3fac625146f69cbdb72a97a | [
"Apache-2.0"
] | null | null | null | // Copyright 2013 Velodyne Acoustics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*=========================================================================
Program: Visualization Toolkit
Module: vtkVelodyneHDLReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkVelodyneHDLReader.h"
#include "vtkPacketFileReader.h"
#include "vtkPacketFileWriter.h"
#include "vtkVelodyneTransformInterpolator.h"
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkMath.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkUnsignedIntArray.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnsignedShortArray.h>
#include <vtkTransform.h>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/filesystem.hpp>
#ifdef _MSC_VER
# include <boost/cstdint.hpp>
typedef boost::uint8_t uint8_t;
#else
# include <stdint.h>
#endif
namespace
{
#define HDL_Grabber_toRadians(x) ((x) * vtkMath::Pi() / 180.0)
const int HDL_NUM_ROT_ANGLES = 36001;
const int HDL_LASER_PER_FIRING = 32;
const int HDL_MAX_NUM_LASERS = 64;
const int HDL_FIRING_PER_PKT = 12;
enum HDLBlock
{
BLOCK_0_TO_31 = 0xeeff,
BLOCK_32_TO_63 = 0xddff
};
#pragma pack(push, 1)
typedef struct HDLLaserReturn
{
unsigned short distance;
unsigned char intensity;
} HDLLaserReturn;
struct HDLFiringData
{
unsigned short blockIdentifier;
unsigned short rotationalPosition;
HDLLaserReturn laserReturns[HDL_LASER_PER_FIRING];
};
struct HDLDataPacket
{
HDLFiringData firingData[HDL_FIRING_PER_PKT];
unsigned int gpsTimestamp;
unsigned char blank1;
unsigned char blank2;
};
struct HDLLaserCorrection
{
double azimuthCorrection;
double verticalCorrection;
double distanceCorrection;
double verticalOffsetCorrection;
double horizontalOffsetCorrection;
double sinVertCorrection;
double cosVertCorrection;
double sinVertOffsetCorrection;
double cosVertOffsetCorrection;
};
struct HDLRGB
{
uint8_t r;
uint8_t g;
uint8_t b;
};
#pragma pack(pop)
//-----------------------------------------------------------------------------
int MapFlags(unsigned int flags, unsigned int low, unsigned int high)
{
return (flags & low ? -1 : flags & high ? 1 : 0);
}
//-----------------------------------------------------------------------------
int MapDistanceFlag(unsigned int flags)
{
return MapFlags(flags & vtkVelodyneHDLReader::DUAL_DISTANCE_MASK,
vtkVelodyneHDLReader::DUAL_DISTANCE_NEAR,
vtkVelodyneHDLReader::DUAL_DISTANCE_FAR);
}
//-----------------------------------------------------------------------------
int MapIntensityFlag(unsigned int flags)
{
return MapFlags(flags & vtkVelodyneHDLReader::DUAL_INTENSITY_MASK,
vtkVelodyneHDLReader::DUAL_INTENSITY_LOW,
vtkVelodyneHDLReader::DUAL_INTENSITY_HIGH);
}
//-----------------------------------------------------------------------------
double HDL32AdjustTimeStamp(int firingblock,
int dsr)
{
return (firingblock * 46.08) + (dsr * 1.152);
}
//-----------------------------------------------------------------------------
double VLP16AdjustTimeStamp(int firingblock,
int dsr,
int firingwithinblock)
{
return (firingblock * 110.592) + (dsr * 2.304) + (firingwithinblock * 55.296);
}
}
//-----------------------------------------------------------------------------
class vtkVelodyneHDLReader::vtkInternal
{
public:
vtkInternal()
{
this->Skip = 0;
this->LastAzimuth = -1;
this->LastTimestamp = std::numeric_limits<unsigned int>::max();
this->TimeAdjust = std::numeric_limits<double>::quiet_NaN();
this->Reader = 0;
this->SplitCounter = 0;
this->NumberOfTrailingFrames = 0;
this->ApplyTransform = 0;
this->PointsSkip = 0;
this->CropReturns = false;
this->CropInside = false;
this->CropRegion[0] = this->CropRegion[1] = 0.0;
this->CropRegion[2] = this->CropRegion[3] = 0.0;
this->CropRegion[4] = this->CropRegion[5] = 0.0;
this->CorrectionsInitialized = false;
std::fill(this->LastPointId, this->LastPointId + HDL_MAX_NUM_LASERS, -1);
this->LaserSelection.resize(64, true);
this->DualReturnFilter = 0;
this->IsDualReturnData = false;
this->IsHDL64Data = false;
this->Init();
}
~vtkInternal()
{
}
std::vector<vtkSmartPointer<vtkPolyData> > Datasets;
vtkSmartPointer<vtkPolyData> CurrentDataset;
vtkNew<vtkTransform> SensorTransform;
vtkSmartPointer<vtkVelodyneTransformInterpolator> Interp;
vtkSmartPointer<vtkPoints> Points;
vtkSmartPointer<vtkUnsignedCharArray> Intensity;
vtkSmartPointer<vtkUnsignedCharArray> LaserId;
vtkSmartPointer<vtkUnsignedShortArray> Azimuth;
vtkSmartPointer<vtkDoubleArray> Distance;
vtkSmartPointer<vtkDoubleArray> Timestamp;
vtkSmartPointer<vtkUnsignedIntArray> RawTime;
vtkSmartPointer<vtkIntArray> IntensityFlag;
vtkSmartPointer<vtkIntArray> DistanceFlag;
vtkSmartPointer<vtkUnsignedIntArray> Flags;
bool IsDualReturnData;
bool IsHDL64Data;
int LastAzimuth;
unsigned int LastTimestamp;
double TimeAdjust;
vtkIdType LastPointId[HDL_MAX_NUM_LASERS];
vtkIdType FirstPointIdThisReturn;
std::vector<fpos_t> FilePositions;
std::vector<int> Skips;
int Skip;
vtkPacketFileReader* Reader;
int SplitCounter;
// Parameters ready by calibration
std::vector<double> cos_lookup_table_;
std::vector<double> sin_lookup_table_;
HDLLaserCorrection laser_corrections_[HDL_MAX_NUM_LASERS];
int CalibrationReportedNumLasers;
bool CorrectionsInitialized;
// User configurable parameters
int NumberOfTrailingFrames;
int ApplyTransform;
int PointsSkip;
bool CropReturns;
bool CropInside;
double CropRegion[6];
std::vector<bool> LaserSelection;
unsigned int DualReturnFilter;
void SplitFrame(bool force=false);
vtkSmartPointer<vtkPolyData> CreateData(vtkIdType numberOfPoints);
vtkSmartPointer<vtkCellArray> NewVertexCells(vtkIdType numberOfVerts);
void Init();
void InitTables();
void LoadCorrectionsFile(const std::string& filename);
void ProcessHDLPacket(unsigned char *data, std::size_t bytesReceived);
double ComputeTimestamp(unsigned int tohTime);
void ComputeOrientation(double timestamp, vtkTransform* geotransform);
// Process the laser return from the firing data
// firingData - one of HDL_FIRING_PER_PKT from the packet
// hdl64offset - either 0 or 32 to support 64-laser systems
// firingBlock - block of packet for firing [0-11]
// azimuthDiff - average azimuth change between firings
// timestamp - the timestamp of the packet
// geotransform - georeferencing transform
void ProcessFiring(HDLFiringData* firingData,
int hdl65offset,
int firingBlock,
int azimuthDiff,
double timestamp,
unsigned int rawtime,
vtkTransform* geotransform);
void PushFiringData(const unsigned char laserId,
const unsigned char rawLaserId,
unsigned short azimuth,
const double timestamp,
const unsigned int rawtime,
const HDLLaserReturn* laserReturn,
const HDLLaserCorrection* correction,
vtkTransform* geotransform,
bool dualReturn);
};
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkVelodyneHDLReader);
//-----------------------------------------------------------------------------
vtkVelodyneHDLReader::vtkVelodyneHDLReader()
{
this->Internal = new vtkInternal;
this->UnloadData();
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
//-----------------------------------------------------------------------------
vtkVelodyneHDLReader::~vtkVelodyneHDLReader()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
const std::string& vtkVelodyneHDLReader::GetFileName()
{
return this->FileName;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetApplyTransform(int apply)
{
if(apply != this->Internal->ApplyTransform)
{
this->Modified();
}
this->Internal->ApplyTransform = apply;
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::GetApplyTransform()
{
return this->Internal->ApplyTransform;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetSensorTransform(vtkTransform* transform)
{
if (transform)
{
this->Internal->SensorTransform->SetMatrix(transform->GetMatrix());
}
else
{
this->Internal->SensorTransform->Identity();
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkVelodyneTransformInterpolator* vtkVelodyneHDLReader::GetInterpolator() const
{
return this->Internal->Interp;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetInterpolator(
vtkVelodyneTransformInterpolator* interpolator)
{
this->Internal->Interp = interpolator;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetFileName(const std::string& filename)
{
if (filename == this->FileName)
{
return;
}
this->FileName = filename;
this->Internal->FilePositions.clear();
this->Internal->Skips.clear();
this->UnloadData();
this->Modified();
}
//-----------------------------------------------------------------------------
const std::string& vtkVelodyneHDLReader::GetCorrectionsFile()
{
return this->CorrectionsFile;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetLaserSelection(int x00, int x01, int x02, int x03, int x04, int x05, int x06, int x07,
int x08, int x09, int x10, int x11, int x12, int x13, int x14, int x15,
int x16, int x17, int x18, int x19, int x20, int x21, int x22, int x23,
int x24, int x25, int x26, int x27, int x28, int x29, int x30, int x31,
int x32, int x33, int x34, int x35, int x36, int x37, int x38, int x39,
int x40, int x41, int x42, int x43, int x44, int x45, int x46, int x47,
int x48, int x49, int x50, int x51, int x52, int x53, int x54, int x55,
int x56, int x57, int x58, int x59, int x60, int x61, int x62, int x63)
{
int mask[64] = {x00, x01, x02, x03, x04, x05, x06, x07,
x08, x09, x10, x11, x12, x13, x14, x15,
x16, x17, x18, x19, x20, x21, x22, x23,
x24, x25, x26, x27, x28, x29, x30, x31,
x32, x33, x34, x35, x36, x37, x38, x39,
x40, x41, x42, x43, x44, x45, x46, x47,
x48, x49, x50, x51, x52, x53, x54, x55,
x56, x57, x58, x59, x60, x61, x62, x63};
this->SetLaserSelection(mask);
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetLaserSelection(int LaserSelection[64])
{
for(int i = 0; i < 64; ++i)
{
this->Internal->LaserSelection[i] = LaserSelection[i];
}
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::GetLaserSelection(int LaserSelection[64])
{
for(int i = 0; i < 64; ++i)
{
LaserSelection[i] = this->Internal->LaserSelection[i];
}
}
//-----------------------------------------------------------------------------
unsigned int vtkVelodyneHDLReader::GetDualReturnFilter() const
{
return this->Internal->DualReturnFilter;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetDualReturnFilter(unsigned int filter)
{
if (this->Internal->DualReturnFilter != filter)
{
this->Internal->DualReturnFilter = filter;
this->Modified();
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::GetVerticalCorrections(double VerticalCorrections[64])
{
for(int i = 0; i < 64; ++i)
{
VerticalCorrections[i] = this->Internal->laser_corrections_[i].verticalCorrection;
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetDummyProperty(int vtkNotUsed(dummy))
{
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetPointsSkip(int pr)
{
this->Internal->PointsSkip = pr;
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetNumberOfTrailingFrames(int numTrailing)
{
assert(numTrailing >= 0);
this->Internal->NumberOfTrailingFrames = numTrailing;
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetCropReturns(int crop)
{
if (!this->Internal->CropReturns == !!crop)
{
this->Internal->CropReturns = !!crop;
this->Modified();
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetCropInside(int crop)
{
if (!this->Internal->CropInside == !!crop)
{
this->Internal->CropInside = !!crop;
this->Modified();
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetCropRegion(double region[6])
{
std::copy(region, region + 6, this->Internal->CropRegion);
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetCropRegion(
double xl, double xu, double yl, double yu, double zl, double zu)
{
this->Internal->CropRegion[0] = xl;
this->Internal->CropRegion[1] = xu;
this->Internal->CropRegion[2] = yl;
this->Internal->CropRegion[3] = yu;
this->Internal->CropRegion[4] = zl;
this->Internal->CropRegion[5] = zu;
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetCorrectionsFile(const std::string& correctionsFile)
{
if (correctionsFile == this->CorrectionsFile)
{
return;
}
if (!boost::filesystem::exists(correctionsFile) ||
boost::filesystem::is_directory(correctionsFile))
{
vtkErrorMacro("Invalid sensor configuration file" << correctionsFile);
return;
}
this->Internal->LoadCorrectionsFile(correctionsFile);
this->CorrectionsFile = correctionsFile;
this->UnloadData();
this->Modified();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::UnloadData()
{
std::fill(this->Internal->LastPointId, this->Internal->LastPointId + HDL_MAX_NUM_LASERS, -1);
this->Internal->LastAzimuth = -1;
this->Internal->LastTimestamp = std::numeric_limits<unsigned int>::max();
this->Internal->TimeAdjust = std::numeric_limits<double>::quiet_NaN();
this->Internal->IsDualReturnData = false;
this->Internal->IsHDL64Data = false;
this->Internal->Datasets.clear();
this->Internal->CurrentDataset = this->Internal->CreateData(0);
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::SetTimestepInformation(vtkInformation *info)
{
const size_t numberOfTimesteps = this->Internal->FilePositions.size();
std::vector<double> timesteps;
for (size_t i = 0; i < numberOfTimesteps; ++i)
{
timesteps.push_back(i);
}
if (numberOfTimesteps)
{
double timeRange[2] = {timesteps.front(), timesteps.back()};
info->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), ×teps.front(), timesteps.size());
info->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
}
else
{
info->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
info->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE());
}
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
vtkPolyData *output = vtkPolyData::GetData(outputVector);
vtkInformation *info = outputVector->GetInformationObject(0);
if (!this->FileName.length())
{
vtkErrorMacro("FileName has not been set.");
return 0;
}
if (!this->Internal->CorrectionsInitialized)
{
vtkErrorMacro("Corrections have not been set");
return 0;
}
int timestep = 0;
if (info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
{
double timeRequest = info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
timestep = static_cast<int>(floor(timeRequest+0.5));
}
if (timestep < 0 || timestep >= this->GetNumberOfFrames())
{
vtkErrorMacro("Cannot meet timestep request: " << timestep << ". Have " << this->GetNumberOfFrames() << " datasets.");
output->ShallowCopy(this->Internal->CreateData(0));
return 0;
}
this->Open();
if(this->Internal->NumberOfTrailingFrames > 0)
{
output->ShallowCopy(this->GetFrameRange(timestep - this->Internal->NumberOfTrailingFrames,
this->Internal->NumberOfTrailingFrames));
}
else
{
output->ShallowCopy(this->GetFrame(timestep));
}
this->Close();
return 1;
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::RequestInformation(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if (this->FileName.length() && !this->Internal->FilePositions.size())
{
this->ReadFrameInformation();
}
vtkInformation *info = outputVector->GetInformationObject(0);
this->SetTimestepInformation(info);
return 1;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "FileName: " << this->FileName << endl;
os << indent << "CorrectionsFile: " << this->CorrectionsFile << endl;
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::CanReadFile(const char *fname)
{
return 1;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::ProcessHDLPacket(unsigned char *data, unsigned int bytesReceived)
{
this->Internal->ProcessHDLPacket(data, bytesReceived);
}
//-----------------------------------------------------------------------------
std::vector<vtkSmartPointer<vtkPolyData> >& vtkVelodyneHDLReader::GetDatasets()
{
return this->Internal->Datasets;
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::GetNumberOfFrames()
{
return this->Internal->FilePositions.size();;
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::GetNumberOfChannels()
{
return this->Internal->CalibrationReportedNumLasers;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::Open()
{
this->Close();
this->Internal->Reader = new vtkPacketFileReader;
if (!this->Internal->Reader->Open(this->FileName))
{
vtkErrorMacro("Failed to open packet file: " << this->FileName << endl << this->Internal->Reader->GetLastError());
this->Close();
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::Close()
{
delete this->Internal->Reader;
this->Internal->Reader = 0;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::DumpFrames(int startFrame, int endFrame, const std::string& filename)
{
if (!this->Internal->Reader)
{
vtkErrorMacro("DumpFrames() called but packet file reader is not open.");
return;
}
vtkPacketFileWriter writer;
if (!writer.Open(filename))
{
vtkErrorMacro("Failed to open packet file for writing: " << filename);
return;
}
pcap_pkthdr* header = 0;
const unsigned char* data = 0;
unsigned int dataLength = 0;
double timeSinceStart = 0;
unsigned int lastAzimuth = 0;
int currentFrame = startFrame;
this->Internal->Reader->SetFilePosition(&this->Internal->FilePositions[startFrame]);
int skip = this->Internal->Skips[startFrame];
while (this->Internal->Reader->NextPacket(data, dataLength, timeSinceStart, &header) &&
currentFrame <= endFrame)
{
if (dataLength == (1206 + 42) ||
dataLength == (512 + 42))
{
writer.WritePacket(header, const_cast<unsigned char*>(data));
}
// dont check for frame counts if it was a GPS packet
if(dataLength != (1206 + 42))
{
continue;
}
// Check if we cycled a frame and decrement
const HDLDataPacket* dataPacket = reinterpret_cast<const HDLDataPacket *>(data + 42);
for (int i = skip; i < HDL_FIRING_PER_PKT; ++i)
{
HDLFiringData firingData = dataPacket->firingData[i];
if (firingData.rotationalPosition != 0 && firingData.rotationalPosition < lastAzimuth)
{
currentFrame++;
if(currentFrame > endFrame)
{
break;
}
}
lastAzimuth = firingData.rotationalPosition;
}
skip = 0;
}
writer.Close();
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vtkVelodyneHDLReader::GetFrameRange(int startFrame, int numberOfFrames)
{
this->UnloadData();
if (!this->Internal->Reader)
{
vtkErrorMacro("GetFrame() called but packet file reader is not open.");
return 0;
}
if (!this->Internal->CorrectionsInitialized)
{
vtkErrorMacro("Corrections have not been set");
return 0;
}
const unsigned char* data = 0;
unsigned int dataLength = 0;
double timeSinceStart = 0;
if(startFrame < 0)
{
numberOfFrames -= startFrame;
startFrame = 0;
}
assert(numberOfFrames > 0);
this->Internal->Reader->SetFilePosition(&this->Internal->FilePositions[startFrame]);
this->Internal->Skip = this->Internal->Skips[startFrame];
this->Internal->SplitCounter = numberOfFrames;
while (this->Internal->Reader->NextPacket(data, dataLength, timeSinceStart))
{
this->ProcessHDLPacket(const_cast<unsigned char*>(data), dataLength);
if (this->Internal->Datasets.size())
{
this->Internal->SplitCounter = 0;
return this->Internal->Datasets.back();
}
}
this->Internal->SplitFrame(true);
this->Internal->SplitCounter = 0;
return this->Internal->Datasets.back();
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vtkVelodyneHDLReader::GetFrame(int frameNumber)
{
this->UnloadData();
if (!this->Internal->Reader)
{
vtkErrorMacro("GetFrame() called but packet file reader is not open.");
return 0;
}
if (!this->Internal->CorrectionsInitialized)
{
vtkErrorMacro("Corrections have not been set");
return 0;
}
assert(this->Internal->FilePositions.size() == this->Internal->Skips.size());
if(frameNumber < 0 || frameNumber > this->Internal->FilePositions.size())
{
vtkErrorMacro("Invalid frame requested");
return 0;
}
const unsigned char* data = 0;
unsigned int dataLength = 0;
double timeSinceStart = 0;
this->Internal->Reader->SetFilePosition(&this->Internal->FilePositions[frameNumber]);
this->Internal->Skip = this->Internal->Skips[frameNumber];
while (this->Internal->Reader->NextPacket(data, dataLength, timeSinceStart))
{
this->ProcessHDLPacket(const_cast<unsigned char*>(data), dataLength);
if (this->Internal->Datasets.size())
{
return this->Internal->Datasets.back();
}
}
this->Internal->SplitFrame();
return this->Internal->Datasets.back();
}
namespace
{
template <typename T>
vtkSmartPointer<T> CreateDataArray(const char* name, vtkIdType np, vtkPolyData* pd)
{
vtkSmartPointer<T> array = vtkSmartPointer<T>::New();
array->Allocate(60000);
array->SetName(name);
array->SetNumberOfTuples(np);
if (pd)
{
pd->GetPointData()->AddArray(array);
}
return array;
}
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vtkVelodyneHDLReader::vtkInternal::CreateData(vtkIdType numberOfPoints)
{
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
// points
vtkNew<vtkPoints> points;
points->SetDataTypeToFloat();
points->Allocate(60000);
points->SetNumberOfPoints(numberOfPoints);
points->GetData()->SetName("Points_m_XYZ");
polyData->SetPoints(points.GetPointer());
polyData->SetVerts(NewVertexCells(numberOfPoints));
// intensity
this->Points = points.GetPointer();
this->Intensity = CreateDataArray<vtkUnsignedCharArray>("intensity", numberOfPoints, polyData);
this->LaserId = CreateDataArray<vtkUnsignedCharArray>("laser_id", numberOfPoints, polyData);
this->Azimuth = CreateDataArray<vtkUnsignedShortArray>("azimuth", numberOfPoints, polyData);
this->Distance = CreateDataArray<vtkDoubleArray>("distance_m", numberOfPoints, polyData);
this->Timestamp = CreateDataArray<vtkDoubleArray>("adjustedtime", numberOfPoints, polyData);
this->RawTime = CreateDataArray<vtkUnsignedIntArray>("timestamp", numberOfPoints, polyData);
this->DistanceFlag = CreateDataArray<vtkIntArray>("dual_distance", numberOfPoints, 0);
this->IntensityFlag = CreateDataArray<vtkIntArray>("dual_intensity", numberOfPoints, 0);
this->Flags = CreateDataArray<vtkUnsignedIntArray>("dual_flags", numberOfPoints, 0);
if (this->IsDualReturnData)
{
polyData->GetPointData()->AddArray(this->DistanceFlag.GetPointer());
polyData->GetPointData()->AddArray(this->IntensityFlag.GetPointer());
}
return polyData;
}
//----------------------------------------------------------------------------
vtkSmartPointer<vtkCellArray> vtkVelodyneHDLReader::vtkInternal::NewVertexCells(vtkIdType numberOfVerts)
{
vtkNew<vtkIdTypeArray> cells;
cells->SetNumberOfValues(numberOfVerts*2);
vtkIdType* ids = cells->GetPointer(0);
for (vtkIdType i = 0; i < numberOfVerts; ++i)
{
ids[i*2] = 1;
ids[i*2+1] = i;
}
vtkSmartPointer<vtkCellArray> cellArray = vtkSmartPointer<vtkCellArray>::New();
cellArray->SetCells(numberOfVerts, cells.GetPointer());
return cellArray;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::PushFiringData(const unsigned char laserId,
const unsigned char rawLaserId,
unsigned short azimuth,
const double timestamp,
const unsigned int rawtime,
const HDLLaserReturn* laserReturn,
const HDLLaserCorrection* correction,
vtkTransform* geotransform,
const bool dualReturn)
{
azimuth %= 36000;
const vtkIdType thisPointId = this->Points->GetNumberOfPoints();
const short intensity = laserReturn->intensity;
double cosAzimuth, sinAzimuth;
if (correction->azimuthCorrection == 0)
{
cosAzimuth = this->cos_lookup_table_[azimuth];
sinAzimuth = this->sin_lookup_table_[azimuth];
}
else
{
double azimuthInRadians = HDL_Grabber_toRadians((static_cast<double> (azimuth) / 100.0) - correction->azimuthCorrection);
cosAzimuth = std::cos (azimuthInRadians);
sinAzimuth = std::sin (azimuthInRadians);
}
double distanceM = laserReturn->distance * 0.002 + correction->distanceCorrection;
double xyDistance = distanceM * correction->cosVertCorrection;
// Compute raw position
double pos[3] =
{
xyDistance * sinAzimuth - correction->horizontalOffsetCorrection * cosAzimuth,
xyDistance * cosAzimuth + correction->horizontalOffsetCorrection * sinAzimuth,
distanceM * correction->sinVertCorrection + correction->verticalOffsetCorrection
};
// Apply sensor transform
this->SensorTransform->InternalTransformPoint(pos, pos);
// Test if point is cropped
if (this->CropReturns)
{
bool pointOutsideOfBox = pos[0] >= this->CropRegion[0] && pos[0] <= this->CropRegion[1] &&
pos[1] >= this->CropRegion[2] && pos[1] <= this->CropRegion[3] &&
pos[2] >= this->CropRegion[4] && pos[2] <= this->CropRegion[5];
if ((pointOutsideOfBox && !this->CropInside) ||
(!pointOutsideOfBox && this->CropInside))
{
return;
}
}
// Do not add any data before here as this might short-circuit
if (dualReturn)
{
const vtkIdType dualPointId = this->LastPointId[rawLaserId];
if (dualPointId < this->FirstPointIdThisReturn)
{
// No matching point from first set (skipped?)
this->Flags->InsertNextValue(DUAL_DOUBLED);
this->DistanceFlag->InsertNextValue(0);
this->IntensityFlag->InsertNextValue(0);
}
else
{
const short dualIntensity = this->Intensity->GetValue(dualPointId);
const double dualDistance = this->Distance->GetValue(dualPointId);
unsigned int firstFlags = this->Flags->GetValue(dualPointId);
unsigned int secondFlags = 0;
if (dualDistance == distanceM && intensity == dualIntensity)
{
// ignore duplicate point and leave first with original flags
return;
}
if (dualIntensity < intensity)
{
firstFlags &= ~DUAL_INTENSITY_HIGH;
secondFlags |= DUAL_INTENSITY_HIGH;
}
else
{
firstFlags &= ~DUAL_INTENSITY_LOW;
secondFlags |= DUAL_INTENSITY_LOW;
}
if (dualDistance < distanceM)
{
firstFlags &= ~DUAL_DISTANCE_FAR;
secondFlags |= DUAL_DISTANCE_FAR;
}
else
{
firstFlags &= ~DUAL_DISTANCE_NEAR;
secondFlags |= DUAL_DISTANCE_NEAR;
}
// We will output only one point so return out of this
if (this->DualReturnFilter)
{
if (!(secondFlags & this->DualReturnFilter))
{
// second return does not match filter; skip
this->Flags->SetValue(dualPointId, firstFlags);
this->DistanceFlag->SetValue(dualPointId, MapDistanceFlag(firstFlags));
this->IntensityFlag->SetValue(dualPointId, MapIntensityFlag(firstFlags));
return;
}
if (!(firstFlags & this->DualReturnFilter))
{
// first return does not match filter; replace with second return
this->Points->SetPoint(dualPointId, pos);
this->Distance->SetValue(dualPointId, distanceM);
this->Intensity->SetValue(dualPointId, laserReturn->intensity);
this->Timestamp->SetValue(dualPointId, timestamp);
this->RawTime->SetValue(dualPointId, rawtime);
this->Flags->SetValue(dualPointId, secondFlags);
this->DistanceFlag->SetValue(dualPointId, MapDistanceFlag(secondFlags));
this->IntensityFlag->SetValue(dualPointId, MapIntensityFlag(secondFlags));
return;
}
}
this->Flags->SetValue(dualPointId, firstFlags);
this->DistanceFlag->SetValue(dualPointId, MapDistanceFlag(firstFlags));
this->IntensityFlag->SetValue(dualPointId, MapIntensityFlag(firstFlags));
this->Flags->InsertNextValue(secondFlags);
this->DistanceFlag->InsertNextValue(MapDistanceFlag(secondFlags));
this->IntensityFlag->InsertNextValue(MapIntensityFlag(secondFlags));
}
}
else
{
this->Flags->InsertNextValue(DUAL_DOUBLED);
this->DistanceFlag->InsertNextValue(0);
this->IntensityFlag->InsertNextValue(0);
}
// Apply geoposition transform
geotransform->InternalTransformPoint(pos, pos);
this->Points->InsertNextPoint(pos);
this->Azimuth->InsertNextValue(azimuth);
this->Intensity->InsertNextValue(laserReturn->intensity);
this->LaserId->InsertNextValue(laserId);
this->Timestamp->InsertNextValue(timestamp);
this->RawTime->InsertNextValue(rawtime);
this->Distance->InsertNextValue(distanceM);
this->LastPointId[rawLaserId] = thisPointId;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::InitTables()
{
if (cos_lookup_table_.size() == 0 || sin_lookup_table_.size() == 0)
{
cos_lookup_table_.resize(HDL_NUM_ROT_ANGLES);
sin_lookup_table_.resize(HDL_NUM_ROT_ANGLES);
for (unsigned int i = 0; i < HDL_NUM_ROT_ANGLES; i++)
{
double rad = HDL_Grabber_toRadians(i / 100.0);
cos_lookup_table_[i] = std::cos(rad);
sin_lookup_table_[i] = std::sin(rad);
}
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::LoadCorrectionsFile(const std::string& correctionsFile)
{
boost::property_tree::ptree pt;
try
{
read_xml(correctionsFile, pt, boost::property_tree::xml_parser::trim_whitespace);
}
catch (boost::exception const&)
{
vtkGenericWarningMacro("LoadCorrectionsFile: error reading calibration file: " << correctionsFile);
return;
}
int enabledCount = 0;
BOOST_FOREACH (boost::property_tree::ptree::value_type &v, pt.get_child("boost_serialization.DB.enabled_"))
{
std::stringstream ss;
if(v.first == "item")
{
ss << v.second.data();
int test = 0;
ss >> test;
if(!ss.fail() && test == 1)
{
enabledCount++;
}
}
}
this->CalibrationReportedNumLasers = enabledCount;
BOOST_FOREACH (boost::property_tree::ptree::value_type &v, pt.get_child("boost_serialization.DB.points_"))
{
if (v.first == "item")
{
boost::property_tree::ptree points = v.second;
BOOST_FOREACH (boost::property_tree::ptree::value_type &px, points)
{
if (px.first == "px")
{
boost::property_tree::ptree calibrationData = px.second;
int index = -1;
double azimuth = 0;
double vertCorrection = 0;
double distCorrection = 0;
double vertOffsetCorrection = 0;
double horizOffsetCorrection = 0;
BOOST_FOREACH (boost::property_tree::ptree::value_type &item, calibrationData)
{
if (item.first == "id_")
index = atoi(item.second.data().c_str());
if (item.first == "rotCorrection_")
azimuth = atof(item.second.data().c_str());
if (item.first == "vertCorrection_")
vertCorrection = atof(item.second.data().c_str());
if (item.first == "distCorrection_")
distCorrection = atof(item.second.data().c_str());
if (item.first == "vertOffsetCorrection_")
vertOffsetCorrection = atof(item.second.data().c_str());
if (item.first == "horizOffsetCorrection_")
horizOffsetCorrection = atof(item.second.data().c_str());
}
if (index != -1)
{
laser_corrections_[index].azimuthCorrection = azimuth;
laser_corrections_[index].verticalCorrection = vertCorrection;
laser_corrections_[index].distanceCorrection = distCorrection / 100.0;
laser_corrections_[index].verticalOffsetCorrection = vertOffsetCorrection / 100.0;
laser_corrections_[index].horizontalOffsetCorrection = horizOffsetCorrection / 100.0;
laser_corrections_[index].cosVertCorrection = std::cos (HDL_Grabber_toRadians(laser_corrections_[index].verticalCorrection));
laser_corrections_[index].sinVertCorrection = std::sin (HDL_Grabber_toRadians(laser_corrections_[index].verticalCorrection));
}
}
}
}
}
for (int i = 0; i < HDL_MAX_NUM_LASERS; i++)
{
HDLLaserCorrection correction = laser_corrections_[i];
laser_corrections_[i].sinVertOffsetCorrection = correction.verticalOffsetCorrection
* correction.sinVertCorrection;
laser_corrections_[i].cosVertOffsetCorrection = correction.verticalOffsetCorrection
* correction.cosVertCorrection;
}
this->CorrectionsInitialized = true;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::Init()
{
this->InitTables();
this->SensorTransform->Identity();
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::SplitFrame(bool force)
{
if(this->SplitCounter > 0 && !force)
{
this->SplitCounter--;
return;
}
for (size_t n = 0; n < HDL_MAX_NUM_LASERS; ++n)
{
this->LastPointId[n] = -1;
}
this->CurrentDataset->SetVerts(this->NewVertexCells(this->CurrentDataset->GetNumberOfPoints()));
this->Datasets.push_back(this->CurrentDataset);
this->CurrentDataset = this->CreateData(0);
}
//-----------------------------------------------------------------------------
double vtkVelodyneHDLReader::vtkInternal::ComputeTimestamp(
unsigned int tohTime)
{
static const double hourInMilliseconds = 3600.0 * 1e6;
if (tohTime < this->LastTimestamp)
{
if (!vtkMath::IsFinite(this->TimeAdjust))
{
// First adjustment; must compute adjustment number
if (this->Interp && this->Interp->GetNumberOfTransforms())
{
const double ts = static_cast<double>(tohTime) * 1e-6;
const double hours = (this->Interp->GetMinimumT() - ts) / 3600.0;
this->TimeAdjust = vtkMath::Round(hours) * hourInMilliseconds;
}
else
{
// Ought to warn about this, but happens when applogic is checking that
// we can read the file :-(
this->TimeAdjust = 0;
}
}
else
{
// Hour has wrapped; add an hour to the update adjustment value
this->TimeAdjust += hourInMilliseconds;
}
}
this->LastTimestamp = tohTime;
return static_cast<double>(tohTime) + this->TimeAdjust;
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::ComputeOrientation(
double timestamp, vtkTransform* geotransform)
{
if(this->ApplyTransform && this->Interp && this->Interp->GetNumberOfTransforms())
{
// NOTE: We store time in milliseconds, but the interpolator uses seconds,
// so we need to adjust here
const double t = timestamp * 1e-6;
this->Interp->InterpolateTransform(t, geotransform);
}
else
{
geotransform->Identity();
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::ProcessFiring(HDLFiringData* firingData,
int hdl64offset,
int firingBlock,
int azimuthDiff,
double timestamp,
unsigned int rawtime,
vtkTransform* geotransform)
{
const bool dual = (this->LastAzimuth == firingData->rotationalPosition) &&
(!this->IsHDL64Data);
if (!dual)
{
this->FirstPointIdThisReturn = this->Points->GetNumberOfPoints();
}
if (dual && !this->IsDualReturnData)
{
this->IsDualReturnData = true;
this->CurrentDataset->GetPointData()->AddArray(this->DistanceFlag.GetPointer());
this->CurrentDataset->GetPointData()->AddArray(this->IntensityFlag.GetPointer());
}
for (int dsr = 0; dsr < HDL_LASER_PER_FIRING; dsr++)
{
unsigned char rawLaserId = static_cast<unsigned char>(dsr + hdl64offset);
unsigned char laserId = rawLaserId;
unsigned short azimuth = firingData->rotationalPosition;
// Detect VLP-16 data and adjust laser id if necessary
int firingWithinBlock = 0;
if(this->CalibrationReportedNumLasers == 16)
{
assert(hdl64offset == 0);
if(laserId >= 16)
{
laserId -= 16;
firingWithinBlock = 1;
}
}
// Interpolate azimuth
double timestampadjustment = 0.0;
double blockdsr0 = 0.0;
double nextblockdsr0 = 1.0;
if(this->CalibrationReportedNumLasers == 32)
{
timestampadjustment = HDL32AdjustTimeStamp(firingBlock, dsr);
nextblockdsr0 = HDL32AdjustTimeStamp(firingBlock+1,0);
blockdsr0 = HDL32AdjustTimeStamp(firingBlock,0);
}
else if(this->CalibrationReportedNumLasers == 16)
{
timestampadjustment = VLP16AdjustTimeStamp(firingBlock, laserId, firingWithinBlock);
nextblockdsr0 = VLP16AdjustTimeStamp(firingBlock+1,0,0);
blockdsr0 = VLP16AdjustTimeStamp(firingBlock,0,0);
}
int azimuthadjustment = vtkMath::Round(azimuthDiff * ((timestampadjustment - blockdsr0) / (nextblockdsr0 - blockdsr0)));
timestampadjustment = vtkMath::Round(timestampadjustment);
if (firingData->laserReturns[dsr].distance != 0.0 && this->LaserSelection[laserId])
{
this->PushFiringData(laserId,
rawLaserId,
azimuth + azimuthadjustment,
timestamp + timestampadjustment,
rawtime + static_cast<unsigned int>(timestampadjustment),
&(firingData->laserReturns[dsr]),
&(laser_corrections_[dsr + hdl64offset]),
geotransform,
dual);
}
}
}
//-----------------------------------------------------------------------------
void vtkVelodyneHDLReader::vtkInternal::ProcessHDLPacket(unsigned char *data, std::size_t bytesReceived)
{
if (bytesReceived != 1206)
{
return;
}
HDLDataPacket* dataPacket = reinterpret_cast<HDLDataPacket *>(data);
vtkNew<vtkTransform> geotransform;
const unsigned int rawtime = dataPacket->gpsTimestamp;
const double timestamp = this->ComputeTimestamp(dataPacket->gpsTimestamp);
this->ComputeOrientation(timestamp, geotransform.GetPointer());
// Update the transforms here and then call internal
// transform
this->SensorTransform->Update();
geotransform->Update();
int firingBlock = this->Skip;
this->Skip = 0;
std::vector<int> diffs (HDL_FIRING_PER_PKT - 1);
for(int i = 0; i < HDL_FIRING_PER_PKT - 1; ++i)
{
int localDiff = (36000 + dataPacket->firingData[i+1].rotationalPosition -
dataPacket->firingData[i].rotationalPosition) % 36000;
diffs[i] = localDiff;
}
std::nth_element(diffs.begin(),
diffs.begin() + HDL_FIRING_PER_PKT/2,
diffs.end());
int azimuthDiff = diffs[HDL_FIRING_PER_PKT/2];
assert(azimuthDiff >= 0);
for ( ; firingBlock < HDL_FIRING_PER_PKT; ++firingBlock)
{
HDLFiringData* firingData = &(dataPacket->firingData[firingBlock]);
int hdl64offset = (firingData->blockIdentifier == BLOCK_0_TO_31) ? 0 : 32;
this->IsHDL64Data |= (hdl64offset > 0);
if (firingData->rotationalPosition < this->LastAzimuth)
{
this->SplitFrame();
}
// Skip this firing every PointSkip
if(this->PointsSkip == 0 || firingBlock % (this->PointsSkip + 1) == 0)
{
this->ProcessFiring(firingData,
hdl64offset,
firingBlock,
azimuthDiff,
timestamp,
rawtime,
geotransform.GetPointer());
}
this->LastAzimuth = firingData->rotationalPosition;
}
}
//-----------------------------------------------------------------------------
int vtkVelodyneHDLReader::ReadFrameInformation()
{
vtkPacketFileReader reader;
if (!reader.Open(this->FileName))
{
vtkErrorMacro("Failed to open packet file: " << this->FileName << endl << reader.GetLastError());
return 0;
}
const unsigned char* data = 0;
unsigned int dataLength = 0;
double timeSinceStart = 0;
unsigned int lastAzimuth = 0;
unsigned int lastTimestamp = 0;
std::vector<fpos_t> filePositions;
std::vector<int> skips;
fpos_t lastFilePosition;
reader.GetFilePosition(&lastFilePosition);
filePositions.push_back(lastFilePosition);
skips.push_back(0);
while (reader.NextPacket(data, dataLength, timeSinceStart))
{
if (dataLength != 1206)
{
continue;
}
const HDLDataPacket* dataPacket = reinterpret_cast<const HDLDataPacket *>(data);
// unsigned int timeDiff = dataPacket->gpsTimestamp - lastTimestamp;
// if (timeDiff > 600 && lastTimestamp != 0)
// {
// printf("missed %d packets\n", static_cast<int>(floor((timeDiff/553.0) + 0.5)));
// }
for (int i = 0; i < HDL_FIRING_PER_PKT; ++i)
{
HDLFiringData firingData = dataPacket->firingData[i];
if (firingData.rotationalPosition < lastAzimuth)
{
filePositions.push_back(lastFilePosition);
skips.push_back(i);
this->UpdateProgress(0.0);
}
lastAzimuth = firingData.rotationalPosition;
}
lastTimestamp = dataPacket->gpsTimestamp;
reader.GetFilePosition(&lastFilePosition);
}
this->Internal->FilePositions = filePositions;
this->Internal->Skips = skips;
return this->GetNumberOfFrames();
}
| 32.702869 | 137 | 0.594711 | [
"vector",
"transform"
] |
f53e81b7d5331ed307f4093ef676021b8ff87065 | 5,504 | cpp | C++ | tests/Cxx/TestXdmfRegularGrid.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 4 | 2015-12-07T08:11:06.000Z | 2020-06-15T01:39:07.000Z | tests/Cxx/TestXdmfRegularGrid.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 1 | 2020-04-26T16:50:37.000Z | 2020-04-26T16:50:37.000Z | tests/Cxx/TestXdmfRegularGrid.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 4 | 2016-04-04T20:54:31.000Z | 2020-06-15T01:39:08.000Z | #include "XdmfArray.hpp"
#include "XdmfGeometry.hpp"
#include "XdmfGeometryType.hpp"
#include "XdmfReader.hpp"
#include "XdmfRegularGrid.hpp"
#include "XdmfTopology.hpp"
#include "XdmfTopologyType.hpp"
#include "XdmfWriter.hpp"
#include "XdmfTestCompareFiles.hpp"
#include <iostream>
int main(int, char **)
{
shared_ptr<XdmfRegularGrid> grid = XdmfRegularGrid::New(1, 1, 1,
1, 1, 1,
0, 0, 0);
shared_ptr<XdmfArray> brickSize = grid->getBrickSize();
std::cout << brickSize->getSize() << " ?= " << 3 << std::endl;
assert(brickSize->getSize() == 3);
for(unsigned int i=0; i<brickSize->getSize(); ++i) {
std::cout << brickSize->getValue<unsigned int>(i) << " ?= " << 1 << std::endl;
assert(brickSize->getValue<unsigned int>(i) == 1);
}
shared_ptr<XdmfArray> dimensions = grid->getDimensions();
std::cout << dimensions->getSize() << " ?= " << 3 << std::endl;
assert(dimensions->getSize() == 3);
for(unsigned int i=0; i<dimensions->getSize(); ++i) {
std::cout << dimensions->getValue<unsigned int>(i) << " ?= " << 1 << std::endl;
assert(dimensions->getValue<unsigned int>(i) == 1);
}
shared_ptr<XdmfArray> origin = grid->getOrigin();
std::cout << origin->getSize() << " ?= " << 3 << std::endl;
assert(origin->getSize() == 3);
for(unsigned int i=0; i<origin->getSize(); ++i) {
std::cout << origin->getValue<unsigned int>(i) << " ?= " << 0 << std::endl;
assert(origin->getValue<unsigned int>(i) == 0);
}
// Setting brickSize, dimensions, origin
shared_ptr<XdmfArray> newBrickSize = XdmfArray::New();
newBrickSize->initialize<double>(3);
newBrickSize->insert(0, 2);
newBrickSize->insert(1, 2);
newBrickSize->insert(2, 2);
grid->setBrickSize(newBrickSize);
brickSize = grid->getBrickSize();
std::cout << brickSize->getSize() << " ?= " << 3 << std::endl;
assert(brickSize->getSize() == 3);
for(unsigned int i=0; i<brickSize->getSize(); ++i) {
std::cout << brickSize->getValue<unsigned int>(i) << " ?= " << 2 << std::endl;
assert(brickSize->getValue<unsigned int>(i) == 2);
}
shared_ptr<XdmfArray> newDimensions = XdmfArray::New();
newDimensions->initialize<unsigned int>(3);
newDimensions->insert(0, 2);
newDimensions->insert(1, 2);
newDimensions->insert(2, 2);
grid->setDimensions(newDimensions);
dimensions = grid->getDimensions();
std::cout << dimensions->getSize() << " ?= " << 3 << std::endl;
assert(dimensions->getSize() == 3);
for(unsigned int i=0; i<dimensions->getSize(); ++i) {
std::cout << dimensions->getValue<unsigned int>(i) << " ?= " << 2 << std::endl;
assert(dimensions->getValue<unsigned int>(i) == 2);
}
shared_ptr<XdmfArray> newOrigin = XdmfArray::New();
newOrigin->initialize<double>(3);
newOrigin->insert(0, 1);
newOrigin->insert(1, 1);
newOrigin->insert(2, 1);
grid->setOrigin(newOrigin);
origin = grid->getOrigin();
std::cout << origin->getSize() << " ?= " << 3 << std::endl;
assert(origin->getSize() == 3);
for(unsigned int i=0; i<origin->getSize(); ++i) {
std::cout << origin->getValue<unsigned int>(i) << " ?= " << 1 << std::endl;
assert(origin->getValue<unsigned int>(i) == 1);
}
// Check values under the hood
shared_ptr<const XdmfTopology> topology = grid->getTopology();
std::cout << topology->getNumberElements() << " ?= " << 1 << std::endl;
assert(topology->getNumberElements() == 1);
shared_ptr<const XdmfTopologyType> topologyType = topology->getType();
std::cout << topologyType->getNodesPerElement() << " ?= " << 8 << std::endl;
assert(topologyType->getNodesPerElement() == 8);
shared_ptr<const XdmfGeometry> geometry = grid->getGeometry();
std::cout << geometry->getNumberPoints() << " ?= " << 8 << std::endl;
assert(geometry->getNumberPoints() == 8);
shared_ptr<const XdmfGeometryType> geometryType = geometry->getType();
std::cout << geometryType->getDimensions() << " ?= " << 3 << std::endl;
assert(geometryType->getDimensions() == 3);
// Input / Output
shared_ptr<XdmfWriter> writer =
XdmfWriter::New("TestXdmfRegularGrid1.xmf");
grid->accept(writer);
shared_ptr<XdmfReader> reader = XdmfReader::New();
shared_ptr<XdmfRegularGrid> grid2 =
shared_dynamic_cast<XdmfRegularGrid>
(reader->read("TestXdmfRegularGrid1.xmf"));
shared_ptr<XdmfWriter> writer2 =
XdmfWriter::New("TestXdmfRegularGrid2.xmf");
grid2->accept(writer2);
if (XdmfTestCompareFiles::compareFiles("TestXdmfRegularGrid1.xmf",
"TestXdmfRegularGrid2.xmf"))
{
std::cout << "compared files match" << std::endl;
}
else
{
std::cout << "compared files do not match" << std::endl;
}
assert(XdmfTestCompareFiles::compareFiles("TestXdmfRegularGrid1.xmf",
"TestXdmfRegularGrid2.xmf"));
// Testing 1d meshes
shared_ptr<XdmfArray> origin1d = XdmfArray::New();
origin1d->pushBack(0);
shared_ptr<XdmfArray> dim1d = XdmfArray::New();
dim1d->pushBack(4);
shared_ptr<XdmfArray> brick1d = XdmfArray::New();
brick1d->pushBack(1);
shared_ptr<XdmfRegularGrid> grid3 = XdmfRegularGrid::New(origin1d, dim1d, brick1d);
shared_ptr<XdmfWriter> writer3 =
XdmfWriter::New("TestXdmfRegularGrid3.xmf");
grid3->accept(writer3);
shared_ptr<XdmfRegularGrid> readgrid =
shared_dynamic_cast<XdmfRegularGrid>(reader->read("TestXdmfRegularGrid3.xmf"));
return 0;
}
| 36.210526 | 85 | 0.634448 | [
"geometry"
] |
f54345ef390f219ddb2fabc807d11757aad83481 | 23,810 | cpp | C++ | cases_test/test_2d_fsi2/src/fsi2.cpp | spadaxsys-dev/SPADAXsys | 5b766c399ca5f8b5536548b9f88b655693b51803 | [
"Apache-2.0"
] | null | null | null | cases_test/test_2d_fsi2/src/fsi2.cpp | spadaxsys-dev/SPADAXsys | 5b766c399ca5f8b5536548b9f88b655693b51803 | [
"Apache-2.0"
] | null | null | null | cases_test/test_2d_fsi2/src/fsi2.cpp | spadaxsys-dev/SPADAXsys | 5b766c399ca5f8b5536548b9f88b655693b51803 | [
"Apache-2.0"
] | null | null | null | /**
* @file fsi2.cpp
* @brief This is the benchmark test of fliud-structure interaction.
* @details We consider a flow-induced vibration of an elastic beam behind a cylinder in 2D.
* @author Xiangyu Hu, Chi Zhang and Luhui Han
* @version 0.1
*/
/**
* @brief SPHinXsys Library.
*/
#include "sphinxsys.h"
/**
* @brief Namespace cite here.
*/
using namespace SPH;
/**
* @brief Basic geometry parameters and numerical setup.
*/
Real DL = 11.0; /**< Channel length. */
Real DH = 4.1; /**< Channel height. */
Real particle_spacing_ref = 0.1; /**< Initial reference particle spacing. */
Real DLsponge = particle_spacing_ref *20.0; /**< Sponge region to impose inflow condition. */
Real BW = particle_spacing_ref * 4.0; /**< Boundary width, determined by spcific layer of boundary patciels. */
Vec2d insert_circle_center(2.0, 2.0); /**< Location of the cylinder center. */
Real insert_circle_radius = 0.5; /**< Radius of the cylinder. */
Real bh = 0.4*insert_circle_radius; /**< Height of the beam. */
Real bl = 7.0*insert_circle_radius; /**< Length of the beam. */
/**
* @brief Geomerty of the beam. Defined through the 4 corners of a box.
*/
Real hbh = bh / 2.0;
Vec2d BLB(insert_circle_center[0], insert_circle_center[1] - hbh);
Vec2d BLT(insert_circle_center[0], insert_circle_center[1] + hbh);
Vec2d BRB(insert_circle_center[0] + insert_circle_radius + bl, insert_circle_center[1] - hbh);
Vec2d BRT(insert_circle_center[0] + insert_circle_radius + bl, insert_circle_center[1] + hbh);
/**
* @brief Material properties of the fluid.
*/
Real rho0_f = 1.0; /**< Density. */
Real U_f = 1.0; /**< Cheractristic velocity. */
Real c_f = 10.0*U_f; /**< Speed of sound. */
Real Re = 100.0; /**< Reynolds number. */
Real mu_f = rho0_f * U_f * (2.0 * insert_circle_radius) / Re; /**< Dynamics visocisty. */
Real k_f = 0.0; /**< kinetic smoothness. */
/**
* @brief Material properties of the solid,
*/
Real rho0_s = 10.0; /**< Reference density.*/
Real poisson = 0.4; /**< Poisson ratio.*/
Real Ae = 1.4e3; /**< Normalized Youngs Modulus. */
Real Youngs_modulus = Ae * rho0_f * U_f * U_f;
/**
* @brief define geometry of SPH bodies
*/
/**
* @brief create a water block shape
*/
std::vector<Point> CreatWaterBlockShape()
{
//geometry
std::vector<Point> water_block_shape;
water_block_shape.push_back(Point(-DLsponge, 0.0));
water_block_shape.push_back(Point(-DLsponge, DH));
water_block_shape.push_back(Point(DL, DH));
water_block_shape.push_back(Point(DL, 0.0));
water_block_shape.push_back(Point(-DLsponge, 0.0));
return water_block_shape;
}
/**
* @brief create a water block buffer shape
*/
std::vector<Point> CreatInflowBufferShape()
{
std::vector<Point> inlfow_buffer_shape;
inlfow_buffer_shape.push_back(Point(-DLsponge, 0.0));
inlfow_buffer_shape.push_back(Point(-DLsponge, DH));
inlfow_buffer_shape.push_back(Point(0.0, DH));
inlfow_buffer_shape.push_back(Point(0.0, 0.0));
inlfow_buffer_shape.push_back(Point(-DLsponge, 0.0));
return inlfow_buffer_shape;
}
/**
* @brief create a beam shape
*/
std::vector<Point> CreatBeamShape()
{
std::vector<Point> beam_shape;
beam_shape.push_back(BLB);
beam_shape.push_back(BLT);
beam_shape.push_back(BRT);
beam_shape.push_back(BRB);
beam_shape.push_back(BLB);
return beam_shape;
}
/**
* @brief create outer wall shape
*/
std::vector<Point> CreatOuterWallShape()
{
std::vector<Point> outer_wall_shape;
outer_wall_shape.push_back(Point(-DLsponge - BW, -BW));
outer_wall_shape.push_back(Point(-DLsponge - BW, DH + BW));
outer_wall_shape.push_back(Point(DL + BW, DH + BW));
outer_wall_shape.push_back(Point(DL + BW, -BW));
outer_wall_shape.push_back(Point(-DLsponge - BW, -BW));
return outer_wall_shape;
}
/**
* @brief create inner wall shape
*/
std::vector<Point> CreatInnerWallShape()
{
std::vector<Point> inner_wall_shape;
inner_wall_shape.push_back(Point(-DLsponge - 2.0*BW, 0.0));
inner_wall_shape.push_back(Point(-DLsponge - 2.0*BW, DH));
inner_wall_shape.push_back(Point(DL + 2.0*BW, DH));
inner_wall_shape.push_back(Point(DL + 2.0*BW, 0.0));
inner_wall_shape.push_back(Point(-DLsponge - 2.0*BW, 0.0));
return inner_wall_shape;
}
/**
* @brief Fluid body definition.
*/
class WaterBlock : public FluidBody
{
public:
WaterBlock(SPHSystem &system, string body_name,
WeaklyCompressibleFluid &material, FluidParticles &fluid_particles,
int refinement_level, ParticlesGeneratorOps op)
: FluidBody(system, body_name, material, fluid_particles, refinement_level, op)
{
/** Geomerty definition. */
std::vector<Point> water_bock_shape = CreatWaterBlockShape();
body_region_.add_geometry(new Geometry(water_bock_shape), RegionBooleanOps::add);
/** Geomerty definition. */
body_region_.add_geometry(new Geometry(insert_circle_center, insert_circle_radius, 100), RegionBooleanOps::sub);
std::vector<Point> beam_shape = CreatBeamShape();
body_region_.add_geometry(new Geometry(beam_shape), RegionBooleanOps::sub);
/** Finalize the geometry definition and correspoding opertation. */
body_region_.done_modeling();
}
};
/**
* @brief Definition of the solid body.
*/
class WallBoundary : public SolidBody
{
public:
WallBoundary(SPHSystem &system, string body_name,
SolidParticles &solid_particles,
int refinement_level, ParticlesGeneratorOps op)
: SolidBody(system, body_name, *(new Solid("EmptyWallMaterial")), solid_particles, refinement_level, op)
{
/** Geomerty definition. */
std::vector<Point> outer_wall_shape = CreatOuterWallShape();
std::vector<Point> inner_wall_shape = CreatInnerWallShape();
body_region_.add_geometry(new Geometry(outer_wall_shape), RegionBooleanOps::add);
body_region_.add_geometry(new Geometry(inner_wall_shape), RegionBooleanOps::sub);
/** Finalize the geometry definition and correspoding opertation. */
body_region_.done_modeling();
}
};
/**
* @brief Definition of the inserted body as a elastic structure.
*/
class InsertedBody : public SolidBody
{
public:
InsertedBody(SPHSystem &system, string body_name, ElasticSolid &material,
ElasticSolidParticles &elastic_particles,
int refinement_level, ParticlesGeneratorOps op)
: SolidBody(system, body_name, material, elastic_particles, refinement_level, op)
{
/** Geomerty definition. */
std::vector<Point> beam_shape = CreatBeamShape();
Geometry *circle_geometry = new Geometry(insert_circle_center, insert_circle_radius, 100);
body_region_.add_geometry(circle_geometry, RegionBooleanOps::add);
Geometry *beam_geometry = new Geometry(beam_shape);
body_region_.add_geometry(beam_geometry, RegionBooleanOps::add);
/** Finalize the geometry definition and correspoding opertation. */
body_region_.done_modeling();
}
};
/**
* @brief constrain the beam base
*/
class BeamBase : public SolidBodyPart
{
public:
BeamBase(SolidBody *solid_body, string constrianed_region_name)
: SolidBodyPart(solid_body, constrianed_region_name)
{
/** Geomerty definition. */
std::vector<Point> beam_shape = CreatBeamShape();
Geometry *circle_geometry = new Geometry(insert_circle_center, insert_circle_radius, 100);
soild_body_part_region_.add_geometry(circle_geometry, RegionBooleanOps::add);
Geometry * beam_gemetry = new Geometry(beam_shape);
soild_body_part_region_.add_geometry(beam_gemetry, RegionBooleanOps::sub);
soild_body_part_region_.done_modeling();
/** Tag the constrained particle. */
TagBodyPartParticles();
}
};
/**
* @brief inflow buffer
*/
class InflowBuffer : public FluidBodyPart
{
public:
InflowBuffer(FluidBody* fluid_body, string constrianed_region_name)
: FluidBodyPart(fluid_body, constrianed_region_name)
{
/** Geomerty definition. */
std::vector<Point> inflow_buffer_shape = CreatInflowBufferShape();
fluid_body_part_region_.add_geometry(new Geometry(inflow_buffer_shape), RegionBooleanOps::add);
/** Finalize the geometry definition and correspoding opertation. */
fluid_body_part_region_.done_modeling();
//tag the constrained particle
TagBodyPartCells();
}
};
/**
* @brief Inflow BCs.
*/
class ParabolicInflow : public fluid_dynamics::InflowBoundaryCondition
{
Real u_ave_, u_ref_, t_ref;
public:
ParabolicInflow(FluidBody* fluid_body,
FluidBodyPart *constrained_region)
: InflowBoundaryCondition(fluid_body, constrained_region)
{
u_ave_ = 0.0;
u_ref_ = 1.0;
t_ref = 2.0;
}
Vecd GetInflowVelocity(Vecd &position, Vecd &velocity)
{
Real u = velocity[0];
Real v = velocity[1];
if (position[0] < 0.0) {
u = 6.0*u_ave_*position[1] * (DH - position[1]) / DH / DH;
v = 0.0;
}
return Vecd(u, v);
}
void PrepareConstraint() override
{
Real run_time = GlobalStaticVariables::physical_time_;
u_ave_ = run_time < t_ref ? 0.5*u_ref_*(1.0 - cos(pi*run_time/ t_ref)) : u_ref_;
}
};
/**
* @brief Definition of an observer body with one particle located at specific position
* of the insert beam.
*/
class BeamObserver : public ObserverLagrangianBody
{
public:
BeamObserver(SPHSystem &system, string body_name,
ObserverParticles &observer_particles,
int refinement_level, ParticlesGeneratorOps op)
: ObserverLagrangianBody(system, body_name, observer_particles, refinement_level, op)
{
/** postion and volume. */
body_input_points_volumes_.push_back(make_pair(0.5 * (BRT + BRB), 0.0));
}
};
/**
* @brief Definition of an observer body with several particles located
* at the entrance of the flow channel.
*/
class FluidObserver : public ObserverEulerianBody
{
public:
FluidObserver(SPHSystem &system, string body_name,
ObserverParticles &observer_particles,
int refinement_level, ParticlesGeneratorOps op)
: ObserverEulerianBody(system, body_name, observer_particles, refinement_level, op)
{
/** A line of measuring points at the entrance of the channel. */
size_t number_observation_pionts = 21;
Real range_of_measure = DH - particle_spacing_ref * 4.0;
Real start_of_measure = particle_spacing_ref*2.0;
for (size_t i = 0; i < number_observation_pionts; ++i) {
Vec2d point_coordinate(0.0, range_of_measure*Real(i) / Real(number_observation_pionts - 1) + start_of_measure);
body_input_points_volumes_.push_back(make_pair(point_coordinate, 0.0));
}
}
};
/**
* @brief Main program starts here.
*/
int main()
{
/**
* @brief Build up -- a SPHSystem --
*/
SPHSystem system(Vec2d(-DLsponge - BW, -BW), Vec2d(DL + BW, DH + BW), particle_spacing_ref);
/** Set the starting time. */
GlobalStaticVariables::physical_time_ = 0.0;
/** Tag for computation from restart files. 0: not from restart files. */
system.restart_step_ = 0;
/** Tag for reload initially repaxed particles. */
system.reload_particle_ = false;
/**
* @brief Material property, partilces and body creation of fluid.
*/
SymmetricTaitFluid fluid("Water", rho0_f, c_f, mu_f, k_f);
FluidParticles fluid_particles("WaterBody");
WaterBlock *water_block = new WaterBlock(system, "WaterBody", fluid, fluid_particles, 0, ParticlesGeneratorOps::lattice);
/**
* @brief Particle and body creation of wall boundary.
*/
SolidParticles solid_particles("Wall");
WallBoundary *wall_boundary = new WallBoundary(system, "Wall", solid_particles, 0, ParticlesGeneratorOps::lattice);
/**
* @brief Material property, particle and body creation of elastic beam(inserted body).
*/
ElasticSolid solid_material("ElasticSolid", rho0_s, Youngs_modulus, poisson, 0.0);
ElasticSolidParticles inserted_body_particles("InsertedBody");
InsertedBody *inserted_body = new InsertedBody(system, "InsertedBody", solid_material, inserted_body_particles, 1, ParticlesGeneratorOps::lattice);
/**
* @brief Particle and body creation of gate observer.
*/
ObserverParticles beam_observer_particles("BeamObserver");
BeamObserver *beam_observer = new BeamObserver(system, "BeamObserver", beam_observer_particles, 0, ParticlesGeneratorOps::direct);
ObserverParticles flow_observer_particles("FlowObserver");
FluidObserver *fluid_observer = new FluidObserver(system, "FluidObserver", flow_observer_particles, 0, ParticlesGeneratorOps::direct);
/**
* @brief simple input and outputs.
*/
In_Output in_output(system);
WriteBodyStatesToVtu write_real_body_states_to_vtu(in_output, system.real_bodies_);
WriteBodyStatesToPlt write_real_body_states_to_plt(in_output, system.real_bodies_);
WriteRestart write_restart_files(in_output, system.real_bodies_);
ReadRestart read_restart_files(in_output, system.real_bodies_);
ReadReloadParticle read_reload_particles(in_output, { inserted_body, water_block }, { "InsertBody", "WaterBody" });
/**
* @brief Body contact map.
* @details The contact map gives the data conntections between the bodies.
* Basically the the rangE of bodies to build neighbor particle lists.
*/
SPHBodyTopology body_topology = { { water_block, { wall_boundary, inserted_body } },
{ wall_boundary, { } }, { inserted_body, { water_block } },
{ beam_observer, {inserted_body} }, { fluid_observer, { water_block } } };
system.SetBodyTopology(&body_topology);
/**
* @brief Simulation data structure set up.
*/
system.CreateParticelsForAllBodies();
/** check whether reload particles. */
if (system.reload_particle_) read_reload_particles.ReadFromFile();
system.InitializeSystemCellLinkedLists();
system.InitializeSystemConfigurations();
/**
* @brief Define all numerical methods which are used in this case.
*/
/**
* @brief Methods used only once.
*/
/** initial condition for fluid body */
fluid_dynamics::WeaklyCompressibleFluidInitialCondition set_all_fluid_particles_at_rest(water_block);
/** Obtain the initial number density of fluid. */
fluid_dynamics::InitialNumberDensity fluid_initial_number_density(water_block, { wall_boundary, inserted_body });
/** initial condition for the solid body */
solid_dynamics::SolidDynamicsInitialCondition set_all_wall_particles_at_rest(wall_boundary);
/** initial condition for the elastic solid bodies */
solid_dynamics::ElasticSolidDynamicsInitialCondition set_all_insert_body_particles_at_rest(inserted_body);
/** Initialize normal direction of the wall boundary. */
solid_dynamics::NormalDirectionSummation get_wall_normal(wall_boundary, {});
/** Initialize normal direction of the inserted body. */
solid_dynamics::NormalDirectionSummation get_inserted_body_normal(inserted_body, {});
/** Corrected strong configuration. */
solid_dynamics::CorrectConfiguration inserted_body_corrected_configuration_in_strong_form(inserted_body, {});
/**
* @brief Methods used for time stepping.
*/
/** Initialize particle acceleration. */
InitializeOtherAccelerations initialize_other_acceleration(water_block);
/** Periodic bounding. */
PeriodicBoundingInXDirection periodic_bounding(water_block);
/** Periodic BCs. */
PeriodicConditionInXDirection periodic_condition(water_block);
/**
* @brief Algorithms of fluid dynamics.
*/
/** Evaluation of density by summation approach. */
fluid_dynamics::DensityBySummation update_fluid_desnity(water_block, { wall_boundary, inserted_body });
/** Divergence correction. */
fluid_dynamics::DivergenceCorrection divergence_correction(water_block, { wall_boundary });
/** Time step size without considering sound wave speed. */
fluid_dynamics::GetAdvectionTimeStepSize get_fluid_adevction_time_step_size(water_block, U_f);
/** Time step size with considering sound wave speed. */
fluid_dynamics::GetAcousticTimeStepSize get_fluid_time_step_size(water_block);
/** Pressure relaxation using verlet time stepping. */
fluid_dynamics::PressureRelaxationVerlet pressure_relaxation(water_block, { wall_boundary, inserted_body });
/** Computing viscous acceleration. */
fluid_dynamics::ComputingViscousAcceleration viscous_acceleration(water_block, { wall_boundary, inserted_body });
/** Impose transport velocity. */
fluid_dynamics::TransportVelocityCorrection transport_velocity_correction(water_block, { wall_boundary, inserted_body });
/** Computing vorticity in the flow. */
fluid_dynamics::ComputingVorticityInFluidField compute_vorticity(water_block);
/** Inflow boundary condition. */
ParabolicInflow
parabolic_inflow(water_block, new InflowBuffer(water_block, "Buffer"));
/**
* @brief Algorithms of FSI.
*/
/** Compute the force exerted on solid body due to fluid pressure and visocisty. */
solid_dynamics::FluidPressureForceOnSolid fluid_pressure_force_on_insrted_body(inserted_body, { water_block });
solid_dynamics::FluidViscousForceOnSolid fluid_viscous_force_on_insrted_body(inserted_body, { water_block });
/**
* @brief Algorithms of solid dynamics.
*/
/** Compute time step size of elastic solid. */
solid_dynamics::GetAcousticTimeStepSize inserted_body_computing_time_step_size(inserted_body);
/** Stress relaxation for the beam. */
solid_dynamics::StressRelaxationFirstStep inserted_body_stress_relaxation_first_step(inserted_body);
solid_dynamics::StressRelaxationSecondStep inserted_body_stress_relaxation_second_step(inserted_body);
/** Constrain region of the inserted body. */
solid_dynamics::ConstrainSolidBodyRegion
constrain_beam_base(inserted_body, new BeamBase(inserted_body, "BeamBase"));
/** Computing the average velocity. */
solid_dynamics::InitializeDisplacement inserted_body_initialize_displacement(inserted_body);
solid_dynamics::UpdateAverageVelocity inserted_body_average_velocity(inserted_body);
/** Update norm .*/
solid_dynamics::UpdateElasticNormalDirection inserted_body_update_normal(inserted_body);
/**
* @brief Methods used for updating data structure.
*/
/** Update the cell linked list of bodies when neccessary. */
ParticleDynamicsCellLinkedList update_water_block_cell_linked_list(water_block);
/** Update the configuration of bodies when neccessary. */
ParticleDynamicsConfiguration update_water_block_configuration(water_block);
/** Update the cell linked list of bodies when neccessary. */
ParticleDynamicsCellLinkedList update_inserted_body_cell_linked_list(inserted_body);
/** Update the contact configuration for a given contact map. */
ParticleDynamicsContactConfiguration update_inserted_body_contact_configuration(inserted_body);
/** Update the contact configuration for the flow observer. */
ParticleDynamicsContactConfiguration update_fluid_observer_body_contact_configuration(fluid_observer);
/**
* @brief oberservation outputs.
*/
WriteTotalViscousForceOnSolid write_total_viscous_force_on_inserted_body(in_output, inserted_body);
WriteObservedElasticDisplacement write_beam_tip_displacement(in_output, beam_observer, { inserted_body });
WriteObservedFluidVelocity write_fluid_velocity(in_output, fluid_observer, { water_block });
/** Pre-simultion*/
set_all_fluid_particles_at_rest.exec();
set_all_wall_particles_at_rest.exec();
set_all_insert_body_particles_at_rest.exec();
periodic_condition.parallel_exec();
/** one need update configuration after peroidic condition. */
update_water_block_configuration.parallel_exec();
get_wall_normal.parallel_exec();
get_inserted_body_normal.parallel_exec();
fluid_initial_number_density.parallel_exec();
inserted_body_corrected_configuration_in_strong_form.parallel_exec();
/**
* @brief The time stepping starts here.
*/
if(system.restart_step_ != 0)
{
GlobalStaticVariables::physical_time_ = read_restart_files.ReadRestartFiles(system.restart_step_);
update_water_block_cell_linked_list.parallel_exec();
update_inserted_body_cell_linked_list.parallel_exec();
periodic_condition.parallel_exec();
/** one need update configuration after peroidic condition. */
update_water_block_configuration.parallel_exec();
update_inserted_body_contact_configuration.parallel_exec();
get_inserted_body_normal.parallel_exec();
}
write_real_body_states_to_plt.WriteToFile(GlobalStaticVariables::physical_time_);
write_beam_tip_displacement.WriteToFile(GlobalStaticVariables::physical_time_);
int number_of_iterations = system.restart_step_;
int screen_output_interval = 100;
int restart_output_interval = screen_output_interval * 10;
Real End_Time = 200.0; /**< End time. */
Real D_Time = End_Time/200.0; /**< time stamps for output. */
Real Dt = 0.0; /**< Default advection time step sizes for fluid. */
Real dt = 0.0; /**< Default accoustic time step sizes for fluid. */
Real dt_s = 0.0; /**< Default accoustic time step sizes for solid. */
/** Statistics for computing time. */
tick_count t1 = tick_count::now();
tick_count::interval_t interval;
/**
* @brief Main loop starts here.
*/
while (GlobalStaticVariables::physical_time_ < End_Time)
{
Real integeral_time = 0.0;
/** Integrate time (loop) until the next output time. */
while (integeral_time < D_Time) {
Dt = get_fluid_adevction_time_step_size.parallel_exec();
update_fluid_desnity.parallel_exec();
divergence_correction.parallel_exec();
initialize_other_acceleration.parallel_exec();
viscous_acceleration.parallel_exec();
transport_velocity_correction.parallel_exec(Dt);
/** FSI for viscous force. */
fluid_viscous_force_on_insrted_body.parallel_exec();
/** Update normal direction on elastic body.*/
inserted_body_update_normal.parallel_exec();
Real relaxation_time = 0.0;
while (relaxation_time < Dt) {
/** Fluid pressure relaxation. */
pressure_relaxation.parallel_exec(dt);
/** FSI for pressure force. */
fluid_pressure_force_on_insrted_body.parallel_exec();
/** Solid dynamics. */
Real dt_s_sum = 0.0;
inserted_body_initialize_displacement.parallel_exec();
while (dt_s_sum < dt) {
dt_s = inserted_body_computing_time_step_size.parallel_exec();
if (dt - dt_s_sum < dt_s) dt_s = dt - dt_s_sum;
inserted_body_stress_relaxation_first_step.parallel_exec(dt_s);
constrain_beam_base.parallel_exec();
inserted_body_stress_relaxation_second_step.parallel_exec(dt_s);
dt_s_sum += dt_s;
}
inserted_body_average_velocity.parallel_exec(dt);
dt = get_fluid_time_step_size.parallel_exec();
relaxation_time += dt;
integeral_time += dt;
GlobalStaticVariables::physical_time_ += dt;
parabolic_inflow.parallel_exec();
}
if (number_of_iterations % screen_output_interval == 0)
{
cout << fixed << setprecision(9) << "N=" << number_of_iterations << " Time = "
<< GlobalStaticVariables::physical_time_
<< " Dt = " << Dt << " dt = " << dt << " dt_s = " << dt_s << "\n";
if (number_of_iterations % restart_output_interval == 0)
write_restart_files.WriteToFile(Real(number_of_iterations));
}
number_of_iterations++;
/** Water block confifuration and periodic constion. */
periodic_bounding.parallel_exec();
update_water_block_cell_linked_list.parallel_exec();
periodic_condition.parallel_exec();
update_water_block_configuration.parallel_exec();
/** Inserted body contact configuration. */
update_inserted_body_cell_linked_list.parallel_exec();
update_inserted_body_contact_configuration.parallel_exec();
write_beam_tip_displacement.WriteToFile(GlobalStaticVariables::physical_time_);
}
compute_vorticity.parallel_exec();
tick_count t2 = tick_count::now();
write_real_body_states_to_vtu.WriteToFile(GlobalStaticVariables::physical_time_);
write_total_viscous_force_on_inserted_body.WriteToFile(GlobalStaticVariables::physical_time_);
update_fluid_observer_body_contact_configuration.parallel_exec();
write_fluid_velocity.WriteToFile(GlobalStaticVariables::physical_time_);
tick_count t3 = tick_count::now();
interval += t3 - t2;
}
tick_count t4 = tick_count::now();
tick_count::interval_t tt;
tt = t4 - t1 - interval;
cout << "Total wall time for computation: " << tt.seconds() << " seconds." << endl;
return 0;
}
| 40.424448 | 149 | 0.755817 | [
"geometry",
"shape",
"vector",
"solid"
] |
f5436b02e6a9ee9766b3e0134aadf94e26025e71 | 32,825 | cpp | C++ | src/ui/listview.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 9 | 2016-01-10T20:59:02.000Z | 2019-01-09T14:18:13.000Z | src/ui/listview.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 31 | 2015-01-30T17:46:17.000Z | 2017-03-04T17:33:50.000Z | src/ui/listview.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 2 | 2015-04-05T08:45:22.000Z | 2018-08-24T06:43:24.000Z | ////////////////////////////////////////////////////////////////////////////////
// Name: listview.cpp
// Purpose: Implementation of wex::listview and related classes
// Author: Anton van Wezenbeek
// Copyright: (c) 2021-2022 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <wex/core/chrono.h>
#include <wex/core/config.h>
#include <wex/core/interruptible.h>
#include <wex/core/log.h>
#include <wex/core/regex.h>
#include <wex/core/tokenize.h>
#include <wex/data/stc.h>
#include <wex/factory/defs.h>
#include <wex/factory/lexers.h>
#include <wex/factory/printing.h>
#include <wex/factory/stc.h>
#include <wex/ui/bind.h>
#include <wex/ui/frame.h>
#include <wex/ui/frd.h>
#include <wex/ui/item-dialog.h>
#include <wex/ui/item-vector.h>
#include <wex/ui/listitem.h>
#include <wex/ui/listview.h>
#include <wex/ui/menu.h>
#include <wx/dnd.h>
#include <wx/generic/dirctrlg.h> // for wxTheFileIconsTable
#include <wx/imaglist.h>
#include <wx/numdlg.h> // for wxGetNumberFromUser
#include <wx/settings.h>
#include <algorithm>
#include <cctype>
namespace wex
{
// file_droptarget is already used
class droptarget : public wxFileDropTarget
{
public:
explicit droptarget(listview* lv)
: m_listview(lv)
{
;
}
bool
OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames) override
{
// Only drop text if nothing is selected,
// so dropping on your own selection is impossible.
if (m_listview->GetSelectedItemCount() == 0)
{
for (size_t i = 0; i < filenames.GetCount(); i++)
{
m_listview->item_from_text(filenames[i]);
}
return true;
}
else
{
return false;
}
};
private:
listview* m_listview;
};
template <typename T> int compare(T x, T y)
{
if (x > y)
return 1;
else if (x < y)
return -1;
else
return 0;
}
const std::vector<item> config_items()
{
return std::vector<item>(
{{"notebook",
{{_("General"),
{{_("list.Header"), item::CHECKBOX, std::any(true)},
{_("list.Single selection"), item::CHECKBOX},
{_("list.Comparator"), item::FILEPICKERCTRL},
{_("list.Sort method"),
{{SORT_ASCENDING, _("Sort ascending")},
{SORT_DESCENDING, _("Sort descending")},
{SORT_TOGGLE, _("Sort toggle")}}},
{_("list.Context size"), 0, 80, 10},
{_("list.Rulers"),
{{wxLC_HRULES, _("Horizontal rulers")},
{wxLC_VRULES, _("Vertical rulers")}},
false}}},
{_("Font"),
{{_("list.Font"),
item::FONTPICKERCTRL,
wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT)}}},
{_("Colour"),
{{_("list.Readonly colour"),
item::COLOURPICKERWIDGET,
*wxLIGHT_GREY}}}}}});
}
std::string ignore_case(const std::string& text)
{
std::string output(text);
if (!wex::find_replace_data::get()->match_case())
{
boost::algorithm::to_upper(output);
}
return output;
};
}; // namespace wex
wex::listview::listview(const data::listview& data)
: m_image_height(16) // not used if IMAGE_FILE_ICON is used, then 16 is fixed
, m_image_width(16)
, m_col_event_id(1000)
, m_data(
this,
data::listview(data).image(
data.type() == data::listview::NONE ||
data.type() == data::listview::TSV ?
data.image() :
data::listview::IMAGE_FILE_ICON))
, m_frame(dynamic_cast<wex::frame*>(wxTheApp->GetTopWindow()))
{
Create(
data.window().parent(),
data.window().id(),
data.window().pos(),
data.window().size(),
data.window().style() == data::NUMBER_NOT_SET ? wxLC_REPORT :
data.window().style(),
data.control().validator() != nullptr ? *data.control().validator() :
wxDefaultValidator,
data.window().name());
config_get();
m_data.inject();
// We can only have one drop target, we use file drop target,
// as list items can also be copied and pasted.
SetDropTarget(new droptarget(this));
switch (m_data.image())
{
case data::listview::IMAGE_NONE:
break;
case data::listview::IMAGE_ART:
case data::listview::IMAGE_OWN:
AssignImageList(
new wxImageList(m_image_width, m_image_height, true, 0),
wxIMAGE_LIST_SMALL);
break;
case data::listview::IMAGE_FILE_ICON:
SetImageList(
wxTheFileIconsTable->GetSmallImageList(),
wxIMAGE_LIST_SMALL);
break;
default:
assert(0);
}
m_frame->update_statusbar(this);
if (
m_data.type() != data::listview::NONE &&
m_data.type() != data::listview::TSV)
{
Bind(
wxEVT_IDLE,
[=, this](wxIdleEvent& event)
{
process_idle(event);
});
}
Bind(
wxEVT_LIST_BEGIN_DRAG,
[=, this](wxListEvent& event)
{
process_list(event, wxEVT_LIST_BEGIN_DRAG);
});
Bind(
wxEVT_LIST_ITEM_ACTIVATED,
[=, this](wxListEvent& event)
{
item_activated(event.GetIndex());
});
Bind(
wxEVT_LIST_ITEM_DESELECTED,
[=, this](wxListEvent& event)
{
m_frame->update_statusbar(this);
});
Bind(
wxEVT_LIST_ITEM_SELECTED,
[=, this](wxListEvent& event)
{
process_list(event, wxEVT_LIST_ITEM_SELECTED);
});
Bind(
wxEVT_LIST_COL_CLICK,
[=, this](wxListEvent& event)
{
sort_column(
event.GetColumn(),
(sort_t)config(_("list.Sort method")).get(SORT_TOGGLE));
});
Bind(
wxEVT_LIST_COL_RIGHT_CLICK,
[=, this](wxListEvent& event)
{
m_to_be_sorted_column_no = event.GetColumn();
menu menu(
GetSelectedItemCount() > 0 ? menu::IS_SELECTED : menu::menu_t_def());
menu.append({{wxID_SORT_ASCENDING}, {wxID_SORT_DESCENDING}});
PopupMenu(&menu);
});
Bind(
wxEVT_RIGHT_DOWN,
[=, this](wxMouseEvent& event)
{
process_mouse(event);
});
Bind(
wxEVT_SET_FOCUS,
[=, this](wxFocusEvent& event)
{
m_frame->set_find_focus(this);
event.Skip();
});
Bind(
wxEVT_SHOW,
[=, this](wxShowEvent& event)
{
event.Skip();
m_frame->update_statusbar(this);
});
bind_other();
}
bool wex::listview::append_columns(const std::vector<column>& cols)
{
SetSingleStyle(wxLC_REPORT);
for (const auto& col : cols)
{
auto mycol(col);
if (const auto index =
AppendColumn(mycol.GetText(), mycol.GetAlign(), mycol.GetWidth());
index == -1)
{
return false;
}
mycol.SetColumn(GetColumnCount() - 1);
m_columns.emplace_back(mycol);
Bind(
wxEVT_MENU,
[=, this](wxCommandEvent& event)
{
sort_column(event.GetId() - m_col_event_id, SORT_TOGGLE);
},
m_col_event_id + GetColumnCount() - 1);
}
return true;
}
void wex::listview::bind_other()
{
bind(this).frd(
find_replace_data::get()->wx(),
[=, this](const std::string& s, bool b)
{
find_next(s, b);
});
bind(this).command(
{{[=, this](wxCommandEvent& event)
{
clear();
},
wxID_CLEAR},
{[=, this](wxCommandEvent& event)
{
copy_selection_to_clipboard();
},
wxID_COPY},
{[=, this](wxCommandEvent& event)
{
edit_delete();
},
wxID_DELETE},
{[=, this](wxCommandEvent& event)
{
item_from_text(clipboard_get());
},
wxID_PASTE},
{[=, this](wxCommandEvent& event)
{
SetItemState(-1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
},
wxID_SELECTALL},
{[=, this](wxCommandEvent& event)
{
sort_column(m_to_be_sorted_column_no, SORT_ASCENDING);
},
wxID_SORT_ASCENDING},
{[=, this](wxCommandEvent& event)
{
sort_column(m_to_be_sorted_column_no, SORT_DESCENDING);
},
wxID_SORT_DESCENDING},
{[=, this](wxCommandEvent& event)
{
copy_selection_to_clipboard();
edit_delete();
},
wxID_CUT},
{[=, this](wxCommandEvent& event)
{
for (auto i = 0; i < GetItemCount(); i++)
{
Select(i, !IsSelected(i));
}
},
ID_EDIT_SELECT_INVERT},
{[=, this](wxCommandEvent& event)
{
for (auto i = 0; i < GetItemCount(); i++)
{
Select(i, false);
}
},
ID_EDIT_SELECT_NONE},
{[=, this](wxCommandEvent& event)
{
if (on_command(event))
{
m_frame->update_statusbar(this);
}
},
wxID_ADD},
{[=, this](wxCommandEvent& event)
{
process_match(event);
},
ID_LIST_MATCH},
{[=, this](wxCommandEvent& event)
{
for (auto i = GetFirstSelected(); i != -1; i = GetNextSelected(i))
{
item_activated(i);
}
},
ID_EDIT_OPEN},
{[=, this](wxCommandEvent& event)
{
if (!IsShown() || GetItemCount() == 0)
return;
if (const auto val(wxGetNumberFromUser(
_("Input") + " (1 - " + std::to_string(GetItemCount()) + "):",
wxEmptyString,
_("Enter Item Number"),
(GetFirstSelected() == -1 ? 1 : GetFirstSelected() + 1),
1,
GetItemCount()));
val > 0)
{
data::listview(data::control().line(val), this).inject();
}
},
wxID_JUMP_TO}});
}
const std::string wex::listview::build_page()
{
std::stringstream text;
text << "<TABLE "
<< (((GetWindowStyle() & wxLC_HRULES) ||
(GetWindowStyle() & wxLC_VRULES)) ?
"border=1" :
"border=0")
<< " cellpadding=4 cellspacing=0 >\n"
<< "<tr>\n";
for (auto c = 0; c < GetColumnCount(); c++)
{
wxListItem col;
GetColumn(c, col);
text << "<td><i>" << col.GetText() << "</i>\n";
}
for (auto i = 0; i < GetItemCount(); i++)
{
text << "<tr>\n";
for (auto col = 0; col < GetColumnCount(); col++)
{
text << "<td>" << GetItemText(i, col) << "\n";
}
}
text << "</TABLE>\n";
return text.str();
}
void wex::listview::build_popup_menu(wex::menu& menu)
{
if (
GetSelectedItemCount() >= 1 &&
listitem(this, GetFirstSelected()).path().stat().is_ok())
{
menu.append(
{{ID_EDIT_OPEN, _("&Open"), data::menu().art(wxART_FILE_OPEN)}, {}});
}
else if (GetSelectedItemCount() >= 1 && m_data.type() == data::listview::TSV)
{
menu.append({{ID_EDIT_OPEN, _("&Open")}});
}
menu.append({{}, {menu_item::EDIT_INVERT}});
if (GetItemCount() > 0 && GetSelectedItemCount() == 0 && InReportView())
{
menu.append({{}});
auto* menuSort = new wex::menu;
for (const auto& it : m_columns)
{
menuSort->append({{m_col_event_id + it.GetColumn(), it.GetText()}});
}
menu.append({{menuSort, _("Sort On")}});
}
if (
(m_data.type() == data::listview::FOLDER && GetSelectedItemCount() <= 1) ||
m_data.type() == data::listview::TSV)
{
menu.append({{}, {wxID_ADD}});
}
}
void wex::listview::clear()
{
if (GetItemCount() == 0)
{
return;
}
DeleteAllItems();
sort_column_reset();
m_frame->update_statusbar(this);
}
int wex::listview::config_dialog(const data::window& par)
{
const data::window data(data::window(par).title(_("List Options")));
if (m_config_dialog == nullptr)
{
m_config_dialog = new item_dialog(config_items(), data);
}
return (data.button() & wxAPPLY) ? m_config_dialog->Show() :
m_config_dialog->ShowModal();
}
void wex::listview::config_get()
{
const auto& ci(config_items());
const item_vector iv(&ci);
lexers::get()->apply_default_style(
[=, this](const std::string& back)
{
SetBackgroundColour(wxColour(back));
});
SetFont(iv.find<wxFont>(_("list.Font")));
SetSingleStyle(
wxLC_HRULES,
(iv.find<long>(_("list.Rulers")) & wxLC_HRULES) > 0);
SetSingleStyle(
wxLC_VRULES,
(iv.find<long>(_("list.Rulers")) & wxLC_VRULES) > 0);
SetSingleStyle(
wxLC_NO_HEADER,
!iv.find<bool>(_("list.Header")) || m_data.type() == data::listview::TSV);
SetSingleStyle(wxLC_SINGLE_SEL, iv.find<bool>(_("list.Single selection")));
items_update();
}
const std::string wex::listview::context(const std::string& line, int pos) const
{
int context_size = config(_("list.Context size")).get(10);
if (pos == -1 || context_size <= 0)
return line;
return (context_size > pos ? std::string(context_size - pos, ' ') :
std::string()) +
line.substr(context_size < pos ? pos - context_size : 0);
}
void wex::listview::copy_selection_to_clipboard()
{
if (GetSelectedItemCount() == 0)
return;
wxBusyCursor wait;
std::string clipboard;
for (auto i = GetFirstSelected(); i != -1; i = GetNextSelected(i))
clipboard += item_to_text(i) + "\n";
clipboard_add(clipboard);
}
void wex::listview::edit_delete()
{
if (GetSelectedItemCount() == 0)
return;
long old_item = -1;
for (long i = -1; (i = GetNextSelected(i)) != -1;)
{
DeleteItem(i);
old_item = i;
i = -1;
}
if (old_item != -1 && old_item < GetItemCount())
SetItemState(old_item, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
items_update();
}
bool wex::listview::find_next(const std::string& text, bool forward)
{
if (text.empty())
{
return false;
}
std::string text_use = ignore_case(text);
const auto firstselected = GetFirstSelected();
static bool recursive = false;
static long start_item;
static long end_item;
if (forward)
{
start_item = recursive ? 0 : (firstselected != -1 ? firstselected + 1 : 0);
end_item = GetItemCount();
}
else
{
start_item = recursive ? GetItemCount() - 1 :
(firstselected != -1 ? firstselected - 1 : 0);
end_item = -1;
}
int match = -1;
for (int index = start_item; index != end_item && match == -1;
(forward ? index++ : index--))
{
std::string text;
for (int col = 0; col < GetColumnCount() && match == -1; col++)
{
text = ignore_case(std::string(GetItemText(index, col)));
if (find_replace_data::get()->match_word())
{
if (text == text_use)
{
match = index;
}
}
else
{
if (text.find(text_use) != std::string::npos)
{
match = index;
}
}
}
}
if (match != -1)
{
recursive = false;
Select(match);
EnsureVisible(match);
if (firstselected != -1 && match != firstselected)
{
Select(firstselected, false);
}
return true;
}
else
{
m_frame->statustext(
get_find_result(text, forward, recursive),
std::string());
if (!recursive)
{
recursive = true;
find_next(text, forward);
recursive = false;
}
return false;
}
}
unsigned int wex::listview::get_art_id(const wxArtID& artid)
{
if (const auto& it = m_art_ids.find(artid); it != m_art_ids.end())
{
return it->second;
}
else
{
if (auto* il = GetImageList(wxIMAGE_LIST_SMALL); il == nullptr)
{
assert(0);
return 0;
}
else
{
m_art_ids.insert({artid, il->GetImageCount()});
return il->Add(wxArtProvider::GetBitmap(
artid,
wxART_OTHER,
wxSize(m_image_width, m_image_height)));
}
}
}
wex::column wex::listview::get_column(const std::string& name) const
{
if (const auto& it = std::find_if(
m_columns.begin(),
m_columns.end(),
[name](auto const& it)
{
return it.GetText() == name;
});
it != m_columns.end())
{
return *it;
}
return column();
}
const std::string wex::listview::get_item_text(
long item_number,
const std::string& col_name) const
{
if (item_number < 0 || item_number >= GetItemCount())
{
return std::string();
}
if (col_name.empty())
{
return GetItemText(item_number);
}
const int col = find_column(col_name);
return col < 0 ? std::string() : GetItemText(item_number, col).ToStdString();
}
bool wex::listview::insert_item(
const std::vector<std::string>& item,
long requested_index)
{
if (item.empty() || item.front().empty() || item.size() > m_columns.size())
{
return false;
}
long index = 0;
for (int no = 0; const auto& col : item)
{
try
{
if (!col.empty())
{
switch (m_columns[no].type())
{
case column::DATE:
if (const auto& [r, t] = chrono().get_time(col); !r)
return false;
break;
case column::FLOAT:
(void)std::stof(col);
break;
case column::INT:
(void)std::stoi(col);
break;
case column::STRING:
break;
default:
break;
}
if (no == 0)
{
if (
(index = InsertItem(
requested_index == -1 ? GetItemCount() : requested_index,
col)) == -1)
{
log("listview insert") << "index:" << index << "col:" << col;
return false;
}
else if (regex v(",fore:(.*)");
v.match(lexers::get()->get_default_style().value()) > 0)
{
SetItemTextColour(index, wxColour(v[0]));
}
}
else
{
if (!set_item(index, no, col))
{
log("listview set_item") << "index:" << index << "col:" << col;
return false;
}
}
}
no++;
}
catch (std::exception& e)
{
log(e) << "insert_item exception:" << col;
return false;
}
}
return true;
}
void wex::listview::item_activated(long item_number)
{
assert(item_number >= 0);
switch (m_data.type())
{
case data::listview::FOLDER:
{
wxDirDialog dir_dlg(
this,
_(wxDirSelectorPromptStr),
GetItemText(item_number),
wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dir_dlg.ShowModal() == wxID_OK)
{
SetItemText(item_number, dir_dlg.GetPath());
listitem(this, item_number).update();
}
}
break;
case data::listview::TSV:
{
m_frame->stc_entry_dialog_title(_("Item"));
m_frame->stc_entry_dialog_component()->set_text(
item_to_text(item_number));
if (m_frame->show_stc_entry_dialog(true) == wxID_OK)
{
int col = 0;
boost::tokenizer<boost::char_separator<char>> tok(
m_frame->stc_entry_dialog_component()->get_text(),
boost::char_separator<char>(
std::string(1, m_field_separator).c_str()));
for (auto it = tok.begin(); it != tok.end() && col < GetColumnCount();
++it)
{
set_item(item_number, col++, *it);
}
}
}
break;
default:
// Cannot be const because of SetItem later on.
if (listitem item(this, item_number); item.path().file_exists())
{
const auto no(get_item_text(item_number, _("Line No")));
data::control data(
(m_data.type() == data::listview::FIND && !no.empty() ?
data::control()
.line(std::stoi(no))
.find(get_item_text(item_number, _("Match"))) :
data::control()));
m_frame->open_file(item.path(), data);
}
else if (item.path().dir_exists())
{
m_frame->stc_entry_dialog_title(_("Folder Type"));
m_frame->stc_entry_dialog_component()->set_text(
get_item_text(item_number, _("Type")));
if (m_frame->show_stc_entry_dialog(true) == wxID_OK)
{
item.set_item(
_("Type"),
m_frame->stc_entry_dialog_component()->get_text());
}
}
}
}
bool wex::listview::item_from_text(const std::string& text)
{
if (text.empty())
{
return false;
}
bool modified = false;
for (const auto& it : boost::tokenizer<boost::char_separator<char>>(
text,
boost::char_separator<char>("\n")))
{
switch (m_data.type())
{
case data::listview::NONE:
case data::listview::TSV:
if (insert_item(tokenize<std::vector<std::string>>(
it,
std::string(1, m_field_separator).c_str())))
{
modified = true;
}
break;
default:
modified = true;
if (!InReportView())
{
listitem(this, path(it)).insert();
}
else if (!report_view(it))
{
return false;
}
}
}
m_frame->update_statusbar(this);
return modified;
}
const std::string wex::listview::item_to_text(long item_number) const
{
std::string text;
if (item_number == -1)
{
for (auto i = 0; i < GetItemCount(); i++)
{
text += GetItemText(i) + "\n";
}
return text;
}
switch (m_data.type())
{
case data::listview::FILE:
case data::listview::HISTORY:
{
const listitem item(const_cast<listview*>(this), item_number);
text =
(item.path().stat().is_ok() ? item.path().string() :
item.path().filename());
if (item.path().dir_exists() && !item.path().file_exists())
{
text += field_separator() + get_item_text(item_number, _("Type"));
}
}
break;
case data::listview::FOLDER:
return GetItemText(item_number);
default:
for (int col = 0; col < GetColumnCount(); col++)
{
text += GetItemText(item_number, col);
if (col < GetColumnCount() - 1)
{
text += m_field_separator;
}
}
}
return text;
}
void wex::listview::items_update()
{
if (
m_data.type() != data::listview::NONE &&
m_data.type() != data::listview::TSV)
{
for (auto i = 0; i < GetItemCount(); i++)
{
listitem(this, i).update();
}
}
}
bool wex::listview::load(const std::list<std::string>& l)
{
clear();
if (l.empty())
{
return true;
}
if (m_data.type() == data::listview::TSV && GetColumnCount() == 0)
{
boost::tokenizer<boost::char_separator<char>> tok(
l.front(),
boost::char_separator<char>("\t"));
int i = 0;
std::for_each(
tok.begin(),
tok.end(),
[this, &i](const auto&)
{
append_columns({{std::to_string(i++ + 1), column::STRING, 50}});
});
}
for (const auto& it : l)
{
item_from_text(it);
}
return true;
}
bool wex::listview::on_command(wxCommandEvent& event)
{
switch (const long new_index =
GetSelectedItemCount() > 0 ? GetFirstSelected() : -1;
data().type())
{
case data::listview::TSV:
m_frame->stc_entry_dialog_title(_("Item"));
m_frame->stc_entry_dialog_component()->set_text(item_to_text(new_index));
if (m_frame->show_stc_entry_dialog(true) == wxID_OK)
{
insert_item(
tokenize<std::vector<std::string>>(
m_frame->stc_entry_dialog_component()->get_text(),
std::string(1, field_separator()).c_str()),
new_index);
}
break;
default:
{
std::string defaultPath;
if (GetSelectedItemCount() > 0)
{
defaultPath = listitem(this, GetFirstSelected()).path().string();
}
wxDirDialog dir_dlg(
this,
_(wxDirSelectorPromptStr),
defaultPath,
wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dir_dlg.ShowModal() == wxID_OK)
{
const auto no =
(GetSelectedItemCount() > 0 ? GetFirstSelected() : GetItemCount());
listitem(this, path(dir_dlg.GetPath().ToStdString())).insert(no);
return true;
}
}
}
return false;
}
void wex::listview::print()
{
wxBusyCursor wait;
printing::get()->get_html_printer()->PrintText(build_page());
}
void wex::listview::print_preview()
{
wxBusyCursor wait;
printing::get()->get_html_printer()->PreviewText(build_page());
}
void wex::listview::process_idle(wxIdleEvent& event)
{
event.Skip();
if (
!IsShown() || interruptible::is_running() || GetItemCount() == 0 ||
!config("AllowSync").get(true))
{
return;
}
if (m_item_number < GetItemCount())
{
if (listitem item(this, m_item_number);
item.path().file_exists() &&
(item.path().stat().get_modification_time_str() !=
get_item_text(m_item_number, _("Modified")) ||
item.path().stat().is_readonly() != item.is_readonly()))
{
item.update();
log::status() << item.path();
m_item_updated = true;
}
m_item_number++;
}
else
{
m_item_number = 0;
if (m_item_updated)
{
if (m_data.type() == data::listview::FILE)
{
if (
config("list.SortSync").get(true) &&
sorted_column_no() == find_column(_("Modified")))
{
sort_column(_("Modified"), SORT_KEEP);
}
}
m_item_updated = false;
}
}
}
void wex::listview::process_list(wxListEvent& event, wxEventType type)
{
if (type == wxEVT_LIST_ITEM_SELECTED)
{
if (m_data.type() != data::listview::NONE && GetSelectedItemCount() == 1)
{
if (const wex::path fn(listitem(this, event.GetIndex()).path());
fn.stat().is_ok())
{
log::status() << fn;
}
else
{
log::status(get_item_text(GetFirstSelected()));
}
}
}
else if (type == wxEVT_LIST_BEGIN_DRAG)
{
// Start drag operation.
std::string text;
for (auto i = GetFirstSelected(); i != -1; i = GetNextSelected(i))
text += item_to_text(i) + "\n";
if (!text.empty())
{
wxTextDataObject textData(text);
wxDropSource source(textData, this);
source.DoDragDrop(wxDragCopy);
}
}
m_frame->update_statusbar(this);
}
void wex::listview::process_match(wxCommandEvent& event)
{
const auto* m = static_cast<path_match*>(event.GetClientData());
listitem item(this, m->path());
item.insert();
item.set_item(_("Line No"), std::to_string(m->line_no() + 1));
item.set_item(_("Line"), context(m->line(), m->pos()));
item.set_item(_("Match"), find_replace_data::get()->get_find_string());
item.set_item(_("Type"), event.GetString());
delete m;
}
void wex::listview::process_mouse(wxMouseEvent& event)
{
menu::menu_t style(menu::menu_t().set(menu::IS_POPUP).set(menu::IS_VISUAL));
if (GetSelectedItemCount() > 0)
style.set(menu::IS_SELECTED);
if (GetItemCount() == 0)
style.set(menu::IS_EMPTY);
if (m_data.type() != data::listview::FIND)
style.set(menu::CAN_PASTE);
if (GetSelectedItemCount() == 0 && GetItemCount() > 0)
{
style.set(menu::ALLOW_CLEAR);
}
wex::menu menu(style);
build_popup_menu(menu);
if (menu.GetMenuItemCount() > 0)
{
PopupMenu(&menu);
}
}
bool wex::listview::report_view(const std::string& text)
{
boost::tokenizer<boost::char_separator<char>> tok(
text,
boost::char_separator<char>(std::string(1, m_field_separator).c_str()));
if (auto tt = tok.begin(); tt != tok.end())
{
if (path fn(*tt); fn.file_exists())
{
listitem item(this, fn);
item.insert();
// And try to set the rest of the columns
// (that are not already set by inserting).
int col = 1;
while (++tt != tok.end() && col < GetColumnCount() - 1)
{
if (
col != find_column(_("Type")) && col != find_column(_("In Folder")) &&
col != find_column(_("Size")) && col != find_column(_("Modified")))
{
if (!set_item(item.GetId(), col, *tt))
return false;
}
col++;
}
}
else
{
// Now we need only the first column (containing findfiles). If
// more columns are present, these are ignored.
const auto& findfiles =
(std::next(tt) != tok.end() ? *(std::next(tt)) : text);
listitem(this, path(*tt), findfiles).insert();
}
}
else
{
listitem(this, path(text)).insert();
}
return true;
}
const std::list<std::string> wex::listview::save() const
{
std::list<std::string> l;
for (auto i = 0; i < GetItemCount(); i++)
{
l.emplace_back(item_to_text(i));
}
return l;
}
std::vector<std::string>* pitems;
int wxCALLBACK compare_cb(wxIntPtr item1, wxIntPtr item2, wxIntPtr sortData)
{
const bool ascending = (sortData > 0);
const auto& str1 = (*pitems)[item1];
const auto& str2 = (*pitems)[item2];
// should return 0 if the items are equal,
// negative value if the first item is less than the second one
// and positive value if the first one is greater than the second one
if (str1.empty() && str2.empty())
{
return 0;
}
else if (str1.empty())
{
return -1;
}
else if (str2.empty())
{
return 1;
}
switch (const auto type = (wex::column::type_t)std::abs(sortData); type)
{
case wex::column::DATE:
{
const auto& [r1, t1] = wex::chrono().get_time(str1);
const auto& [r2, t2] = wex::chrono().get_time(str2);
if (!r1 || !r2)
return 0;
if (ascending)
return wex::compare((unsigned long)t1, (unsigned long)t2);
else
return wex::compare((unsigned long)t2, (unsigned long)t1);
}
break;
case wex::column::FLOAT:
if (ascending)
return wex::compare(std::stof(str1), std::stof(str2));
else
return wex::compare(std::stof(str2), std::stof(str1));
break;
case wex::column::INT:
if (ascending)
return wex::compare(std::stoi(str1), std::stoi(str2));
else
return wex::compare(std::stoi(str2), std::stoi(str1));
break;
case wex::column::STRING:
if (!wex::find_replace_data::get()->match_case())
{
if (ascending)
return wex::ignore_case(str1).compare(wex::ignore_case(str2));
else
return wex::ignore_case(str2).compare(wex::ignore_case(str1));
}
else
{
if (ascending)
return str1.compare(str2);
else
return str2.compare(str1);
}
break;
default:
assert(0);
}
return 0;
}
bool wex::listview::set_item(
long index,
int column,
const std::string& text,
int imageId)
{
if (text.empty())
return true;
try
{
switch (m_columns[column].type())
{
case column::DATE:
if (const auto& [r, t] = chrono().get_time(text); !r)
return false;
break;
case column::FLOAT:
(void)std::stof(text);
break;
case column::INT:
(void)std::stoi(text);
break;
case column::STRING:
break;
default:
break;
}
return SetItem(index, column, text, imageId);
}
catch (std::exception& e)
{
log(e) << "index:" << index << "col:" << column << ":" << text;
return false;
}
}
bool wex::listview::set_item_image(long item_number, const wxArtID& artid)
{
if (item_number < 0 || item_number >= GetItemCount())
{
return false;
}
return (
m_data.image() == data::listview::IMAGE_ART ?
SetItemImage(item_number, get_art_id(artid)) :
false);
}
bool wex::listview::sort_column(int column_no, sort_t sort_method)
{
if (column_no == -1 || column_no >= static_cast<int>(m_columns.size()))
{
return false;
}
wxBusyCursor wait;
sort_column_reset();
auto& sorted_col = m_columns[column_no];
sorted_col.set_is_sorted_ascending(sort_method);
std::vector<std::string> items;
pitems = &items;
for (int i = 0; i < GetItemCount(); i++)
{
items.emplace_back(GetItemText(i, column_no));
SetItemData(i, i);
}
try
{
const auto sortdata =
(sorted_col.is_sorted_ascending() ? sorted_col.type() :
(0 - sorted_col.type()));
SortItems(compare_cb, sortdata);
ShowSortIndicator(column_no, sorted_col.is_sorted_ascending());
m_sorted_column_no = column_no;
if (GetItemCount() > 0)
{
items_update();
after_sorting();
}
log::status(_("Sorted on")) << sorted_col.GetText().ToStdString();
return true;
}
catch (std::exception& e)
{
log(e) << "sort:" << sorted_col.GetText().ToStdString();
return false;
}
}
void wex::listview::sort_column_reset()
{
if (m_sorted_column_no != -1)
{
RemoveSortIndicator();
m_sorted_column_no = -1;
}
}
| 22.669199 | 80 | 0.559817 | [
"vector"
] |
f54475a4b380eb975a1c8ef1a30e5001b6918348 | 1,079 | cpp | C++ | cses/introductoryproblems/1068_WeirdAlgorithm.cpp | seahrh/cses-problem-set | 1d4ab18f7686ab4e87cc74a5e911494780e42b21 | [
"MIT"
] | null | null | null | cses/introductoryproblems/1068_WeirdAlgorithm.cpp | seahrh/cses-problem-set | 1d4ab18f7686ab4e87cc74a5e911494780e42b21 | [
"MIT"
] | null | null | null | cses/introductoryproblems/1068_WeirdAlgorithm.cpp | seahrh/cses-problem-set | 1d4ab18f7686ab4e87cc74a5e911494780e42b21 | [
"MIT"
] | 1 | 2022-02-12T11:05:13.000Z | 2022-02-12T11:05:13.000Z | /*
Consider an algorithm that takes as input a positive integer n.
If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one.
The algorithm repeats this, until n is one. For example, the sequence for n=3 is as follows:
3→10→5→16→8→4→2→1
Your task is to simulate the execution of the algorithm for a given value of n.
Input
The only input line contains an integer n.
Output
Print a line that contains all values of n during the algorithm.
Constraints
1≤n≤106
Example
Input:
3
Output:
3 10 5 16 8 4 2 1
*/
#include <bits/stdc++.h>
#define ll long long
using namespace std;
vector<ll> solve(ll n)
{
vector<ll> res = {n};
while (n != 1)
{
if (n % 2 == 0)
{
n /= 2;
}
else
{
n = 3 * n + 1;
}
res.push_back(n);
}
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n;
cin >> n;
vector<ll> res = solve(n);
for (ll i : res)
{
cout << i << " ";
}
return 0;
}
| 19.981481 | 114 | 0.589435 | [
"vector"
] |
f545dd523369f831b6e7c13be56302152e0159f0 | 1,280 | cpp | C++ | source/Applications/Advanced/TransformPointCloudFromMillimetersToMeters/TransformPointCloudFromMillimetersToMeters.cpp | zivid/cpp-extra-samples | 133dd8514176af3fd2bbbb604520f4439430ee00 | [
"BSD-3-Clause"
] | 3 | 2019-06-17T12:00:31.000Z | 2020-01-25T07:49:26.000Z | source/Applications/Advanced/TransformPointCloudFromMillimetersToMeters/TransformPointCloudFromMillimetersToMeters.cpp | zivid/cpp-extra-samples | 133dd8514176af3fd2bbbb604520f4439430ee00 | [
"BSD-3-Clause"
] | 84 | 2019-07-15T16:12:41.000Z | 2020-05-26T13:23:27.000Z | source/Applications/Advanced/TransformPointCloudFromMillimetersToMeters/TransformPointCloudFromMillimetersToMeters.cpp | zivid/cpp-extra-samples | 133dd8514176af3fd2bbbb604520f4439430ee00 | [
"BSD-3-Clause"
] | 4 | 2019-12-11T11:31:48.000Z | 2020-04-27T10:00:36.000Z | /*
Transform point cloud data from millimeters to meters.
The ZDF file for this sample can be found under the main instructions for Zivid samples.
*/
#include <Zivid/Zivid.h>
#include <iostream>
int main()
{
try
{
Zivid::Application zivid;
const auto dataFile = std::string(ZIVID_SAMPLE_DATA_DIR) + "/ArucoMarkerInCameraOrigin.zdf";
std::cout << "Reading " << dataFile << " point cloud" << std::endl;
auto frame = Zivid::Frame(dataFile);
auto pointCloud = frame.pointCloud();
const auto transformMillimetersToMeters =
Zivid::Matrix4x4{ { 0.001F, 0, 0, 0 }, { 0, 0.001F, 0, 0 }, { 0, 0, 0.001F, 0 }, { 0, 0, 0, 1 } };
std::cout << "Transforming point cloud from mm to m" << std::endl;
pointCloud.transform(transformMillimetersToMeters);
const auto transformedFile = "FrameInMeters.zdf";
std::cout << "Saving transformed point cloud to file: " << transformedFile << std::endl;
frame.save(transformedFile);
}
catch(const std::exception &e)
{
std::cerr << "Error: " << Zivid::toString(e) << std::endl;
std::cout << "Press enter to exit." << std::endl;
std::cin.get();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 29.767442 | 110 | 0.609375 | [
"transform"
] |
f54a49f0adbdb24225de6d71c60a2627b2614fd3 | 927 | cc | C++ | src/releaseComponent.cc | bjornos/kalyra | 0effb44f9190af72347d97468a8c2cf7bf6d9620 | [
"MIT"
] | null | null | null | src/releaseComponent.cc | bjornos/kalyra | 0effb44f9190af72347d97468a8c2cf7bf6d9620 | [
"MIT"
] | 16 | 2018-10-05T14:21:22.000Z | 2019-05-06T11:53:59.000Z | src/releaseComponent.cc | bjornos/kalyra | 0effb44f9190af72347d97468a8c2cf7bf6d9620 | [
"MIT"
] | null | null | null | #include "kalyra.hh"
#include "releaseComponent.hh"
using namespace std;
releaseComponent::releaseComponent(vector<string> preCommands,
vector<string> postCommands, vector<string> components) :
preCommands(preCommands),
postCommands(postCommands),
components(components)
{
}
releaseComponent::~releaseComponent()
{
}
string releaseComponent::getFileName(string& pathName)
{
string s = string(pathName);
size_t pos = 0;
const string delim = PLT_SLASH;
// strip away everything from path name until the final slash
while ((pos = s.find(delim)) != string::npos) {
s.substr(0, pos);
s.erase(0, pos + delim.length());
}
return s;
}
vector<string>& releaseComponent::getPreCommands()
{
return preCommands;
}
vector<string>& releaseComponent::getComponents()
{
return components;
}
vector<string>& releaseComponent::getPostCommands()
{
return postCommands;
}
| 18.918367 | 65 | 0.703344 | [
"vector"
] |
f55e56ee23a35ff20dcaa8e8d86874e87b23c973 | 2,974 | cpp | C++ | client/crypto-sdk/test/crc32-test.cpp | orbs-network/orbs-network-typescript | a878afb5e6f8de3a2042764f0cecd6f27d113c18 | [
"MIT"
] | 21 | 2018-06-27T13:48:43.000Z | 2019-09-10T10:55:03.000Z | client/crypto-sdk/test/crc32-test.cpp | orbs-network/orbs-network-typescript | a878afb5e6f8de3a2042764f0cecd6f27d113c18 | [
"MIT"
] | 1 | 2018-08-01T08:55:28.000Z | 2018-08-01T18:09:22.000Z | client/crypto-sdk/test/crc32-test.cpp | orbs-network/orbs-network-typescript | a878afb5e6f8de3a2042764f0cecd6f27d113c18 | [
"MIT"
] | null | null | null | #include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../lib/crc32.h"
#include "../lib/utils.h"
using namespace std;
using namespace testing;
using namespace Orbs;
TEST(Hash, computes_binary_CRC32_of_binary) {
vector<uint8_t> res;
vector<uint8_t> data1;
CRC32::Hash(data1, res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("00000000")));
uint8_t rawData2[] = "Hello World!";
vector<uint8_t> data2(rawData2, rawData2 + sizeof(rawData2) - 1);
CRC32::Hash(data2, res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("1c291ca3")));
uint8_t rawData3[] = "If I sign myself Jean-Paul Sartre it is not the same thing as if I sign myself Jean-Paul Sartre, Nobel Prize winner.";
vector<uint8_t> data3(rawData3, rawData3 + sizeof(rawData3) - 1);
CRC32::Hash(data3, res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("75e33aef")));
uint8_t rawData4[] = "אורבס";
vector<uint8_t> data4(rawData4, rawData4 + sizeof(rawData4) - 1);
CRC32::Hash(data4, res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("426cf367")));
}
TEST(Hash, computes_binary_CRC32_of_string) {
vector<uint8_t> res;
CRC32::Hash("", res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("00000000")));
CRC32::Hash("Hello World!", res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("1c291ca3")));
CRC32::Hash("If I sign myself Jean-Paul Sartre it is not the same thing as if I sign myself Jean-Paul Sartre, Nobel Prize winner.", res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("75e33aef")));
CRC32::Hash("אורבס", res);
EXPECT_THAT(res, ElementsAreArray(Utils::Hex2Vec("426cf367")));
}
TEST(Hash, computes_string_CRC32_of_binary) {
string res;
vector<uint8_t> data1;
CRC32::Hash(data1, res);
EXPECT_STREQ(res.c_str(), "00000000");
uint8_t rawData2[] = "Hello World!";
vector<uint8_t> data2(rawData2, rawData2 + sizeof(rawData2) - 1);
CRC32::Hash(data2, res);
EXPECT_STREQ(res.c_str(), "1c291ca3");
uint8_t rawData3[] = "If I sign myself Jean-Paul Sartre it is not the same thing as if I sign myself Jean-Paul Sartre, Nobel Prize winner.";
vector<uint8_t> data3(rawData3, rawData3 + sizeof(rawData3) - 1);
CRC32::Hash(data3, res);
EXPECT_STREQ(res.c_str(), "75e33aef");
uint8_t rawData4[] = "אורבס";
vector<uint8_t> data4(rawData4, rawData4 + sizeof(rawData4) - 1);
CRC32::Hash(data4, res);
EXPECT_STREQ(res.c_str(), "426cf367");
}
TEST(Hash, computes_string_CRC32_of_string) {
string res;
CRC32::Hash("", res);
EXPECT_STREQ(res.c_str(), "00000000");
CRC32::Hash("Hello World!", res);
EXPECT_STREQ(res.c_str(), "1c291ca3");
CRC32::Hash("If I sign myself Jean-Paul Sartre it is not the same thing as if I sign myself Jean-Paul Sartre, Nobel Prize winner.", res);
EXPECT_STREQ(res.c_str(), "75e33aef");
CRC32::Hash("אורבס", res);
EXPECT_STREQ(res.c_str(), "426cf367");
}
| 33.795455 | 144 | 0.682582 | [
"vector"
] |
f562d944ff296405d9484b1807926f66a1bed211 | 3,093 | cc | C++ | chrome/browser/sessions/session_restore_delegate.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/sessions/session_restore_delegate.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/sessions/session_restore_delegate.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 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 "chrome/browser/sessions/session_restore_delegate.h"
#include <stddef.h>
#include <utility>
#include "base/macros.h"
#include "base/metrics/field_trial.h"
#include "chrome/browser/sessions/session_restore_stats_collector.h"
#include "chrome/browser/sessions/tab_loader.h"
#include "chrome/common/url_constants.h"
#include "components/favicon/content/content_favicon_driver.h"
#include "content/public/browser/web_contents.h"
namespace {
bool IsInternalPage(const GURL& url) {
// There are many chrome:// UI URLs, but only look for the ones that users
// are likely to have open. Most of the benefit is from the NTP URL.
const char* const kReloadableUrlPrefixes[] = {
chrome::kChromeUIDownloadsURL,
chrome::kChromeUIHistoryURL,
chrome::kChromeUINewTabURL,
chrome::kChromeUISettingsURL,
};
// Prefix-match against the table above. Use strncmp to avoid allocating
// memory to convert the URL prefix constants into std::strings.
for (size_t i = 0; i < arraysize(kReloadableUrlPrefixes); ++i) {
if (!strncmp(url.spec().c_str(), kReloadableUrlPrefixes[i],
strlen(kReloadableUrlPrefixes[i])))
return true;
}
return false;
}
} // namespace
SessionRestoreDelegate::RestoredTab::RestoredTab(content::WebContents* contents,
bool is_active,
bool is_app,
bool is_pinned)
: contents_(contents),
is_active_(is_active),
is_app_(is_app),
is_internal_page_(IsInternalPage(contents->GetLastCommittedURL())),
is_pinned_(is_pinned) {
}
bool SessionRestoreDelegate::RestoredTab::operator<(
const RestoredTab& right) const {
// Tab with internal web UI like NTP or Settings are good choices to
// defer loading.
if (is_internal_page_ != right.is_internal_page_)
return !is_internal_page_;
// Pinned tabs should be loaded first.
if (is_pinned_ != right.is_pinned_)
return is_pinned_;
// Apps should be loaded before normal tabs.
if (is_app_ != right.is_app_)
return is_app_;
// Finally, older tabs should be deferred first.
return contents_->GetLastActiveTime() > right.contents_->GetLastActiveTime();
}
// static
void SessionRestoreDelegate::RestoreTabs(
const std::vector<RestoredTab>& tabs,
const base::TimeTicks& restore_started) {
// Restore the favicon for all tabs. Any tab may end up being deferred due
// to memory pressure so it's best to have some visual indication of its
// contents.
for (const auto& restored_tab : tabs) {
// Restore the favicon for deferred tabs.
favicon::ContentFaviconDriver* favicon_driver =
favicon::ContentFaviconDriver::FromWebContents(restored_tab.contents());
favicon_driver->FetchFavicon(favicon_driver->GetActiveURL());
}
TabLoader::RestoreTabs(tabs, restore_started);
}
| 36.821429 | 80 | 0.700938 | [
"vector"
] |
f562fb04707a751d35422aade3a9b0a24622b992 | 1,737 | cpp | C++ | Sparky-core/src/maths/vec3.cpp | aadipoddar/Sparky | 2a4caf905aa3056c8290ea10735e87666dc22912 | [
"Apache-2.0"
] | null | null | null | Sparky-core/src/maths/vec3.cpp | aadipoddar/Sparky | 2a4caf905aa3056c8290ea10735e87666dc22912 | [
"Apache-2.0"
] | null | null | null | Sparky-core/src/maths/vec3.cpp | aadipoddar/Sparky | 2a4caf905aa3056c8290ea10735e87666dc22912 | [
"Apache-2.0"
] | null | null | null | #include "vec3.h"
namespace sparky
{
namespace maths
{
vec3::vec3()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
vec3::vec3(const float& x, const float& y, const float& z)
{
this->x = x;
this->y = y;
this->z = z;
}
vec3& vec3::add(const vec3& other)
{
x += other.x;
y += other.y;
z += other.z;
return *this;
}
vec3& vec3::subtract(const vec3& other)
{
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
vec3& vec3::multiply(const vec3& other)
{
x *= other.x;
y *= other.y;
z *= other.z;
return *this;
}
vec3& vec3::divide(const vec3& other)
{
x /= other.x;
y /= other.y;
z /= other.z;
return *this;
}
vec3 operator+(vec3 left, const vec3& right)
{
return left.add(right);
}
vec3 operator-(vec3 left, const vec3& right)
{
return left.subtract(right);
}
vec3 operator*(vec3 left, const vec3& right)
{
return left.multiply(right);
}
vec3 operator/(vec3 left, const vec3& right)
{
return left.divide(right);
}
bool vec3::operator==(const vec3& other)
{
return x == other.x && y == other.y && z == other.z;
}
bool vec3::operator!=(const vec3& other)
{
return !(*this == other);
}
vec3& vec3::operator+=(const vec3& other)
{
return add(other);
}
vec3& vec3::operator-=(const vec3& other)
{
return subtract(other);
}
vec3& vec3::operator*=(const vec3& other)
{
return multiply(other);
}
vec3& vec3::operator/=(const vec3& other)
{
return divide(other);
}
std::ostream& operator<<(std::ostream& stream, const vec3& vector)
{
stream << " vec3: (" << vector.x << ", " << vector.y << ", " << vector.z << ")";
return stream;
}
}
} | 16.083333 | 83 | 0.553253 | [
"vector"
] |
f5643cf6f66ba5e23b3bad6429d305326f98b799 | 7,242 | cpp | C++ | source/tests/wasm_loader_test/source/wasm_loader_test.cpp | ketangupta34/core | e8422f94a3c13a75cf85424f45b86ac5eaf30c33 | [
"Apache-2.0"
] | null | null | null | source/tests/wasm_loader_test/source/wasm_loader_test.cpp | ketangupta34/core | e8422f94a3c13a75cf85424f45b86ac5eaf30c33 | [
"Apache-2.0"
] | null | null | null | source/tests/wasm_loader_test/source/wasm_loader_test.cpp | ketangupta34/core | e8422f94a3c13a75cf85424f45b86ac5eaf30c33 | [
"Apache-2.0"
] | null | null | null | /*
* WebAssembly Loader Tests by Parra Studios
*
* Copyright (C) 2016 - 2021 Vicente Eduardo Ferrer Garcia <vic798@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <gtest/gtest.h>
#include <metacall/metacall.h>
#include <metacall/metacall_value.h>
class wasm_loader_test : public testing::Test
{
protected:
void SetUp() override
{
metacall_initialize();
}
void TearDown() override
{
metacall_destroy();
}
};
void TestFunction(void *handle, const char *name, const std::vector<enum metacall_value_id> &expected_param_types, enum metacall_value_id expected_return_type)
{
void *func = metacall_handle_function(handle, name);
// GoogleTest does not support `ASSERT_NE(NULL, actual)`.
ASSERT_TRUE(func != NULL);
ASSERT_EQ(expected_param_types.size(), metacall_function_size(func));
for (size_t i = 0; i < expected_param_types.size(); i++)
{
enum metacall_value_id param_type;
ASSERT_EQ(0, metacall_function_parameter_type(func, i, ¶m_type));
ASSERT_EQ(expected_param_types[i], param_type);
}
enum metacall_value_id return_type;
ASSERT_EQ(0, metacall_function_return_type(func, &return_type));
ASSERT_EQ(expected_return_type, return_type);
}
TEST_F(wasm_loader_test, InitializeAndDestroy)
{
// This is extremely hacky and causes an error when loading the buffer,
// since it is invalid. However, it is currently impossible to initialize a
// loader without attempting to load a handle with it. Ideally, there would
// be a `metacall_initialize_loader` function or similar.
const char dummy_buffer[1] = { 0 };
metacall_load_from_memory("wasm", dummy_buffer, 1, NULL);
ASSERT_EQ(0, metacall_is_initialized("wasm"));
// `metacall_destroy` does nothing if Metacall is not initialized, so we
// can safely call it here even though we also call it during tear-down.
ASSERT_EQ(0, metacall_destroy());
}
TEST_F(wasm_loader_test, LoadBinaryFromMemory)
{
// See https://webassembly.github.io/spec/core/binary/modules.html#binary-module
const char empty_module[] = {
0x00, 0x61, 0x73, 0x6d, // Magic bytes
0x01, 0x00, 0x00, 0x00 // Version
};
ASSERT_EQ(0, metacall_load_from_memory("wasm", empty_module, sizeof(empty_module), NULL));
const char invalid_module[] = { 0 };
ASSERT_NE(0, metacall_load_from_memory("wasm", invalid_module, sizeof(invalid_module), NULL));
}
TEST_F(wasm_loader_test, LoadTextFromMemory)
{
const char *empty_module = "(module)";
ASSERT_EQ(0, metacall_load_from_memory("wasm", empty_module, strlen(empty_module), NULL));
const char *invalid_module = "(invalid)";
ASSERT_NE(0, metacall_load_from_memory("wasm", invalid_module, strlen(invalid_module), NULL));
}
#if defined(BUILD_SCRIPT_TESTS)
TEST_F(wasm_loader_test, LoadFromFile)
{
const char *empty_module_filename = "empty_module.wat";
const char *invalid_module_filename = "invalid_module.wat";
ASSERT_EQ(0, metacall_load_from_file("wasm", &empty_module_filename, 1, NULL));
ASSERT_NE(0, metacall_load_from_file("wasm", &invalid_module_filename, 1, NULL));
}
TEST_F(wasm_loader_test, LoadFromPackage)
{
ASSERT_EQ(0, metacall_load_from_package("wasm", "empty_module.wasm", NULL));
ASSERT_NE(0, metacall_load_from_package("wasm", "invalid_module.wasm", NULL));
}
TEST_F(wasm_loader_test, DiscoverFunctions)
{
const char *functions_module_filename = "functions.wat";
void *handle;
ASSERT_EQ(0, metacall_load_from_file("wasm", &functions_module_filename, 1, &handle));
ASSERT_EQ(NULL, metacall_handle_function(handle, "does_not_exist"));
TestFunction(handle, "none_ret_none", {}, METACALL_INVALID);
TestFunction(handle, "i32_ret_none", { METACALL_INT }, METACALL_INVALID);
TestFunction(handle, "i32_f32_i64_f64_ret_none", { METACALL_INT, METACALL_FLOAT, METACALL_LONG, METACALL_DOUBLE }, METACALL_INVALID);
TestFunction(handle, "none_ret_i32", {}, METACALL_INT);
TestFunction(handle, "none_ret_i32_f32_i64_f64", {}, METACALL_ARRAY);
TestFunction(handle, "i32_f32_i64_f64_ret_i32_f32_i64_f64", { METACALL_INT, METACALL_FLOAT, METACALL_LONG, METACALL_DOUBLE }, METACALL_ARRAY);
}
TEST_F(wasm_loader_test, CallFunctions)
{
const char *functions_module_filename = "functions.wat";
ASSERT_EQ(0, metacall_load_from_file("wasm", &functions_module_filename, 1, NULL));
void *ret = metacall("none_ret_none");
ASSERT_EQ(NULL, ret);
ret = metacall("i32_ret_none", 0);
ASSERT_EQ(NULL, ret);
ret = metacall("i32_f32_i64_f64_ret_none", 0, 0, 0, 0);
ASSERT_EQ(NULL, ret);
ret = metacall("none_ret_i32");
ASSERT_EQ(METACALL_INT, metacall_value_id(ret));
ASSERT_EQ(1, metacall_value_to_int(ret));
metacall_value_destroy(ret);
ret = metacall("none_ret_i32_f32_i64_f64");
ASSERT_EQ(METACALL_ARRAY, metacall_value_id(ret));
void **values = metacall_value_to_array(ret);
ASSERT_EQ(METACALL_INT, metacall_value_id(values[0]));
ASSERT_EQ(METACALL_FLOAT, metacall_value_id(values[1]));
ASSERT_EQ(METACALL_LONG, metacall_value_id(values[2]));
ASSERT_EQ(METACALL_DOUBLE, metacall_value_id(values[3]));
ASSERT_EQ(1, metacall_value_to_int(values[0]));
ASSERT_EQ(2, metacall_value_to_float(values[1]));
ASSERT_EQ(3, metacall_value_to_long(values[2]));
ASSERT_EQ(4, metacall_value_to_double(values[3]));
metacall_value_destroy(ret);
ret = metacall("i32_f32_i64_f64_ret_i32_f32_i64_f64", 0, 0, 0, 0);
ASSERT_EQ(METACALL_ARRAY, metacall_value_id(ret));
values = metacall_value_to_array(ret);
ASSERT_EQ(METACALL_INT, metacall_value_id(values[0]));
ASSERT_EQ(METACALL_FLOAT, metacall_value_id(values[1]));
ASSERT_EQ(METACALL_LONG, metacall_value_id(values[2]));
ASSERT_EQ(METACALL_DOUBLE, metacall_value_id(values[3]));
ASSERT_EQ(1, metacall_value_to_int(values[0]));
ASSERT_EQ(2, metacall_value_to_float(values[1]));
ASSERT_EQ(3, metacall_value_to_long(values[2]));
ASSERT_EQ(4, metacall_value_to_double(values[3]));
metacall_value_destroy(ret);
// The return value should be NULL when a trap is reached
ret = metacall("trap");
ASSERT_EQ(NULL, ret);
}
TEST_F(wasm_loader_test, LinkModules)
{
const char *modules[] = {
"exports1.wat",
"exports2.wat",
"imports.wat"
};
ASSERT_EQ(0, metacall_load_from_file("wasm", modules, sizeof(modules) / sizeof(modules[0]), NULL));
void *ret = metacall("duplicate_func_i32");
ASSERT_EQ(METACALL_INT, metacall_value_id(ret));
ASSERT_EQ(1, metacall_value_to_int(ret));
metacall_value_destroy(ret);
ret = metacall("duplicate_func_i64");
ASSERT_EQ(METACALL_LONG, metacall_value_id(ret));
ASSERT_EQ(2, metacall_value_to_long(ret));
metacall_value_destroy(ret);
}
TEST_F(wasm_loader_test, InvalidLinkModules)
{
const char *modules[] = {
"exports1.wat",
"imports.wat"
};
ASSERT_EQ(1, metacall_load_from_file("wasm", modules, sizeof(modules) / sizeof(modules[0]), NULL));
}
#endif
| 33.683721 | 159 | 0.763739 | [
"vector"
] |
f565da980e888f722e91e2e79000b35ad33b3302 | 481 | hpp | C++ | Vocabulary.hpp | Sanaxen/N3LP | 06526ba558231c5973d26a5f2b876a9379dc4502 | [
"MIT"
] | 93 | 2015-12-16T13:17:23.000Z | 2022-03-01T17:02:51.000Z | Vocabulary.hpp | Sanaxen/N3LP | 06526ba558231c5973d26a5f2b876a9379dc4502 | [
"MIT"
] | 2 | 2016-01-03T23:48:17.000Z | 2017-10-17T05:29:08.000Z | Vocabulary.hpp | Sanaxen/N3LP | 06526ba558231c5973d26a5f2b876a9379dc4502 | [
"MIT"
] | 32 | 2016-01-07T15:52:50.000Z | 2021-02-08T00:55:26.000Z | #pragma once
#include <string>
#include <unordered_map>
#include <vector>
class Vocabulary{
public:
Vocabulary(const std::string& trainFile, const int tokenFreqThreshold);
class Token;
std::unordered_map<std::string, int> tokenIndex;
std::vector<Vocabulary::Token*> tokenList;
int eosIndex;
int unkIndex;
};
class Vocabulary::Token{
public:
Token(const std::string& str_, const int count_):
str(str_), count(count_)
{};
std::string str;
int count;
};
| 17.178571 | 73 | 0.706861 | [
"vector"
] |
f565fd8a45096cbd25207833cda64ed9ca489e37 | 720 | hpp | C++ | string/RunLength.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | 3 | 2021-11-04T08:45:12.000Z | 2021-11-29T08:44:26.000Z | string/RunLength.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | string/RunLength.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | #pragma once
#include "../other/template.hpp"
template<class Cont, class Comp>
std::vector<std::pair<typename Cont::value_type, int>> RunLength(const Cont& str, const Comp& cmp) {
std::vector<std::pair<typename Cont::value_type, int>> res;
if (str.size() == 0) return res;
res.emplace_back(str[0], 1);
rep (i, 1, str.size()) {
if (cmp(res.back().first, str[i])) ++res.back().second;
else res.emplace_back(str[i], 1);
}
return res;
}
template<class Cont> std::vector<std::pair<typename Cont::value_type, int>> RunLength(const Cont& str) {
return RunLength(str, std::equal_to<typename Cont::value_type>());
}
/**
* @brief RunLength(ランレングス圧縮)
* @docs docs/RunLength.md
*/
| 28.8 | 104 | 0.647222 | [
"vector"
] |
f568252889aeeb34fd4d3a1464bf6a8f1a79b1d8 | 10,648 | cpp | C++ | Modules/ThirdParty/OssimPlugins/src/ossim/ossimTileMapModel.cpp | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | 1 | 2019-09-12T00:53:05.000Z | 2019-09-12T00:53:05.000Z | Modules/ThirdParty/OssimPlugins/src/ossim/ossimTileMapModel.cpp | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/OssimPlugins/src/ossim/ossimTileMapModel.cpp | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | 1 | 2020-10-15T09:37:30.000Z | 2020-10-15T09:37:30.000Z | /*
* Copyright (C) 2005-2019 by Centre National d'Etudes Spatiales (CNES)
*
* This file is licensed under MIT license:
*
* 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 "ossimTileMapModel.h"
#include <stdio.h>
#include <cstdlib>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
//***
// Define Trace flags for use within this file:
//***
#include <ossim/base/ossimTrace.h>
static ossimTrace traceExec ("ossimTileMapModel:exec");
static ossimTrace traceDebug ("ossimTileMapModel:debug");
namespace ossimplugins
{
RTTI_DEF1(ossimTileMapModel, "ossimTileMapModel", ossimSensorModel);
//*****************************************************************************
// DEFAULT CONSTRUCTOR: ossimTileMapModel()
//
//*****************************************************************************
ossimTileMapModel::ossimTileMapModel()
:
ossimSensorModel(),
qDepth (1)
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel: entering..." << std::endl;
// initAdjustableParameters();
// std::cout << "TileMapModel constructor" << std::endl;
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel: returning..." << std::endl;
}
bool ossimTileMapModel::open(const ossimFilename& file)
{
static const char MODULE[] = "ossimTileMapModel::open";
ossimString os = file.beforePos(4);
if (traceDebug())
{
CLOG << " Entered..." << std::endl
<< " trying to open file " << file << std::endl;
}
if(os == "http" || file.ext() == "otb")
{
return true;
}
return false;
}
//*****************************************************************************
// CONSTRUCTOR: ossimTileMapModel(kwl)
//
// Constructs model from keywordlist geometry file
//
//*****************************************************************************
ossimTileMapModel::ossimTileMapModel(const ossimKeywordlist& geom_kwl)
:
ossimSensorModel(),
qDepth (1)
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel(geom_kwl): entering..." << std::endl;
//***
// Parse keywordlist for geometry:
//***
loadState(geom_kwl);
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel(geom_kwl): Exited..." << std::endl;
}
//*****************************************************************************
// COPY CONSTRUCTOR:
//*****************************************************************************
ossimTileMapModel::ossimTileMapModel(const ossimTileMapModel& rhs)
:
ossimSensorModel (rhs),
qDepth (rhs.qDepth)
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel(rhs): entering..." << std::endl;
//initAdjustableParameters();
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::ossimTileMapModel(rhs): returning..." << std::endl;
}
//*****************************************************************************
// METHOD: ossimTileMapModel::lineSampleHeightToWorld()
//
// Performs the line/sample to groundpoint projection given an elevation.
//
//*****************************************************************************
void ossimTileMapModel::lineSampleToWorld(const ossimDpt& image_point,
ossimGpt& gpt) const
{
lineSampleHeightToWorld(image_point, 0.0, gpt);
}
void ossimTileMapModel::lineSampleHeightToWorld(const ossimDpt& image_point,
const double& /* height */,
ossimGpt& gpt) const
{
if(!image_point.hasNans())
{
gpt.lon = static_cast<double>(image_point.samp)/(1 << qDepth)/256 *360.0-180.0;
double y = static_cast<double>(image_point.line)/(1 << qDepth)/256;
double ex = exp(4*M_PI*(y-0.5));
gpt.lat = -180.0/M_PI*asin((ex-1)/(ex+1));
}
else
{
gpt.makeNan();
}
return;
}
void ossimTileMapModel::worldToLineSample(const ossimGpt& ground_point,
ossimDpt& img_pt) const
{
// if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::worldToLineSample(): entering..." << std::endl;
if(ground_point.isLatNan() || ground_point.isLonNan() )
{
img_pt.makeNan();
return;
}
double x = (180.0 + ground_point.lon) / 360.0;
double y = - ground_point.lat * M_PI / 180; // convert to radians
y = 0.5 * log((1+sin(y)) / (1 - sin(y)));
y *= 1.0/(2 * M_PI); // scale factor from radians to normalized
y += 0.5; // and make y range from 0 - 1
img_pt.samp = floor(x*pow(2.,static_cast<double>(qDepth))*256);
img_pt.line = floor(y*pow(2.,static_cast<double>(qDepth))*256);
return;
}
//*****************************************************************************
// METHOD: ossimTileMapModel::print()
//
// Formatted dump of data members.
//
//*****************************************************************************
std::ostream& ossimTileMapModel::print(std::ostream& os) const
{
os << "\nDump of ossimTileMapModel object at "
<< std::hex << this << ":\n"
<< "\nTileMapModel -- Dump of all data members: "
<< "\n theImageID: " << theImageID.chars()
<< "\n theImageSize: " << theImageSize
<< "\n theRefImgPt: " << theRefImgPt
<< "\n theRefGndPt: " << theRefGndPt
<< "\n theGSD.line: " << theGSD.line
<< "\n theGSD.samp: " << theGSD.samp
<< "\n qDepth: " << qDepth
<< std::endl;
return ossimSensorModel::print(os);
}
//*****************************************************************************
// METHOD: ossimTileMapModel::saveState()
//
// Saves the model state to the KWL. This KWL also serves as a geometry file.
//
//*****************************************************************************
bool ossimTileMapModel::saveState(ossimKeywordlist& kwl,
const char* prefix) const
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::saveState: entering..." << std::endl;
kwl.add(prefix, ossimKeywordNames::TYPE_KW, TYPE_NAME(this));
kwl.add(prefix, "depth", qDepth);
//***
// Hand off to base class for common stuff:
//***
ossimSensorModel::saveState(kwl, prefix);
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::saveState: returning..." << std::endl;
return true;
}
//*****************************************************************************
// METHOD: ossimTileMapModel::loadState()
//
// Restores the model's state from the KWL. This KWL also serves as a
// geometry file.
//
//*****************************************************************************
bool ossimTileMapModel::loadState(const ossimKeywordlist& kwl,
const char* prefix)
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::loadState: entering..." << std::endl;
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::loadState:"
<< "\nInput kwl: " << kwl
<< std::endl;
}
const char* value = NULL;
//const char* keyword =NULL;
bool success;
//***
// Assure this keywordlist contains correct type info:
//***
value = kwl.find(prefix, ossimKeywordNames::TYPE_KW);
if (!value || (strcmp(value, TYPE_NAME(this))))
{
theErrorStatus = 1;
return false;
}
value = kwl.find(prefix, "depth");
qDepth = atoi(value);
//***
// Pass on to the base-class for parsing first:
//***
success = ossimSensorModel::loadState(kwl, prefix);
if (!success)
{
theErrorStatus++;
return false;
}
updateModel();
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::loadState: returning..." << std::endl;
return true;
}
//*****************************************************************************
// STATIC METHOD: ossimTileMapModel::writeGeomTemplate
//
// Writes a sample kwl to output stream.
//
//*****************************************************************************
void ossimTileMapModel::writeGeomTemplate(std::ostream& os)
{
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::writeGeomTemplate: entering..." << std::endl;
os <<
"//**************************************************************\n"
"// Template for TileMap model keywordlist\n"
"//**************************************************************\n"
<< ossimKeywordNames::TYPE_KW << ": " << "ossimTileMapModel" << std::endl;
if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTileMapModel::writeGeomTemplate: returning..." << std::endl;
return;
}
} // End: namespace ossimplugins
| 35.493333 | 144 | 0.533809 | [
"geometry",
"object",
"model"
] |
f56c2441ebb637bc818e11794e4079f2b433640d | 7,800 | hpp | C++ | libmarch/include/march/mesh/ConservationElement/BasicCE.hpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 16 | 2015-12-09T02:54:42.000Z | 2021-04-20T11:26:39.000Z | libmarch/include/march/mesh/ConservationElement/BasicCE.hpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 95 | 2015-12-09T00:49:40.000Z | 2022-02-14T13:34:55.000Z | libmarch/include/march/mesh/ConservationElement/BasicCE.hpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 13 | 2015-05-08T04:16:42.000Z | 2021-01-15T09:28:06.000Z | #pragma once
/*
* Copyright (c) 2016, Yung-Yu Chen <yyc@solvcon.net>
* BSD 3-Clause License, see COPYING
*/
#include <array>
#include <string>
#include <ostream>
#include "march/core.hpp"
#include "march/mesh/UnstructuredBlock.hpp"
namespace march {
namespace detail {
/**
* Calculator of BasicCE.
*/
template< size_t NDIM >
struct BasicCECenterVolumeHelper {
typedef UnstructuredBlock<NDIM> block_type;
typedef Vector<NDIM> vector_type;
/**
* Read the input data from standard mesh.
*
* @param[in] block The block to load from.
* @param[in] icl The index of cell of interest.
* @param[in] ifl The index of face in the cell, 0-base.
*/
BasicCECenterVolumeHelper(const block_type & block, index_type icl, index_type ifl)
: tfcnds(block.fcnds()[block.clfcs()[icl][ifl+1]])
{
assert(ifl < block.clfcs()[icl][0]);
// cell and face centers.
index_type ifc = block.clfcs()[icl][ifl+1];
outward_face = block.fccls()[icl][0] == icl ? true : false;
crdi = block.clcnd()[icl];
crde = block.clcnd()[block.fcrcl(ifc, icl)];
if (3 == NDIM) fcnd = block.fccnd()[ifc];
// node coordinates.
index_type inf;
for (inf=0; inf<tfcnds[0]; ++inf) crd[inf] = block.ndcrd()[tfcnds[inf+1]];
if (3 == NDIM) crd[inf] = crd[0];
}
void calc_cnd_vol(vector_type & cnd, real_type & vol) const;
void calc_subface_cnd(std::array<vector_type, block_type::FCMND> & fccnd) const;
void calc_subface_nml(std::array<vector_type, block_type::FCMND> & fcnml) const;
const index_type (&tfcnds)[block_type::FCMND+1]; // "t" for "this".
bool outward_face; // true if the face normal of icl point outward.
vector_type crdi;
vector_type crde;
vector_type fcnd; // only valid in 3 dimensional.
vector_type crd[block_type::FCMND+1]; // only in 3 dimensional we need the last vector.
}; /* end struct BasicCECenterVolumeHelper */
template<>
inline void BasicCECenterVolumeHelper<3>::calc_cnd_vol(BasicCECenterVolumeHelper<3>::vector_type & cnd, real_type & vol) const {
vol = 0.0;
cnd = 0.0;
for (index_type inf=0; inf<tfcnds[0]; ++inf) {
vector_type tvec = crd[inf] + crd[inf+1] + fcnd;
// base triangle.
vector_type disu = crd[inf ] - fcnd;
vector_type disv = crd[inf+1] - fcnd;
vector_type dist = cross(disu, disv);
// inner tetrahedron.
vector_type disw = crdi - fcnd;
real_type voli = fabs(dist.dot(disw)) / 6;
vector_type cndi = (tvec + crdi) / 4;
// outer tetrahedron.
disw = crde - fcnd;
real_type vole = fabs(dist.dot(disw)) / 6;
vector_type cnde = (tvec + crde) / 4;
// accumulate volume and centroid for BCE.
vol += voli + vole;
cnd += cndi * voli + cnde * vole;
}
cnd /= vol;
}
template<>
inline void BasicCECenterVolumeHelper<2>::calc_cnd_vol(BasicCECenterVolumeHelper<2>::vector_type & cnd, real_type & vol) const {
// triangle formed by cell point and two face nodes.
vector_type cndi = (crd[0] + crd[1] + crdi) / 3;
real_type voli = fabs(cross(crd[0]-crdi, crd[1]-crdi)) / 2;
// triangle formed by neighbor cell point and two face nodes.
vector_type cnde = (crd[0] + crd[1] + crde) / 3;
real_type vole = fabs(cross(crd[0]-crde, crd[1]-crde)) / 2;
// volume of BCE (quadrilateral) formed by the two triangles.
vol = voli + vole;
// geometry center of each BCE for cell jcl.
cnd = (cndi * voli + cnde * vole) / vol;
}
template< size_t NDIM >
inline void BasicCECenterVolumeHelper<NDIM>::calc_subface_cnd(
std::array<BasicCECenterVolumeHelper<NDIM>::vector_type, BasicCECenterVolumeHelper<NDIM>::block_type::FCMND> & sfcnd
) const {
for (index_type inf=0; inf<tfcnds[0]; ++inf) {
sfcnd[inf] = crde;
for (index_type it=inf; it<inf+(NDIM-1); ++it) sfcnd[inf] += crd[it];
sfcnd[inf] /= NDIM;
}
}
template<>
inline void BasicCECenterVolumeHelper<3>::calc_subface_nml(
std::array<BasicCECenterVolumeHelper<3>::vector_type, BasicCECenterVolumeHelper<3>::block_type::FCMND> & sfnml
) const {
real_type voe = outward_face ? 0.5 : -0.5;
for (index_type inf=0; inf<tfcnds[0]; ++inf) {
vector_type disu = crd[inf ] - crde;
vector_type disv = crd[inf+1] - crde;
sfnml[inf] = cross(disu, disv) * voe;
}
}
template<>
inline void BasicCECenterVolumeHelper<2>::calc_subface_nml(
std::array<BasicCECenterVolumeHelper<2>::vector_type, BasicCECenterVolumeHelper<2>::block_type::FCMND> & sfnml
) const {
real_type voe = (crd[0][0]-crde[0])*(crd[1][1]-crde[1])
- (crd[0][1]-crde[1])*(crd[1][0]-crde[0]);
voe /= fabs(voe);
sfnml[0][0] = -(crde[1]-crd[0][1]) * voe;
sfnml[0][1] = (crde[0]-crd[0][0]) * voe;
sfnml[1][0] = (crde[1]-crd[1][1]) * voe;
sfnml[1][1] = -(crde[0]-crd[1][0]) * voe;
}
} /* end namespace detail */
/**
* Geometry data for a single basic conservation element (BCE).
*/
template< size_t NDIM >
struct BasicCE {
typedef UnstructuredBlock<NDIM> block_type;
typedef Vector<NDIM> vector_type;
vector_type cnd; // basic conservation element centroid.
real_type vol; // basic conservation element volume.
std::array<vector_type, block_type::FCMND> sfcnd; // sub-face centroids.
std::array<vector_type, block_type::FCMND> sfnml; // sub-face normal.
BasicCE() {
#ifdef MH_DEBUG
init_sentinel();
#endif // MH_DEBUG
}
BasicCE(const block_type & block, index_type icl, index_type ifl) {
#ifdef MH_DEBUG
init_sentinel();
#endif // MH_DEBUG
detail::BasicCECenterVolumeHelper<NDIM> helper(block, icl, ifl);
helper.calc_cnd_vol(cnd, vol);
helper.calc_subface_cnd(sfcnd);
helper.calc_subface_nml(sfnml);
}
BasicCE(const block_type & block, index_type icl, index_type ifl, bool init_sentinel) {
if (init_sentinel) { this->init_sentinel(); }
detail::BasicCECenterVolumeHelper<NDIM> helper(block, icl, ifl);
helper.calc_cnd_vol(cnd, vol);
helper.calc_subface_cnd(sfcnd);
helper.calc_subface_nml(sfnml);
}
void init_sentinel() {
cnd = MH_REAL_SENTINEL;
vol = MH_REAL_SENTINEL;
for (size_t isf=0; isf<block_type::FCMND; ++isf) {
sfcnd[isf] = MH_REAL_SENTINEL;
sfnml[isf] = MH_REAL_SENTINEL;
}
}
std::string repr(size_t indent=0, size_t precision=0) const;
}; /* end struct BasicCE */
template< size_t NDIM > std::string BasicCE<NDIM>::repr(size_t indent, size_t precision) const {
std::string ret(string::format("BasicCE%ldD(", NDIM));
const std::string indented_newline = string::create_indented_newline(indent);
if (indent) { ret += indented_newline; }
ret += "cnd=" + cnd.repr(indent, precision) + ",";
ret += indent ? indented_newline : std::string(" ");
ret += "vol=" + string::from_double(vol, precision);
for (size_t isf=0; isf<block_type::FCMND; ++isf) {
ret += ",";
ret += indent ? indented_newline : std::string(" ");
ret += string::format("sfcnd[%d]=", isf) + sfcnd[isf].repr(indent, precision);
}
for (size_t isf=0; isf<block_type::FCMND; ++isf) {
ret += ",";
ret += indent ? indented_newline : std::string(" ");
ret += string::format("sfnml[%d]=", isf) + sfnml[isf].repr(indent, precision);
}
if (indent) { ret += "\n)"; }
else { ret += ")"; }
return ret;
}
} /* end namespace march */
template< size_t NDIM >
std::ostream& operator<< (
std::ostream& stream, const march::BasicCE<NDIM> & bce
) {
stream << bce.repr();
return stream;
}
// vim: set ff=unix fenc=utf8 nobomb et sw=4 ts=4:
| 35.454545 | 128 | 0.626923 | [
"mesh",
"geometry",
"vector"
] |
f56e86eb4948f0be4df52368082813d95a7a32ba | 3,108 | hxx | C++ | app/src/main/jni/OcctJni_Viewer.hxx | Open-Cascade-SAS/OCCT-samples-kotlin | 8fd4d8a35d696e0ad46961d9e619fb1eaef092c5 | [
"MIT"
] | null | null | null | app/src/main/jni/OcctJni_Viewer.hxx | Open-Cascade-SAS/OCCT-samples-kotlin | 8fd4d8a35d696e0ad46961d9e619fb1eaef092c5 | [
"MIT"
] | null | null | null | app/src/main/jni/OcctJni_Viewer.hxx | Open-Cascade-SAS/OCCT-samples-kotlin | 8fd4d8a35d696e0ad46961d9e619fb1eaef092c5 | [
"MIT"
] | null | null | null | // Copyright (c) 2014-2021 OPEN CASCADE SAS
//
// This file is part of the examples of the Open CASCADE Technology software library.
//
// 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 <AIS_InteractiveContext.hxx>
#include <AIS_ViewController.hxx>
#include <TopoDS_Shape.hxx>
#include <V3d_Viewer.hxx>
#include <V3d_View.hxx>
class AIS_ViewCube;
//! Main C++ back-end for activity.
class OcctJni_Viewer : public AIS_ViewController
{
public:
//! Empty constructor
OcctJni_Viewer (float theDispDensity);
//! Initialize the viewer
bool init();
//! Release the viewer
void release();
//! Resize the viewer
void resize (int theWidth,
int theHeight);
//! Open CAD file
bool open (const TCollection_AsciiString& thePath);
//! Take snapshot
bool saveSnapshot (const TCollection_AsciiString& thePath,
int theWidth = 0,
int theHeight = 0);
//! Viewer update.
//! Returns TRUE if more frames should be requested.
bool redraw();
//! Move camera
void setProj (V3d_TypeOfOrientation theProj)
{
if (myView.IsNull())
{
return;
}
myView->SetProj (theProj);
myView->Invalidate();
}
//! Fit All.
void fitAll();
protected:
//! Reset viewer content.
void initContent();
//! Print information about OpenGL ES context.
void dumpGlInfo (bool theIsBasic);
//! Handle redraw.
virtual void handleViewRedraw (const Handle(AIS_InteractiveContext)& theCtx,
const Handle(V3d_View)& theView) override;
protected:
Handle(V3d_Viewer) myViewer;
Handle(V3d_View) myView;
Handle(AIS_InteractiveContext) myContext;
Handle(Prs3d_TextAspect) myTextStyle; //!< text style for OSD elements
Handle(AIS_ViewCube) myViewCube; //!< view cube object
TopoDS_Shape myShape;
float myDevicePixelRatio; //!< device pixel ratio for handling high DPI displays
bool myIsJniMoreFrames; //!< need more frame flag
};
| 31.08 | 107 | 0.688224 | [
"cad",
"object"
] |
f56fd8788bde6625ead088e692088e2286fc0949 | 17,679 | cpp | C++ | Dev/SourcesEngine/Gugu/Resources/ParticleEffect.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | Dev/SourcesEngine/Gugu/Resources/ParticleEffect.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | Dev/SourcesEngine/Gugu/Resources/ParticleEffect.cpp | Legulysse/guguEngine | 889ba87f219d476169fab1072f3af1428df62d49 | [
"Zlib"
] | null | null | null | ////////////////////////////////////////////////////////////////
// Header
#include "Gugu/Common.h"
#include "Gugu/Resources/ParticleEffect.h"
////////////////////////////////////////////////////////////////
// Includes
#include "Gugu/External/PugiXmlWrap.h"
////////////////////////////////////////////////////////////////
// File Implementation
namespace gugu {
ParticleEffect::ParticleEffect()
{
}
ParticleEffect::~ParticleEffect()
{
Unload();
}
EResourceType::Type ParticleEffect::GetResourceType() const
{
return EResourceType::ParticleEffect;
}
ParticleSystemSettings* ParticleEffect::GetParticleSettings()
{
return &m_particleSettings;
}
void ParticleEffect::Unload()
{
}
bool ParticleEffect::LoadFromXml(const pugi::xml_document& document)
{
pugi::xml_node nodeParticleEffect = document.child("ParticleEffect");
if (!nodeParticleEffect)
return false;
Unload();
static const std::map<ParticleSystemSettings::EParticleShape, std::string> particleShapeEnumToString = {
{ ParticleSystemSettings::EParticleShape::Point, "Point" },
{ ParticleSystemSettings::EParticleShape::Quad, "Quad" },
};
static const std::map<ParticleSystemSettings::EEmitterShape, std::string> emitterShapeEnumToString = {
{ ParticleSystemSettings::EEmitterShape::Point, "Point" },
{ ParticleSystemSettings::EEmitterShape::Circle, "Circle" },
{ ParticleSystemSettings::EEmitterShape::Annulus, "Annulus" },
};
static const std::map<ParticleSystemSettings::EEmissionBehaviour, std::string> emissionBehaviourEnumToString = {
{ ParticleSystemSettings::EEmissionBehaviour::RandomDirection, "RandomDirection" },
{ ParticleSystemSettings::EEmissionBehaviour::AngleDirection, "AngleDirection" },
{ ParticleSystemSettings::EEmissionBehaviour::AwayFromCenter, "AwayFromCenter" },
};
static const std::map<std::string, ParticleSystemSettings::EParticleShape> particleShapeStringToEnum = {
{ "Point", ParticleSystemSettings::EParticleShape::Point },
{ "Quad", ParticleSystemSettings::EParticleShape::Quad },
};
static const std::map<std::string, ParticleSystemSettings::EEmitterShape> emitterShapeStringToEnum = {
{ "Point", ParticleSystemSettings::EEmitterShape::Point },
{ "Circle", ParticleSystemSettings::EEmitterShape::Circle },
{ "Annulus", ParticleSystemSettings::EEmitterShape::Annulus },
};
static const std::map<std::string, ParticleSystemSettings::EEmissionBehaviour> emissionBehaviourStringToEnum = {
{ "RandomDirection", ParticleSystemSettings::EEmissionBehaviour::RandomDirection },
{ "AngleDirection", ParticleSystemSettings::EEmissionBehaviour::AngleDirection },
{ "AwayFromCenter", ParticleSystemSettings::EEmissionBehaviour::AwayFromCenter },
};
std::string particleShapeValue = particleShapeEnumToString.at(m_particleSettings.particleShape);
std::string emitterShapeValue = emitterShapeEnumToString.at(m_particleSettings.emitterShape);
std::string emissionBehaviourValue = emissionBehaviourEnumToString.at(m_particleSettings.emissionBehaviour);
// Setup
m_particleSettings.loop = nodeParticleEffect.child("Loop").attribute("value").as_bool(m_particleSettings.loop);
m_particleSettings.duration = nodeParticleEffect.child("Duration").attribute("value").as_int(m_particleSettings.duration);
m_particleSettings.maxParticleCount = nodeParticleEffect.child("MaxParticleCount").attribute("value").as_int(m_particleSettings.maxParticleCount);
particleShapeValue = nodeParticleEffect.child("ParticleShape").attribute("value").as_string(particleShapeValue.c_str());
m_particleSettings.useSortBuffer = nodeParticleEffect.child("SortBuffer").attribute("value").as_bool(m_particleSettings.useSortBuffer);
m_particleSettings.localSpace = nodeParticleEffect.child("LocalSpace").attribute("value").as_bool(m_particleSettings.localSpace);
// Emitter Shape
emitterShapeValue = nodeParticleEffect.child("EmitterShape").attribute("value").as_string(emitterShapeValue.c_str());
m_particleSettings.emitterRadius = nodeParticleEffect.child("EmitterRadius").attribute("value").as_float(m_particleSettings.emitterRadius);
m_particleSettings.emitterInnerRadius = nodeParticleEffect.child("EmitterInnerRadius").attribute("value").as_float(m_particleSettings.emitterInnerRadius);
// Particle Spawn
pugi::xml_node nodeSpawnPerSecond = nodeParticleEffect.child("SpawnPerSecond");
m_particleSettings.useRandomSpawnPerSecond = nodeSpawnPerSecond.attribute("random").as_bool(m_particleSettings.useRandomSpawnPerSecond);
m_particleSettings.minSpawnPerSecond = nodeSpawnPerSecond.attribute("min").as_float(m_particleSettings.minSpawnPerSecond);
m_particleSettings.maxSpawnPerSecond = nodeSpawnPerSecond.attribute("max").as_float(m_particleSettings.maxSpawnPerSecond);
pugi::xml_node nodeParticlesPerSpawn = nodeParticleEffect.child("ParticlesPerSpawn");
m_particleSettings.useRandomParticlesPerSpawn = nodeParticlesPerSpawn.attribute("random").as_bool(m_particleSettings.useRandomParticlesPerSpawn);
m_particleSettings.minParticlesPerSpawn = nodeParticlesPerSpawn.attribute("min").as_int(m_particleSettings.minParticlesPerSpawn);
m_particleSettings.maxParticlesPerSpawn = nodeParticlesPerSpawn.attribute("max").as_int(m_particleSettings.maxParticlesPerSpawn);
// Particle behaviour
emissionBehaviourValue = nodeParticleEffect.child("EmissionBehaviour").attribute("value").as_string(emissionBehaviourValue.c_str());
pugi::xml_node nodeEmissionDirection = nodeParticleEffect.child("EmissionDirection");
m_particleSettings.emissionDirection.x = nodeEmissionDirection.attribute("x").as_float(m_particleSettings.emissionDirection.x);
m_particleSettings.emissionDirection.y = nodeEmissionDirection.attribute("y").as_float(m_particleSettings.emissionDirection.y);
m_particleSettings.emissionAngle = nodeParticleEffect.child("EmissionAngle").attribute("value").as_float(m_particleSettings.emissionAngle);
pugi::xml_node nodeLifetime = nodeParticleEffect.child("Lifetime");
m_particleSettings.useRandomLifetime = nodeLifetime.attribute("random").as_bool(m_particleSettings.useRandomLifetime);
m_particleSettings.minLifetime = nodeLifetime.attribute("min").as_int(m_particleSettings.minLifetime);
m_particleSettings.maxLifetime = nodeLifetime.attribute("max").as_int(m_particleSettings.maxLifetime);
pugi::xml_node nodeVelocity = nodeParticleEffect.child("Velocity");
m_particleSettings.useRandomVelocity = nodeVelocity.attribute("random").as_bool(m_particleSettings.useRandomVelocity);
m_particleSettings.minVelocity = nodeVelocity.attribute("min").as_float(m_particleSettings.minVelocity);
m_particleSettings.maxVelocity = nodeVelocity.attribute("max").as_float(m_particleSettings.maxVelocity);
// Render
m_particleSettings.keepSizeRatio = nodeParticleEffect.child("KeepSizeRatio").attribute("value").as_bool(m_particleSettings.keepSizeRatio);
pugi::xml_node nodeStartSize = nodeParticleEffect.child("StartSize");
m_particleSettings.useRandomStartSize = nodeStartSize.attribute("random").as_bool(m_particleSettings.useRandomStartSize);
m_particleSettings.minStartSize.x = nodeStartSize.attribute("min_x").as_float(m_particleSettings.minStartSize.x);
m_particleSettings.minStartSize.y = nodeStartSize.attribute("min_y").as_float(m_particleSettings.minStartSize.y);
m_particleSettings.maxStartSize.x = nodeStartSize.attribute("max_x").as_float(m_particleSettings.maxStartSize.x);
m_particleSettings.maxStartSize.y = nodeStartSize.attribute("max_y").as_float(m_particleSettings.maxStartSize.y);
m_particleSettings.updateSizeOverLifetime = nodeParticleEffect.child("UpdateSizeOverLifetime").attribute("value").as_bool(m_particleSettings.updateSizeOverLifetime);
pugi::xml_node nodeEndSize = nodeParticleEffect.child("EndSize");
m_particleSettings.useRandomEndSize = nodeEndSize.attribute("random").as_bool(m_particleSettings.useRandomEndSize);
m_particleSettings.minEndSize.x = nodeEndSize.attribute("min_x").as_float(m_particleSettings.minEndSize.x);
m_particleSettings.minEndSize.y = nodeEndSize.attribute("min_y").as_float(m_particleSettings.minEndSize.y);
m_particleSettings.maxEndSize.x = nodeEndSize.attribute("max_x").as_float(m_particleSettings.maxEndSize.x);
m_particleSettings.maxEndSize.y = nodeEndSize.attribute("max_y").as_float(m_particleSettings.maxEndSize.y);
m_particleSettings.updateColorOverLifetime = nodeParticleEffect.child("UpdateColorOverLifetime").attribute("value").as_bool(m_particleSettings.updateColorOverLifetime);
pugi::xml_node nodeStartColor = nodeParticleEffect.child("StartColor");
m_particleSettings.startColor.r = (sf::Uint8)nodeStartColor.attribute("r").as_uint(m_particleSettings.startColor.r);
m_particleSettings.startColor.g = (sf::Uint8)nodeStartColor.attribute("g").as_uint(m_particleSettings.startColor.g);
m_particleSettings.startColor.b = (sf::Uint8)nodeStartColor.attribute("b").as_uint(m_particleSettings.startColor.b);
m_particleSettings.startColor.a = (sf::Uint8)nodeStartColor.attribute("a").as_uint(m_particleSettings.startColor.a);
pugi::xml_node nodeEndColor = nodeParticleEffect.child("EndColor");
m_particleSettings.endColor.r = (sf::Uint8)nodeEndColor.attribute("r").as_uint(m_particleSettings.endColor.r);
m_particleSettings.endColor.g = (sf::Uint8)nodeEndColor.attribute("g").as_uint(m_particleSettings.endColor.g);
m_particleSettings.endColor.b = (sf::Uint8)nodeEndColor.attribute("b").as_uint(m_particleSettings.endColor.b);
m_particleSettings.endColor.a = (sf::Uint8)nodeEndColor.attribute("a").as_uint(m_particleSettings.endColor.a);
m_particleSettings.imageSetID = nodeParticleEffect.child("ImageSetID").attribute("value").as_string(m_particleSettings.imageSetID.c_str());
// Finalize
m_particleSettings.particleShape = particleShapeStringToEnum.at(particleShapeValue);
m_particleSettings.emitterShape = emitterShapeStringToEnum.at(emitterShapeValue);
m_particleSettings.emissionBehaviour = emissionBehaviourStringToEnum.at(emissionBehaviourValue);
return true;
}
bool ParticleEffect::SaveToXml(pugi::xml_document& document) const
{
pugi::xml_node nodeParticleEffect = document.append_child("ParticleEffect");
static const std::map<ParticleSystemSettings::EParticleShape, std::string> particleShapeEnumToString = {
{ ParticleSystemSettings::EParticleShape::Point, "Point" },
{ ParticleSystemSettings::EParticleShape::Quad, "Quad" },
};
static const std::map<ParticleSystemSettings::EEmitterShape, std::string> emitterShapeEnumToString = {
{ ParticleSystemSettings::EEmitterShape::Point, "Point" },
{ ParticleSystemSettings::EEmitterShape::Circle, "Circle" },
{ ParticleSystemSettings::EEmitterShape::Annulus, "Annulus" },
};
static const std::map<ParticleSystemSettings::EEmissionBehaviour, std::string> emissionBehaviourEnumToString = {
{ ParticleSystemSettings::EEmissionBehaviour::RandomDirection, "RandomDirection" },
{ ParticleSystemSettings::EEmissionBehaviour::AngleDirection, "AngleDirection" },
{ ParticleSystemSettings::EEmissionBehaviour::AwayFromCenter, "AwayFromCenter" },
};
std::string particleShapeValue = particleShapeEnumToString.at(m_particleSettings.particleShape);
std::string emitterShapeValue = emitterShapeEnumToString.at(m_particleSettings.emitterShape);
std::string emissionBehaviourValue = emissionBehaviourEnumToString.at(m_particleSettings.emissionBehaviour);
// Setup
nodeParticleEffect.append_child("Loop").append_attribute("value").set_value(m_particleSettings.loop);
nodeParticleEffect.append_child("Duration").append_attribute("value").set_value(m_particleSettings.duration);
nodeParticleEffect.append_child("MaxParticleCount").append_attribute("value").set_value(m_particleSettings.maxParticleCount);
nodeParticleEffect.append_child("ParticleShape").append_attribute("value").set_value(particleShapeValue.c_str());
nodeParticleEffect.append_child("SortBuffer").append_attribute("value").set_value(m_particleSettings.useSortBuffer);
nodeParticleEffect.append_child("LocalSpace").append_attribute("value").set_value(m_particleSettings.localSpace);
// Emitter Shape
nodeParticleEffect.append_child("EmitterShape").append_attribute("value").set_value(emitterShapeValue.c_str());
nodeParticleEffect.append_child("EmitterRadius").append_attribute("value").set_value(m_particleSettings.emitterRadius);
nodeParticleEffect.append_child("EmitterInnerRadius").append_attribute("value").set_value(m_particleSettings.emitterInnerRadius);
// Particle Spawn
pugi::xml_node nodeSpawnPerSecond = nodeParticleEffect.append_child("SpawnPerSecond");
nodeSpawnPerSecond.append_attribute("random").set_value(m_particleSettings.useRandomSpawnPerSecond);
nodeSpawnPerSecond.append_attribute("min").set_value(m_particleSettings.minSpawnPerSecond);
nodeSpawnPerSecond.append_attribute("max").set_value(m_particleSettings.maxSpawnPerSecond);
pugi::xml_node nodeParticlesPerSpawn = nodeParticleEffect.append_child("ParticlesPerSpawn");
nodeParticlesPerSpawn.append_attribute("random").set_value(m_particleSettings.useRandomParticlesPerSpawn);
nodeParticlesPerSpawn.append_attribute("min").set_value(m_particleSettings.minParticlesPerSpawn);
nodeParticlesPerSpawn.append_attribute("max").set_value(m_particleSettings.maxParticlesPerSpawn);
// Particle behaviour
nodeParticleEffect.append_child("EmissionBehaviour").append_attribute("value").set_value(emissionBehaviourValue.c_str());
pugi::xml_node nodeEmissionDirection = nodeParticleEffect.append_child("EmissionDirection");
nodeEmissionDirection.append_attribute("x").set_value(m_particleSettings.emissionDirection.x);
nodeEmissionDirection.append_attribute("y").set_value(m_particleSettings.emissionDirection.y);
nodeParticleEffect.append_child("EmissionAngle").append_attribute("value").set_value(m_particleSettings.emissionAngle);
pugi::xml_node nodeLifetime = nodeParticleEffect.append_child("Lifetime");
nodeLifetime.append_attribute("random").set_value(m_particleSettings.useRandomLifetime);
nodeLifetime.append_attribute("min").set_value(m_particleSettings.minLifetime);
nodeLifetime.append_attribute("max").set_value(m_particleSettings.maxLifetime);
pugi::xml_node nodeVelocity = nodeParticleEffect.append_child("Velocity");
nodeVelocity.append_attribute("random").set_value(m_particleSettings.useRandomVelocity);
nodeVelocity.append_attribute("min").set_value(m_particleSettings.minVelocity);
nodeVelocity.append_attribute("max").set_value(m_particleSettings.maxVelocity);
// Render
nodeParticleEffect.append_child("KeepSizeRatio").append_attribute("value").set_value(m_particleSettings.keepSizeRatio);
pugi::xml_node nodeStartSize = nodeParticleEffect.append_child("StartSize");
nodeStartSize.append_attribute("random").set_value(m_particleSettings.useRandomStartSize);
nodeStartSize.append_attribute("min_x").set_value(m_particleSettings.minStartSize.x);
nodeStartSize.append_attribute("min_y").set_value(m_particleSettings.minStartSize.y);
nodeStartSize.append_attribute("max_x").set_value(m_particleSettings.maxStartSize.x);
nodeStartSize.append_attribute("max_y").set_value(m_particleSettings.maxStartSize.y);
nodeParticleEffect.append_child("UpdateSizeOverLifetime").append_attribute("value").set_value(m_particleSettings.updateSizeOverLifetime);
pugi::xml_node nodeEndSize = nodeParticleEffect.append_child("EndSize");
nodeEndSize.append_attribute("random").set_value(m_particleSettings.useRandomEndSize);
nodeEndSize.append_attribute("min_x").set_value(m_particleSettings.minEndSize.x);
nodeEndSize.append_attribute("min_y").set_value(m_particleSettings.minEndSize.y);
nodeEndSize.append_attribute("max_x").set_value(m_particleSettings.maxEndSize.x);
nodeEndSize.append_attribute("max_y").set_value(m_particleSettings.maxEndSize.y);
nodeParticleEffect.append_child("UpdateColorOverLifetime").append_attribute("value").set_value(m_particleSettings.updateColorOverLifetime);
pugi::xml_node nodeStartColor = nodeParticleEffect.append_child("StartColor");
nodeStartColor.append_attribute("r").set_value(m_particleSettings.startColor.r);
nodeStartColor.append_attribute("g").set_value(m_particleSettings.startColor.g);
nodeStartColor.append_attribute("b").set_value(m_particleSettings.startColor.b);
nodeStartColor.append_attribute("a").set_value(m_particleSettings.startColor.a);
pugi::xml_node nodeEndColor = nodeParticleEffect.append_child("EndColor");
nodeEndColor.append_attribute("r").set_value(m_particleSettings.endColor.r);
nodeEndColor.append_attribute("g").set_value(m_particleSettings.endColor.g);
nodeEndColor.append_attribute("b").set_value(m_particleSettings.endColor.b);
nodeEndColor.append_attribute("a").set_value(m_particleSettings.endColor.a);
nodeParticleEffect.append_child("ImageSetID").append_attribute("value").set_value(m_particleSettings.imageSetID.c_str());
return true;
}
} // namespace gugu
| 63.365591 | 173 | 0.776571 | [
"render",
"shape"
] |
f5702cbc6910046234b4585e8fb48aaab84f6898 | 11,089 | cpp | C++ | src/common/plugin/fulltext/test/FulltextPluginTest.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | src/common/plugin/fulltext/test/FulltextPluginTest.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | src/common/plugin/fulltext/test/FulltextPluginTest.cpp | linkensphere201/nebula-common-personal | e31b7e88326195a08ac0460fd469326455df6417 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include <gtest/gtest.h>
#include "common/base/Base.h"
#include "common/encryption/MD5Utils.h"
#include "common/network/NetworkUtils.h"
#include "common/plugin/fulltext/FTUtils.h"
#include "common/plugin/fulltext/elasticsearch/ESStorageAdapter.h"
#include "common/plugin/fulltext/elasticsearch/ESGraphAdapter.h"
namespace nebula {
namespace plugin {
void verifyBodyStr(const std::string& actual, const folly::dynamic& expect) {
ASSERT_EQ(" -d'", actual.substr(0, 4));
ASSERT_EQ("'", actual.substr(actual.size() - 1, 1));
auto body = folly::parseJson(actual.substr(4, actual.size() - 5));
ASSERT_EQ(expect, body);
}
void verifyBodyStr(const std::string& actual, const std::vector<folly::dynamic>& expect) {
std::vector<std::string> lines;
folly::split("\n", actual, lines, true);
if (lines.size() > 0) {
ASSERT_LE(2, lines.size());
ASSERT_EQ("'", lines[lines.size() - 1]);
for (size_t i = 1; i < lines.size() - 1; i++) {
auto body = folly::parseJson(lines[i]);
ASSERT_EQ(expect[i - 1], body);
}
}
}
TEST(FulltextPluginTest, ESIndexCheckTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient client(localHost_);
auto ret = ESGraphAdapter().indexExistsCmd(client, "test_index");
auto expected = "/usr/bin/curl -H \"Content-Type: application/json; charset=utf-8\" "
"-XGET \"http://127.0.0.1:9200/_cat/indices/test_index?format=json\"";
ASSERT_EQ(expected, ret);
}
TEST(FulltextPluginTest, ESCreateIndexTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient client(localHost_);
auto ret = ESGraphAdapter().createIndexCmd(client, "test_index");
auto expected = "/usr/bin/curl -H \"Content-Type: application/json; charset=utf-8\" "
"-XPUT \"http://127.0.0.1:9200/test_index\"";
ASSERT_EQ(expected, ret);
}
TEST(FulltextPluginTest, ESDropIndexTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient client(localHost_);
auto ret = ESGraphAdapter().dropIndexCmd(client, "test_index");
auto expected = "/usr/bin/curl -H \"Content-Type: application/json; charset=utf-8\" "
"-XDELETE \"http://127.0.0.1:9200/test_index\"";
ASSERT_EQ(expected, ret);
}
TEST(FulltextPluginTest, ESPutTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient hc(localHost_);
DocItem item("index1", "col1", 1, 2, "aaaa");
auto header = ESStorageAdapter().putHeader(hc, item);
std::string expected = "/usr/bin/curl -H \"Content-Type: application/json; charset=utf-8\" "
"-XPUT \"http://127.0.0.1:9200/index1/_doc/"
"000000000100000000028c43de7b01bca674276c43e09b3ec5baYWFhYQ==\"";
ASSERT_EQ(expected, header);
auto body = ESStorageAdapter().putBody(item);
folly::dynamic d = folly::dynamic::object("schema_id", item.schema)
("column_id", DocIDTraits::column(item.column))
("value", DocIDTraits::val(item.val));
verifyBodyStr(std::move(body), std::move(d));
}
TEST(FulltextPluginTest, ESBulkTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient hc(localHost_);
DocItem item1("index1", "col1", 1, 2, "aaaa");
DocItem item2("index1", "col1", 1, 2, "bbbb");
std::set<std::string> strs;
strs.emplace("aaa");
strs.emplace("bbb");
std::vector<DocItem> items;
items.emplace_back(DocItem("index1", "col1", 1, 2, "aaaa"));
items.emplace_back(DocItem("index1", "col1", 1, 2, "bbbb"));
auto header = ESStorageAdapter().bulkHeader(hc);
std::string expected = "/usr/bin/curl -H \"Content-Type: application/x-ndjson; "
"charset=utf-8\" -XPOST \"http://127.0.0.1:9200/_bulk\"";
ASSERT_EQ(expected, header);
std::vector<folly::dynamic> bodys;
for (const auto& item : items) {
folly::dynamic meta = folly::dynamic::object("_id", DocIDTraits::docId(item))
("_index", item.index);
folly::dynamic data = folly::dynamic::object("value", DocIDTraits::val(item.val))
("schema_id", item.schema)
("column_id", DocIDTraits::column(item.column));
bodys.emplace_back(folly::dynamic::object("index", std::move(meta)));
bodys.emplace_back(std::move(data));
}
auto body = ESStorageAdapter().bulkBody(items);
verifyBodyStr(body, std::move(bodys));
}
TEST(FulltextPluginTest, ESPutToTest) {
HostAddr localHost_{"127.0.0.1", 11111};
HttpClient hc(localHost_);
DocItem item1("index1", "col1", 1, 2, "aaaa");
// A ElasticSearch instance needs to be turn on at here, so expected false.
auto ret = ESStorageAdapter::kAdapter->put(hc, item1);
ASSERT_FALSE(ret);
}
TEST(FulltextPluginTest, ESResultTest) {
// {
// "took": 2,
// "timed_out": false,
// "_shards": {
// "total": 1,
// "successful": 1,
// "skipped": 0,
// "failed": 0
// },
// "hits": {
// "total": {
// "value": 1,
// "relation": "eq"
// },
// "max_score": 3.3862944,
// "hits": [
// {
// "_index": "my_temp_index_3",
// "_type": "_doc",
// "_id": "part1_tag1_col1_aaa",
// "_score": 3.3862944,
// "_source": {
// "value": "aaa"
// }
// },
// {
// "_index": "my_temp_index_3",
// "_type": "_doc",
// "_id": "part2_tag2_col1_bbb",
// "_score": 1.0,
// "_source": {
// "value": "bbb"
// }
// }
// ]
// }
// }
{
std::string json = R"({"took": 2,"timed_out": false,"_shards": {"total": 1,"successful": 1,
"skipped": 0,"failed": 0},"hits": {"total": {"value": 1,"relation":
"eq"},"max_score": 3.3862944,"hits": [{"_index": "my_temp_index_3",
"_type": "_doc","_id": "part1_tag1_col1_aaa","_score": 3.3862944,
"_source": {"value": "aaa"}},{"_index": "my_temp_index_3","_type":
"_doc","_id": "part2_tag2_col1_bbb","_score": 1.0,
"_source": {"value": "bbb"}}]}})";
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient hc(localHost_);
std::vector<std::string> rows;
auto ret = ESGraphAdapter().result(json, rows);
ASSERT_TRUE(ret);
std::vector<std::string> expect = {"aaa", "bbb"};
ASSERT_EQ(expect, rows);
}
// {
// "took": 1,
// "timed_out": false,
// "_shards": {
// "total": 1,
// "successful": 1,
// "skipped": 0,
// "failed": 0
// },
// "hits": {
// "total": {
// "value": 0,
// "relation": "eq"
// },
// "max_score": null,
// "hits": []
// }
// }
{
std::string json = R"({"took": 1,"timed_out": false,"_shards": {"total": 1,"successful": 1,
"skipped": 0,"failed": 0},"hits": {"total":
{"value": 0,"relation": "eq"},"max_score": null,"hits": []}})";
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient hc(localHost_);
std::vector<std::string> rows;
auto ret = ESGraphAdapter().result(json, rows);
ASSERT_TRUE(ret);
ASSERT_EQ(0, rows.size());
}
// {
// "error": {
// "root_cause": [
// {
// "type": "parsing_exception",
// "reason": "Unknown key for a VALUE_STRING in [_soure].",
// "line": 1,
// "col": 128
// }
// ],
// "type": "parsing_exception",
// "reason": "Unknown key for a VALUE_STRING in [_soure].",
// "line": 1,
// "col": 128
// },
// "status": 400
// }
{
std::string json = R"({"error": {"root_cause": [{"type": "parsing_exception","reason":
"Unknown key for a VALUE_STRING in [_soure].","line": 1,"col": 128}],
"type": "parsing_exception","reason": "Unknown key for a VALUE_STRING
in [_soure].","line": 1,"col": 128},"status": 400})";
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient hc(localHost_);
std::vector<std::string> rows;
auto ret = ESGraphAdapter().result(json, rows);
ASSERT_FALSE(ret);
}
}
// TODO: The json string is not comparable.
TEST(FulltextPluginTest, ESPrefixTest) {
HostAddr localHost_{"127.0.0.1", 9200};
HttpClient client(localHost_);
DocItem item("index1", "col1", 1, 2, "aa");
LimitItem limit(10, 100);
auto header = ESGraphAdapter().header(client, item, limit);
std::string expected = "/usr/bin/curl -H \"Content-Type: application/json; charset=utf-8\" "
"-XGET \"http://127.0.0.1:9200/index1/_search?timeout=10ms\"";
ASSERT_EQ(expected, header);
auto body = ESGraphAdapter().prefixBody("aa");
ASSERT_EQ("{\"prefix\":{\"value\":\"aa\"}}", folly::toJson(body));
}
TEST(FulltextPluginTest, ESWildcardTest) {
auto body = ESGraphAdapter().wildcardBody("a?a");
ASSERT_EQ("{\"wildcard\":{\"value\":\"a?a\"}}", folly::toJson(body));
}
TEST(FulltextPluginTest, ESRegexpTest) {
auto body = ESGraphAdapter().regexpBody("+a");
ASSERT_EQ("{\"regexp\":{\"value\":\"+a\"}}", folly::toJson(body));
}
TEST(FulltextPluginTest, ESFuzzyTest) {
auto body = ESGraphAdapter().fuzzyBody("+a", "AUTO", "OR");
auto expected = "{\"match\":{\"value\":{\"operator\":\"OR\","
"\"query\":\"+a\",\"fuzziness\":\"AUTO\"}}}";
ASSERT_EQ(folly::parseJson(expected), body);
}
} // namespace plugin
} // namespace nebula
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
folly::init(&argc, &argv, true);
google::SetStderrLogging(google::INFO);
return RUN_ALL_TESTS();
}
| 39.603571 | 100 | 0.511588 | [
"object",
"vector"
] |
f5719f26bc5e30726c8ef7f9038f2ab81a8a2d57 | 34,184 | cpp | C++ | src/coherence/util/SafeHashMap.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/util/SafeHashMap.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/util/SafeHashMap.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "coherence/util/SafeHashMap.hpp"
#include "coherence/util/Collections.hpp"
#include "coherence/util/ConcurrentModificationException.hpp"
#include "private/coherence/lang/AssociativeArray.hpp"
#include "private/coherence/util/logging/Logger.hpp"
#include <algorithm>
COH_OPEN_NAMESPACE2(coherence,util)
COH_REGISTER_TYPED_CLASS(SafeHashMap);
// ----- file local helpers -------------------------------------------------
namespace
{
/**
* Return a singleton empty array used to indicate that the SHM is resizing
*/
ObjectArray::Handle getNoEntriesArray()
{
static FinalHandle<ObjectArray> h(System::common(),
ObjectArray::create(0));
return h;
}
COH_STATIC_INIT(getNoEntriesArray());
/**
* Return a singleton empty array used to indicate that the SHM is no
* longer valid. This is used by LocalNamedCache::release/destroy.
*
* Note this marker array cannot reuse the NoEntriesArray.
*/
ObjectArray::Handle getInvalidArray()
{
// mf 2015.02.26: Work around for aparent VisualStudio bug.
// Debug x86 VisualStudio 2013 build running functional tests with the "alloc" heap analyzer enabled
// segfaults here when the "standard" one line form i.e.
// static FinalHandle<ObjectArray> h(System::common(), ObjectArray::create(0));
// is used. This occurs during static initialization and "h" is left in a zeroed out state and
// returning "h" naturally triggers a segfault because it doesn't contain a guardian monitor.
// This appears to be a compiler bug as breaking it up as follows resolves the issue.
static Object& monitor = System::common();
static ObjectArray::Handle hao = ObjectArray::create(0);
static FinalHandle<ObjectArray> h(monitor, hao);
return h;
}
COH_STATIC_INIT(getInvalidArray());
}
COH_EXPORT_SPEC_MEMBER(const size32_t SafeHashMap::default_initialsize)
COH_EXPORT_SPEC_MEMBER(const size32_t SafeHashMap::biggest_modulo)
// ----- constructors -------------------------------------------------------
SafeHashMap::SafeHashMap(size32_t cInitialBuckets, float32_t flLoadFactor, float32_t flGrowthRate)
: f_vResizing(self(), Object::create()), m_cEntries(0), m_haeBucket(*f_vResizing)
{
if (flLoadFactor <= 0)
{
COH_THROW (IllegalArgumentException::create(
"SafeHashMap: Load factor must be greater than zero."));
}
if (flGrowthRate <= 0)
{
COH_THROW (IllegalArgumentException::create(
"SafeHashMap: Growth rate must be greater than zero."));
}
if (cInitialBuckets == 0)
{
// Note that 0 is reserved for detecting growth
cInitialBuckets = 1;
}
// initialize the hash map data structure
m_haeBucket = ObjectArray::create(cInitialBuckets);
m_cCapacity = (size32_t) (cInitialBuckets * flLoadFactor);
m_flLoadFactor = flLoadFactor;
m_flGrowthRate = flGrowthRate;
}
SafeHashMap::SafeHashMap(const SafeHashMap& that)
: super(), f_vResizing(self(), Object::create()), m_cEntries(0),
m_haeBucket(*f_vResizing)
{
COH_SYNCHRONIZED (&that)
{
// only have to deep-clone the bucket array and the map entries
ObjectArray::View vaeBucket = that.m_haeBucket;
size32_t cBuckets = vaeBucket->length;
ObjectArray::Handle haeBucket = ObjectArray::create(cBuckets);
for (size32_t i = 0; i < cBuckets; ++i)
{
Entry::View vEntryThat = cast<Entry::View>(vaeBucket[i]);
if (vEntryThat != NULL)
{
haeBucket[i] = copyEntryList(vEntryThat, true);
}
}
m_haeBucket = haeBucket;
m_cCapacity = that.m_cCapacity;
m_cEntries = that.m_cEntries;
m_flLoadFactor = that.m_flLoadFactor;
m_flGrowthRate = that.m_flGrowthRate;
}
}
// ----- Map interface ------------------------------------------------------
size32_t SafeHashMap::size() const
{
COH_SYNCHRONIZED_MEMBER_READ
{
return m_cEntries;
}
}
bool SafeHashMap::isEmpty() const
{
return size() == 0;
}
bool SafeHashMap::containsKey(Object::View vKey) const
{
return getEntryInternal(vKey) != NULL;
}
Object::Holder SafeHashMap::get(Object::View vKey) const
{
Entry::View vEntry = getEntryInternal(vKey);
return NULL == vEntry ? (Object::Holder) NULL : vEntry->getValue();
}
SafeHashMap::Entry::View SafeHashMap::getEntry(Object::View vKey) const
{
return getEntryInternal(vKey);
}
SafeHashMap::Entry::Handle SafeHashMap::getEntry(Object::View vKey)
{
return getEntryInternal(vKey);
}
Object::Holder SafeHashMap::put(Object::View vKey, Object::Holder ohValue)
{
Entry::Handle hEntry = getEntryInternal(vKey);
nonexistent: if (NULL == hEntry)
{
// calculate hash code for the key
size32_t nHash = getHashCode(vKey);
// instantiate and configure a new Entry
hEntry = instantiateEntry(vKey, ohValue, nHash);
// synchronize the addition of the new Entry
// note that it is possible that an Entry with the same key
// has been added by another thread
COH_SYNCHRONIZED (this)
{
// get the array of buckets
ObjectArray::Handle haeBucket = m_haeBucket;
size32_t cBuckets = haeBucket->length;
// hash to a particular bucket
size32_t nBucket = getBucketIndex(nHash, cBuckets);
Entry::Handle hEntryCur = cast<Entry::Handle>(haeBucket[nBucket]);
// walk the linked list of entries (open hash) in the bucket
// to verify the Entry has not already been added
while (hEntryCur != NULL)
{
// optimization: check hash first
if (nHash == hEntryCur->m_nHash && hEntryCur->isKeyEqual(vKey))
{
// found the entry; it is no longer non-existent
hEntry = hEntryCur;
goto nonexistent;
}
hEntryCur = hEntryCur->m_hNext;
}
// put the Entry in at the front of the list of entries
// for that bucket
hEntry->m_hNext = cast<Entry::Handle>(haeBucket[nBucket]);
haeBucket[nBucket] = hEntry;
size32_t cEntries = m_cEntries;
m_cEntries = ++cEntries;
if (cEntries > m_cCapacity)
{
grow();
}
}
// note: supports subclasses that implement ObservableMap
hEntry->onAdd();
return NULL;
}
// note that it is possible that the Entry is being removed
// by another thread or that the value is being updated by
// another thread because this is not synchronized
return hEntry->setValue(ohValue);
}
void SafeHashMap::grow()
{
if (!isValid())
{
COH_THROW(IllegalStateException::create("No longer valid"));
}
COH_SYNCHRONIZED (this)
{
// store off the old bucket array
ObjectArray::Handle haeOld = m_haeBucket;
size32_t cOld = haeOld->length;
// check if there is no more room to grow
if (cOld >= biggest_modulo)
{
return;
}
// use a 0-length array to signify that a resize is taking place
m_haeBucket = getNoEntriesArray();
// calculate growth
size32_t cNew = (size32_t) std::min((int64_t) (cOld * (1.0F + m_flGrowthRate)), (int64_t) biggest_modulo);
if (cNew <= cOld)
{
// very low growth rate or very low initial size (stupid!)
cNew = cOld + 1;
}
// use a prime number at least as big than the new size
cNew = getNextPrime(cNew); // see AssociativeArray.hpp
// create a new bucket array; in the case of an OutOfMemoryError
// be sure to restore the old bucket array
ObjectArray::Handle haeNew;
try
{
haeNew = ObjectArray::create(cNew);
if (NULL == haeNew)
{
m_haeBucket = haeOld;
COH_THROW (IllegalStateException::create(
"out of memory during SafeHashMap::grow()"));
}
}
catch (...)
{
m_haeBucket = haeOld;
throw;
}
// if there are Iterators active, they are iterating over an array of
// buckets which is about to be completely whacked; to make sure that
// the Iterators can recover from the bucket array getting whacked,
// the resize will create a clone of each entry in the old bucket
// array and put those clones into the old bucket array in the same
// order that the original entries were found, thus allowing the
// Iterators to find their place again without missing or repeating
// any data, other than the potential for missing data added after
// the iteration began (which is always possible anyways)
bool fRetain = isActiveIterator();
// rehash
for (size32_t i = 0; i < cOld; ++i)
{
Entry::Handle hEntry = cast<Entry::Handle>(haeOld[i]);
Entry::Handle hEntryRetain = NULL;
// NSA Store off the old entries so we can put them in place for
// the iterators. I'm sure this can be more optimized but until
// I have confidence in the approach and a deeper understanding
// of this code I want to Keep It Simple Stupid!
Entry::Handle hEntryCopy = fRetain ? copyEntryList(hEntry, false) : NULL;
while (hEntry != NULL)
{
// store off the next Entry
// (it is going to get hammered otherwise)
Entry::Handle hEntryNext = hEntry->m_hNext;
// rehash the Entry into the new bucket array
size32_t nBucket = getBucketIndex(hEntry->m_nHash, cNew);
hEntry->m_hNext = cast<Entry::Handle>(haeNew[nBucket]);
haeNew[nBucket] = hEntry;
/*
// clone each entry if Iterators are active (since they will
// need the entries in the same order to avoid having to
// throw a CME in most cases)
if (fRetain)
{
Entry::Handle hEntryCopy = cast<Entry::Handle>(hEntry->clone());
if (NULL == hEntryRetain)
{
haeOld[i] = hEntryCopy;
}
else
{
hEntryRetain->m_hNext = hEntryCopy;
}
hEntryRetain = hEntryCopy;
}
*/
// process next Entry in the old list
hEntry = hEntryNext;
}
// NSA is this an acceptable order modification or are we at risk
// here for CMEs?
if (fRetain)
{
haeOld[i] = hEntryCopy;
}
}
// store updated bucket array
m_cCapacity = (size32_t) (cNew * m_flLoadFactor);
m_haeBucket = haeNew;
// notify threads that are waiting for the resize to complete
COH_SYNCHRONIZED (f_vResizing)
{
f_vResizing->notifyAll();
}
}
}
size32_t SafeHashMap::getHashCode(Object::View vKey) const
{
return Object::hashCode(vKey);
}
Object::Holder SafeHashMap::remove(Object::View vKey)
{
COH_SYNCHRONIZED (this)
{
// get the array of buckets
ObjectArray::Handle haeBucket = m_haeBucket;
size32_t cBuckets = haeBucket->length;
// hash to a particular bucket
size32_t nHash = getHashCode(vKey);
size32_t nBucket = getBucketIndex(nHash, cBuckets);
Entry::Handle hEntryCur = cast<Entry::Handle>(haeBucket[nBucket]);
// walk the linked list of entries (open hash) in the bucket
// to verify the Entry has not already been added
Entry::Handle hEntryPrev = NULL;
while (hEntryCur != NULL)
{
// optimization: check hash first
if (nHash == hEntryCur->m_nHash && hEntryCur->isKeyEqual(vKey))
{
// remove the current Entry from the list
if (NULL == hEntryPrev)
{
haeBucket[nBucket] = (Object::Handle) hEntryCur->m_hNext;
}
else
{
hEntryPrev->m_hNext = hEntryCur->m_hNext;
}
m_cEntries = m_cEntries - 1;
return hEntryCur->getValue();
}
hEntryPrev = hEntryCur;
hEntryCur = hEntryCur->m_hNext;
}
return NULL;
}
}
void SafeHashMap::clear()
{
COH_SYNCHRONIZED (this)
{
m_haeBucket = ObjectArray::create(default_initialsize);
m_cEntries = 0;
m_cCapacity = (size32_t) (default_initialsize * m_flLoadFactor);
}
}
Set::View SafeHashMap::entrySet() const
{
// we can't cache the entrySet as we'd end up with a circular reference
// and be self sustaining. Using a WeakReference from the Map to the
// EntrySet wouldn't be too useful, and doing a WeakReference from the
// Set to the Map would be plain incorrect
return instantiateEntrySet();
}
Set::Handle SafeHashMap::entrySet()
{
// we can't cache the entrySet as we'd end up with a circular reference
// and be self sustaining. Using a WeakReference from the Map to the
// EntrySet wouldn't be too useful, and doing a WeakReference from the
// Set to the Map would be plain incorrect
return instantiateEntrySet();
}
// ----- helper methods -----------------------------------------------------
SafeHashMap::Entry::Handle SafeHashMap::cloneEntryList(Entry::View vEntryThat) const
{
if (NULL == vEntryThat)
{
return NULL;
}
// clone the head of the chain
Entry::Handle hEntryThis = cast<Entry::Handle>(vEntryThat->clone());
// clone the rest of the chain
Entry::Handle hEntryPrevThis = hEntryThis;
Entry::View vEntryNextThat = vEntryThat->m_hNext;
while (vEntryNextThat != NULL)
{
// clone the entry
Entry::Handle hEntryNextThis = cast<Entry::Handle>(vEntryNextThat->clone());
// link it in
hEntryPrevThis->m_hNext = hEntryNextThis;
// advance
hEntryPrevThis = hEntryNextThis;
vEntryNextThat = vEntryNextThat->m_hNext;
}
return hEntryThis;
}
SafeHashMap::Entry::Handle SafeHashMap::getEntryInternal(Object::View vKey) const
{
// calculate hash code for the oKey
size32_t nHash = getHashCode(vKey);
while (true)
{
// get the bucket array
ObjectArray::View vaeBucket = getStableBucketArray();
size32_t cBuckets = vaeBucket->length;
// hash to a particular bucket
size32_t nBucket = getBucketIndex(nHash, cBuckets);
Entry::Handle hEntry = cast<Entry::Handle>(vaeBucket[nBucket]);
// walk the linked list of entries (open hash) in the bucket
while (hEntry != NULL)
{
// optimization: check hash first
if (nHash == hEntry->m_nHash && hEntry->isKeyEqual(vKey))
{
// COH-1542: check for resize before returning Entry
break;
}
hEntry = hEntry->m_hNext;
}
// if a resize occurred, the bucket array may have been reshuffled
// while we were searching it; we know a resize occurred iff the
// hash bucket array changed
if (vaeBucket == m_haeBucket)
{
// no resize occurred
return hEntry;
}
}
}
void SafeHashMap::removeEntryInternal(Entry::Handle hEntry)
{
COH_SYNCHRONIZED (this)
{
if (NULL == hEntry)
{
COH_THROW (IllegalArgumentException::create("entry is NULL"));
}
// get the array of buckets
ObjectArray::Handle haeBucket = m_haeBucket;
size32_t cBuckets = haeBucket->length;
// hash to a particular bucket
size32_t nHash = hEntry->m_nHash;
size32_t nBucket = getBucketIndex(nHash, cBuckets);
// check the head
Entry::Handle hEntryHead = cast<Entry::Handle>(haeBucket[nBucket]);
if (hEntry == hEntryHead)
{
haeBucket[nBucket] = hEntry->m_hNext;
}
else
{
// walk the linked list of entries (open hash) in the bucket
Entry::Handle hEntryPrev = hEntryHead;
while (true)
{
if (NULL == hEntryPrev)
{
// another thread has already removed the entry
return;
}
Entry::Handle hEntryCur = hEntryPrev->m_hNext;
if (hEntry == hEntryCur)
{
hEntryPrev->m_hNext = hEntryCur->m_hNext;
break;
}
hEntryPrev = hEntryCur;
}
}
m_cEntries = m_cEntries - 1;
}
}
size32_t SafeHashMap::getBucketIndex(size32_t nHash, size32_t cBuckets) const
{
return nHash % cBuckets;
}
ObjectArray::View SafeHashMap::getStableBucketArray() const
{
// get the bucket array
ObjectArray::View vaeBucket = m_haeBucket;
// wait for any ongoing resize to complete
while (vaeBucket->length == 0)
{
COH_SYNCHRONIZED (f_vResizing)
{
// now that we have the lock, verify that it is
// still necessary to wait
if (m_haeBucket->length == 0)
{
if (isValid())
{
// limit the wait, so grow() can fail w/out notifying
f_vResizing->wait(1000);
}
else
{
COH_THROW(IllegalStateException::create("No longer valid"));
}
}
}
vaeBucket = m_haeBucket;
}
return vaeBucket;
}
void SafeHashMap::iteratorActivated() const
{
m_cIterators.adjust(1);
}
void SafeHashMap::iteratorDeactivated() const
{
m_cIterators.adjust(-1);
}
bool SafeHashMap::isActiveIterator() const
{
return m_cIterators.get() != 0;
}
void SafeHashMap::invalidate()
{
COH_SYNCHRONIZED (this)
{
m_haeBucket = getInvalidArray();
m_cEntries = 0;
m_cCapacity = 0;
}
}
bool SafeHashMap::isValid() const
{
return m_haeBucket != getInvalidArray();
}
SafeHashMap::Entry::Handle SafeHashMap::copyEntryList(
SafeHashMap::Entry::View vEntry, bool fDeep)
{
if (vEntry == NULL)
{
return NULL;
}
// Clone the head of the chain
Entry::Handle hResult = copyEntry(vEntry, fDeep);
SafeHashMap::Entry::Handle hEntry = hResult;
while (vEntry->m_hNext != NULL)
{
// grab the next entry to copy
vEntry = vEntry->m_hNext;
// copy the next entry
hEntry->m_hNext = copyEntry(vEntry, fDeep);
// move the chains
hEntry = hEntry->m_hNext;
}
return hResult;
}
SafeHashMap::Entry::Handle SafeHashMap::copyEntry(Entry::View vEntry, bool fDeep)
{
// Clone the head of the chain
Entry::Handle hResult;
if (fDeep)
{
Object::View vKey = vEntry->getKey()->clone();
hResult = instantiateEntry(vKey,
vEntry->getValue()->clone(), getHashCode(vKey));
}
else
{
hResult = instantiateEntry(vEntry);
}
return hResult;
}
// ----- inner class: Entry -------------------------------------------------
SafeHashMap::Entry::Handle SafeHashMap::instantiateEntry(Object::View vKey,
Object::Holder ohValue, size32_t nHash)
{
return Entry::create(vKey, ohValue, nHash);
}
SafeHashMap::Entry::Handle SafeHashMap::instantiateEntry(SafeHashMap::Entry::View vEntry)
{
return Entry::create(vEntry);
}
SafeHashMap::Entry::Entry(Object::View vKey, Object::Holder ohValue,
size32_t nHash)
: f_vKey(self(), vKey), m_ohValue(self(), ohValue), m_nHash(nHash),
m_hNext(self())
{
}
SafeHashMap::Entry::Entry(const SafeHashMap::Entry& that)
: super(that), f_vKey(self(), Object::clone(that.f_vKey)),
m_ohValue(self(), Object::clone(that.m_ohValue)),
m_nHash(that.m_nHash), m_hNext(self())
{
}
SafeHashMap::Entry::Entry(Entry::View vThat)
: f_vKey(self(), vThat->f_vKey),
m_ohValue(self(), vThat->m_ohValue),
m_nHash(vThat->m_nHash), m_hNext(self())
{
}
bool SafeHashMap::Entry::isKeyEqual(Object::View vKey) const
{
return Object::equals(f_vKey, vKey);
}
Object::View SafeHashMap::Entry::getKey() const
{
return f_vKey;
}
Object::Holder SafeHashMap::Entry::getValue() const
{
return m_ohValue;
}
Object::Holder SafeHashMap::Entry::getValue()
{
return ((const Entry*) this)->getValue();
}
Object::Holder SafeHashMap::Entry::setValue(Object::Holder ohValue)
{
COH_SYNCHRONIZED_MEMBER_WRITE
{
return coh_synchronized_member_write.exchangeMember(m_ohValue, ohValue);
}
}
bool SafeHashMap::Entry::equals(Object::View that) const
{
Map::Entry::View vThat = cast<Map::Entry::View>(that, false);
if (vThat != NULL)
{
if (this == vThat)
{
return true;
}
Object::View vThisValue = this->m_ohValue;
Object::View vThatValue = vThat->getValue();
return isKeyEqual(vThat->getKey()) &&
(NULL == vThisValue ? NULL == vThatValue
: vThisValue->equals(vThatValue));
}
return false;
}
size32_t SafeHashMap::Entry::hashCode() const
{
return Object::hashCode(getKey());
}
TypedHandle<const String> SafeHashMap::Entry::toString() const
{
return Collections::toString(this);
}
void SafeHashMap::Entry::onAdd()
{
}
// ----- inner class: EntrySet ----------------------------------------------
Set::Handle SafeHashMap::instantiateEntrySet()
{
return EntrySet::create(Handle(this));
}
Set::View SafeHashMap::instantiateEntrySet() const
{
return EntrySet::create(View(this));
}
SafeHashMap::EntrySet::EntrySet(SafeHashMap::Holder ohMap)
: f_ohMap(self(), ohMap)
{
}
// ----- Set interface --------------------------------------------------
Iterator::Handle SafeHashMap::EntrySet::iterator() const
{
return instantiateIterator();
}
Muterator::Handle SafeHashMap::EntrySet::iterator()
{
return instantiateIterator();
}
size32_t SafeHashMap::EntrySet::size() const
{
return getDelegate()->size();
}
bool SafeHashMap::EntrySet::contains(Object::View v) const
{
Map::Entry::View vEntry = cast<Map::Entry::View>(v);
if (vEntry != NULL)
{
Map::Entry::View vThisEntry = getDelegate()->getEntryInternal(vEntry->getKey());
return vThisEntry != NULL && vThisEntry->equals(vEntry);
}
return false;
}
bool SafeHashMap::EntrySet::remove(Object::View v)
{
SafeHashMap::Handle hMap = getDelegate();
COH_SYNCHRONIZED (hMap)
{
if (contains(v))
{
hMap->remove((cast<Map::Entry::View>(v))->getKey());
return true;
}
else
{
return false;
}
}
}
void SafeHashMap::EntrySet::clear()
{
getDelegate()->clear();
}
ObjectArray::Handle SafeHashMap::EntrySet::toArray(
ObjectArray::Handle ha) const
{
// synchronizing prevents add/remove, keeping size() constant
SafeHashMap::View vMap = getDelegate();
COH_SYNCHRONIZED (vMap)
{
// verify ha size or create the array to store the map contents
size32_t c = vMap->size();
if (ha == NULL || ha->length < c)
{
ha = ObjectArray::create(c);
}
else if (ha->length > c)
{
ha[c] = NULL;
}
// walk all buckets
ObjectArray::View vaeBucket = vMap->m_haeBucket;
size32_t cBuckets = vaeBucket->length;
for (size32_t iBucket = 0, i = 0; iBucket < cBuckets; ++iBucket)
{
// walk all entries in the bucket
Entry::Holder ohEntry = cast<Entry::Holder>(vaeBucket[iBucket]);
while (ohEntry != NULL)
{
ha[i++] = ohEntry;
if (instanceof<Entry::Handle>(ohEntry))
{
ohEntry = cast<Entry::Handle>(ohEntry)->m_hNext;
}
else
{
ohEntry = ohEntry->m_hNext;
}
}
}
}
return ha;
}
// ----- Object interface -----------------------------------------------
bool SafeHashMap::EntrySet::equals(Object::View that) const
{
if (that == this)
{
return true;
}
Set::View vThat = cast<Set::View>(that, false);
if (NULL == vThat)
{
return false;
}
return vThat->size() == size() && containsAll(vThat);
}
size32_t SafeHashMap::EntrySet::hashCode() const
{
size32_t nHash = 0;
for (Iterator::Handle hIter = iterator(); hIter->hasNext(); )
{
nHash += Object::hashCode(hIter->next());
}
return nHash;
}
SafeHashMap::View SafeHashMap::EntrySet::getDelegate() const
{
return f_ohMap;
}
SafeHashMap::Handle SafeHashMap::EntrySet::getDelegate()
{
return cast<SafeHashMap::Handle>(f_ohMap);
}
// ----- inner class: EntrySet Iterator -------------------------------------
Iterator::Handle SafeHashMap::EntrySet::instantiateIterator() const
{
return EntrySetIterator::create(getDelegate());
}
Muterator::Handle SafeHashMap::EntrySet::instantiateIterator()
{
return EntrySetIterator::create(getDelegate());
}
SafeHashMap::EntrySetIterator::EntrySetIterator(SafeHashMap::Holder ohMap)
: f_ohMap(self(), ohMap), m_vaeBucket(self()), m_iBucket(size32_t(-1)),
m_hEntryPrev(self(), Entry::Handle(NULL), true),
m_fResized(false), m_fDeactivated(false),
m_fViewer(!instanceof<Map::Handle>(ohMap))
{
}
SafeHashMap::EntrySetIterator::~EntrySetIterator()
{
try
{
deactivate();
}
catch (Exception::View e)
{
COH_LOG("Unexpected exception in destructor: " << e, 1);
// eat it
}
}
// ----- internal -------------------------------------------------------
void SafeHashMap::EntrySetIterator::advance()
{
if (m_fDeactivated)
{
// the Iterator has already reached the end on a previous
// call to advance()
return;
}
SafeHashMap::View vMap = f_ohMap;
ObjectArray::View vaeBucket = m_vaeBucket;
if (NULL == vaeBucket)
{
vMap->iteratorActivated();
vaeBucket = m_vaeBucket = vMap->getStableBucketArray();
}
Entry::Handle hEntry = m_hEntryPrev;
size32_t iBucket = size32_t(-1); // -1 indicates no change
bool fResized = m_fResized; // resize previously detected
while (true)
{
if (hEntry != NULL)
{
// advance within the currrent bucket
hEntry = hEntry->m_hNext;
}
// check if the current bucket has been exhausted, and if
// it has, then advance to the first non-empty bucket
if (NULL == hEntry)
{
iBucket = m_iBucket;
size32_t cBuckets = vaeBucket->length;
do
{
if (++iBucket >= cBuckets)
{
// a resize could have occurred to cause this
if (!fResized && vaeBucket != vMap->m_haeBucket)
{
// at this point, a resize has just been
// detected; the handling for the resize
// is below
break;
}
deactivate();
return;
}
hEntry = cast<Entry::Handle>(vaeBucket[iBucket]);
}
while (NULL == hEntry);
}
// check for a resize having occurred since the iterator
// was created
if (!fResized && vaeBucket != vMap->m_haeBucket)
{
m_fResized = true;
// if there is a previously-iterated entry, the
// Iterator has to back up and find that same entry
// in the cloned list of entries in the bucket; that
// cloned list is used to maintain a nearly CME-free
// view of the Map contents after the resize has
// occurred.
if (m_hEntryPrev != NULL)
{
// wait for the resize to complete (so that the
// necessary clones of each entry will have been
// created)
vMap->getStableBucketArray();
// find the same entry
Object::View vKey = m_hEntryPrev->getKey();
hEntry = cast<Entry::Handle>(vaeBucket[m_iBucket]);
while (hEntry != NULL && hEntry->getKey() != vKey)
{
hEntry = hEntry->m_hNext;
}
if (NULL == hEntry)
{
// previous has been removed, thus we don't
// know where to pick up the iteration and
// have to revert to a CME
deactivate();
COH_THROW (ConcurrentModificationException::create());
}
m_hEntryPrev = hEntry;
}
// since a resize has occurred, the Iterator has to
// start again from the last-iterated entry to find
// the next entry, because the entry that this
// Iterator had previously is a "real" entry which
// is in the new "current" bucket array for the Map,
// while the entries being iterated (post-resize) are
// just copies of the entries created to maintain the
// pre-resize iteration order
advance();
return;
}
// after a resize occurs, the entries being iterated
// over are no longer the "real" entries; they are simply
// place-holders for purpose of maintaining the order of
// the iterator; if this has occurred, find the real
// entry and make it visible from the Iterator
Entry::Handle hEntryVisible = fResized
? vMap->getEntryInternal(hEntry->getKey())
: hEntry;
// update the current bucket index if the iterator
// advanced to a new bucket
if (iBucket != (size32_t) -1)
{
m_iBucket = iBucket;
}
// after a resize, the entry could have been removed, and
// that would not have shown up in the pre-resize entries
// that this iterator is going over so check for a remove
if (hEntryVisible != NULL)
{
// remember the entry being iterated next; if a
// resize has occurred, this is a copy of the
// actual entry, maintained by the Iterator for
// purposes of providing a nearly CME-free
// iteration
m_hEntryPrev = hEntry;
// report back the actual entry that exists in the
// Map that is being iterated next
if (m_fViewer)
{
// Iterator over Set::View, don't return Handles to Entries
setNext((Object::View) hEntryVisible);
}
else
{
setNext(hEntryVisible);
}
return;
}
}
}
void SafeHashMap::EntrySetIterator::deactivate() const
{
if (!m_fDeactivated)
{
// no more entries to iterate; notify the
// containing Map that this Iterator is no
// longer active against a particular version
// of the bucket array
f_ohMap->iteratorDeactivated();
m_fDeactivated = true;
}
}
void SafeHashMap::EntrySetIterator::remove(Object::Holder oh)
{
if (m_fViewer)
{
COH_THROW (UnsupportedOperationException::create());
}
SafeHashMap::Handle hMap = cast<SafeHashMap::Handle>(f_ohMap);
hMap->remove(cast<Map::Entry::Handle>(oh)->getKey());
}
COH_CLOSE_NAMESPACE2
| 30.630824 | 114 | 0.547683 | [
"object"
] |
f57373ca39796b92ad926bcc678544ba9f8fb499 | 519 | hpp | C++ | KDBMS/TableColumn.hpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | KDBMS/TableColumn.hpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | KDBMS/TableColumn.hpp | karbovskiydmitriy/KDBMS | 573ba629dc88f79b8c85127f42eb2b5806178d07 | [
"MIT"
] | null | null | null | #pragma once
#ifndef __TABLECOLUMN_HPP__
#define __TABLECOLUMN_HPP__
#include "Config.hpp"
#include <string>
#include "Serializeable.hpp"
#include "Types.hpp"
#include "Attributes.hpp"
using namespace std;
struct DllExport TableColumn : Serializeable
{
String name;
Type type;
Attributes attributes;
TableColumn();
TableColumn(String name, Type type, Attributes attributes = 0);
SerializedObject Serialize() override;
bool Deserialize(SerializedObject object) override;
};
#endif // __TABLECOLUMN_HPP__
| 17.3 | 64 | 0.77842 | [
"object"
] |
f5748f7c459c8224121fe4b84251823f8c4cb6cd | 16,990 | cpp | C++ | unittests/whitelist_blacklist_tests.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | unittests/whitelist_blacklist_tests.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | unittests/whitelist_blacklist_tests.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <cubetrain/testing/tester.hpp>
#include <cubetrain/testing/tester_network.hpp>
#include <fc/variant_object.hpp>
#include <cubetrain.tk/cubetrain.tk.wast.hpp>
#include <cubetrain.tk/cubetrain.tk.abi.hpp>
#include <deferred_test/deferred_test.wast.hpp>
#include <deferred_test/deferred_test.abi.hpp>
#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif
using namespace cubetrain;
using namespace cubetrain::chain;
using namespace cubetrain::testing;
using mvo = fc::mutable_variant_object;
template<class Tester = TESTER>
class whitelist_blacklist_tester {
public:
whitelist_blacklist_tester() {}
static controller::config get_default_chain_configuration( const fc::path& p ) {
controller::config cfg;
cfg.blocks_dir = p / config::default_blocks_dir_name;
cfg.state_dir = p / config::default_state_dir_name;
cfg.state_size = 1024*1024*8;
cfg.state_guard_size = 0;
cfg.reversible_cache_size = 1024*1024*8;
cfg.reversible_guard_size = 0;
cfg.contracts_console = true;
cfg.genesis.initial_timestamp = fc::time_point::from_iso_string("2020-01-01T00:00:00.000");
cfg.genesis.initial_key = base_tester::get_public_key( config::system_account_name, "active" );
for(int i = 0; i < boost::unit_test::framework::master_test_suite().argc; ++i) {
if(boost::unit_test::framework::master_test_suite().argv[i] == std::string("--binaryen"))
cfg.wasm_runtime = chain::wasm_interface::vm_type::binaryen;
else if(boost::unit_test::framework::master_test_suite().argv[i] == std::string("--wavm"))
cfg.wasm_runtime = chain::wasm_interface::vm_type::wavm;
else
cfg.wasm_runtime = chain::wasm_interface::vm_type::binaryen;
}
return cfg;
}
void init( bool bootstrap = true ) {
FC_ASSERT( !chain, "chain is already up" );
auto cfg = get_default_chain_configuration( tempdir.path() );
cfg.actor_whitelist = actor_whitelist;
cfg.actor_blacklist = actor_blacklist;
cfg.contract_whitelist = contract_whitelist;
cfg.contract_blacklist = contract_blacklist;
cfg.action_blacklist = action_blacklist;
chain.emplace(cfg);
wdump((last_produced_block));
chain->set_last_produced_block_map( last_produced_block );
if( !bootstrap ) return;
chain->create_accounts({N(cubetrain.tk), N(alice), N(bob), N(charlie)});
chain->set_code(N(cubetrain.tk), cubetrain_tk_wast);
chain->set_abi(N(cubetrain.tk), cubetrain_tk_abi);
chain->push_action( N(cubetrain.tk), N(create), N(cubetrain.tk), mvo()
( "issuer", "cubetrain.tk" )
( "maximum_supply", "1000000.00 TOK" )
);
chain->push_action( N(cubetrain.tk), N(issue), N(cubetrain.tk), mvo()
( "to", "cubetrain.tk" )
( "quantity", "1000000.00 TOK" )
( "memo", "issue" )
);
chain->produce_blocks();
}
void shutdown() {
FC_ASSERT( chain.valid(), "chain is not up" );
last_produced_block = chain->get_last_produced_block_map();
wdump((last_produced_block));
chain.reset();
}
transaction_trace_ptr transfer( account_name from, account_name to, string quantity = "1.00 TOK" ) {
return chain->push_action( N(cubetrain.tk), N(transfer), from, mvo()
( "from", from )
( "to", to )
( "quantity", quantity )
( "memo", "" )
);
}
fc::temp_directory tempdir; // Must come before chain
fc::optional<Tester> chain;
flat_set<account_name> actor_whitelist;
flat_set<account_name> actor_blacklist;
flat_set<account_name> contract_whitelist;
flat_set<account_name> contract_blacklist;
flat_set< pair<account_name, action_name> > action_blacklist;
map<account_name, block_id_type> last_produced_block;
};
struct transfer_args {
account_name from;
account_name to;
asset quantity;
string memo;
};
FC_REFLECT( transfer_args, (from)(to)(quantity)(memo) )
BOOST_AUTO_TEST_SUITE(whitelist_blacklist_tests)
BOOST_AUTO_TEST_CASE( actor_whitelist ) { try {
whitelist_blacklist_tester<> test;
test.actor_whitelist = {config::system_account_name, N(cubetrain.tk), N(alice)};
test.init();
test.transfer( N(cubetrain.tk), N(alice), "1000.00 TOK" );
test.transfer( N(alice), N(bob), "100.00 TOK" );
BOOST_CHECK_EXCEPTION( test.transfer( N(bob), N(alice) ),
actor_whitelist_exception,
fc_exception_message_is("authorizing actor(s) in transaction are not on the actor whitelist: [\"bob\"]")
);
signed_transaction trx;
trx.actions.emplace_back( vector<permission_level>{{N(alice),config::active_name}, {N(bob),config::active_name}},
N(cubetrain.tk), N(transfer),
fc::raw::pack(transfer_args{
.from = N(alice),
.to = N(bob),
.quantity = asset::from_string("10.00 TOK"),
.memo = ""
})
);
test.chain->set_transaction_headers(trx);
trx.sign( test.chain->get_private_key( N(alice), "active" ), test.chain->control->get_chain_id() );
trx.sign( test.chain->get_private_key( N(bob), "active" ), test.chain->control->get_chain_id() );
BOOST_CHECK_EXCEPTION( test.chain->push_transaction( trx ),
actor_whitelist_exception,
fc_exception_message_starts_with("authorizing actor(s) in transaction are not on the actor whitelist: [\"bob\"]")
);
test.chain->produce_blocks();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( actor_blacklist ) { try {
whitelist_blacklist_tester<> test;
test.actor_blacklist = {N(bob)};
test.init();
test.transfer( N(cubetrain.tk), N(alice), "1000.00 TOK" );
test.transfer( N(alice), N(bob), "100.00 TOK" );
BOOST_CHECK_EXCEPTION( test.transfer( N(bob), N(alice) ),
actor_blacklist_exception,
fc_exception_message_starts_with("authorizing actor(s) in transaction are on the actor blacklist: [\"bob\"]")
);
signed_transaction trx;
trx.actions.emplace_back( vector<permission_level>{{N(alice),config::active_name}, {N(bob),config::active_name}},
N(cubetrain.tk), N(transfer),
fc::raw::pack(transfer_args{
.from = N(alice),
.to = N(bob),
.quantity = asset::from_string("10.00 TOK"),
.memo = ""
})
);
test.chain->set_transaction_headers(trx);
trx.sign( test.chain->get_private_key( N(alice), "active" ), test.chain->control->get_chain_id() );
trx.sign( test.chain->get_private_key( N(bob), "active" ), test.chain->control->get_chain_id() );
BOOST_CHECK_EXCEPTION( test.chain->push_transaction( trx ),
actor_blacklist_exception,
fc_exception_message_starts_with("authorizing actor(s) in transaction are on the actor blacklist: [\"bob\"]")
);
test.chain->produce_blocks();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( contract_whitelist ) { try {
whitelist_blacklist_tester<> test;
test.contract_whitelist = {config::system_account_name, N(cubetrain.tk), N(bob)};
test.init();
test.transfer( N(cubetrain.tk), N(alice), "1000.00 TOK" );
test.transfer( N(alice), N(cubetrain.tk) );
test.transfer( N(alice), N(bob) );
test.transfer( N(alice), N(charlie), "100.00 TOK" );
test.transfer( N(charlie), N(alice) );
test.chain->produce_blocks();
test.chain->set_code(N(bob), cubetrain_tk_wast);
test.chain->set_abi(N(bob), cubetrain_tk_abi);
test.chain->produce_blocks();
test.chain->set_code(N(charlie), cubetrain_tk_wast);
test.chain->set_abi(N(charlie), cubetrain_tk_abi);
test.chain->produce_blocks();
test.transfer( N(alice), N(bob) );
BOOST_CHECK_EXCEPTION( test.transfer( N(alice), N(charlie) ),
contract_whitelist_exception,
fc_exception_message_is("account 'charlie' is not on the contract whitelist")
);
test.chain->push_action( N(bob), N(create), N(bob), mvo()
( "issuer", "bob" )
( "maximum_supply", "1000000.00 CUR" )
);
BOOST_CHECK_EXCEPTION( test.chain->push_action( N(charlie), N(create), N(charlie), mvo()
( "issuer", "charlie" )
( "maximum_supply", "1000000.00 CUR" )
),
contract_whitelist_exception,
fc_exception_message_starts_with("account 'charlie' is not on the contract whitelist")
);
test.chain->produce_blocks();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( contract_blacklist ) { try {
whitelist_blacklist_tester<> test;
test.contract_blacklist = {N(charlie)};
test.init();
test.transfer( N(cubetrain.tk), N(alice), "1000.00 TOK" );
test.transfer( N(alice), N(cubetrain.tk) );
test.transfer( N(alice), N(bob) );
test.transfer( N(alice), N(charlie), "100.00 TOK" );
test.transfer( N(charlie), N(alice) );
test.chain->produce_blocks();
test.chain->set_code(N(bob), cubetrain_tk_wast);
test.chain->set_abi(N(bob), cubetrain_tk_abi);
test.chain->produce_blocks();
test.chain->set_code(N(charlie), cubetrain_tk_wast);
test.chain->set_abi(N(charlie), cubetrain_tk_abi);
test.chain->produce_blocks();
test.transfer( N(alice), N(bob) );
BOOST_CHECK_EXCEPTION( test.transfer( N(alice), N(charlie) ),
contract_blacklist_exception,
fc_exception_message_is("account 'charlie' is on the contract blacklist")
);
test.chain->push_action( N(bob), N(create), N(bob), mvo()
( "issuer", "bob" )
( "maximum_supply", "1000000.00 CUR" )
);
BOOST_CHECK_EXCEPTION( test.chain->push_action( N(charlie), N(create), N(charlie), mvo()
( "issuer", "charlie" )
( "maximum_supply", "1000000.00 CUR" )
),
contract_blacklist_exception,
fc_exception_message_starts_with("account 'charlie' is on the contract blacklist")
);
test.chain->produce_blocks();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( action_blacklist ) { try {
whitelist_blacklist_tester<> test;
test.contract_whitelist = {config::system_account_name, N(cubetrain.tk), N(bob), N(charlie)};
test.action_blacklist = {{N(charlie), N(create)}};
test.init();
test.transfer( N(cubetrain.tk), N(alice), "1000.00 TOK" );
test.chain->produce_blocks();
test.chain->set_code(N(bob), cubetrain_tk_wast);
test.chain->set_abi(N(bob), cubetrain_tk_abi);
test.chain->produce_blocks();
test.chain->set_code(N(charlie), cubetrain_tk_wast);
test.chain->set_abi(N(charlie), cubetrain_tk_abi);
test.chain->produce_blocks();
test.transfer( N(alice), N(bob) );
test.transfer( N(alice), N(charlie) ),
test.chain->push_action( N(bob), N(create), N(bob), mvo()
( "issuer", "bob" )
( "maximum_supply", "1000000.00 CUR" )
);
BOOST_CHECK_EXCEPTION( test.chain->push_action( N(charlie), N(create), N(charlie), mvo()
( "issuer", "charlie" )
( "maximum_supply", "1000000.00 CUR" )
),
action_blacklist_exception,
fc_exception_message_starts_with("action 'charlie::create' is on the action blacklist")
);
test.chain->produce_blocks();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( blacklist_cubetrain ) { try {
whitelist_blacklist_tester<tester> tester1;
tester1.init();
tester1.chain->produce_blocks();
tester1.chain->set_code(config::system_account_name, cubetrain_tk_wast);
tester1.chain->produce_blocks();
tester1.shutdown();
tester1.contract_blacklist = {config::system_account_name};
tester1.init(false);
whitelist_blacklist_tester<tester> tester2;
tester2.init(false);
while( tester2.chain->control->head_block_num() < tester1.chain->control->head_block_num() ) {
auto b = tester1.chain->control->fetch_block_by_number( tester2.chain->control->head_block_num()+1 );
tester2.chain->push_block( b );
}
tester1.chain->produce_blocks(2);
while( tester2.chain->control->head_block_num() < tester1.chain->control->head_block_num() ) {
auto b = tester1.chain->control->fetch_block_by_number( tester2.chain->control->head_block_num()+1 );
tester2.chain->push_block( b );
}
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( deferred_blacklist_failure ) { try {
whitelist_blacklist_tester<tester> tester1;
tester1.init();
tester1.chain->produce_blocks();
tester1.chain->set_code( N(bob), deferred_test_wast );
tester1.chain->set_abi( N(bob), deferred_test_abi );
tester1.chain->set_code( N(charlie), deferred_test_wast );
tester1.chain->set_abi( N(charlie), deferred_test_abi );
tester1.chain->produce_blocks();
tester1.chain->push_action( N(bob), N(defercall), N(alice), mvo()
( "payer", "alice" )
( "sender_id", 0 )
( "contract", "charlie" )
( "payload", 10 )
);
tester1.chain->produce_blocks(2);
tester1.shutdown();
tester1.contract_blacklist = {N(charlie)};
tester1.init(false);
whitelist_blacklist_tester<tester> tester2;
tester2.init(false);
while( tester2.chain->control->head_block_num() < tester1.chain->control->head_block_num() ) {
auto b = tester1.chain->control->fetch_block_by_number( tester2.chain->control->head_block_num()+1 );
tester2.chain->push_block( b );
}
tester1.chain->push_action( N(bob), N(defercall), N(alice), mvo()
( "payer", "alice" )
( "sender_id", 1 )
( "contract", "charlie" )
( "payload", 10 )
);
BOOST_CHECK_EXCEPTION( tester1.chain->produce_blocks(), fc::exception,
fc_exception_message_is("account 'charlie' is on the contract blacklist")
);
tester1.chain->produce_blocks(2, true); // Produce 2 empty blocks (other than onblock of course).
while( tester2.chain->control->head_block_num() < tester1.chain->control->head_block_num() ) {
auto b = tester1.chain->control->fetch_block_by_number( tester2.chain->control->head_block_num()+1 );
tester2.chain->push_block( b );
}
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE( blacklist_onerror ) { try {
whitelist_blacklist_tester<TESTER> tester1;
tester1.init();
tester1.chain->produce_blocks();
tester1.chain->set_code( N(bob), deferred_test_wast );
tester1.chain->set_abi( N(bob), deferred_test_abi );
tester1.chain->set_code( N(charlie), deferred_test_wast );
tester1.chain->set_abi( N(charlie), deferred_test_abi );
tester1.chain->produce_blocks();
tester1.chain->push_action( N(bob), N(defercall), N(alice), mvo()
( "payer", "alice" )
( "sender_id", 0 )
( "contract", "charlie" )
( "payload", 13 )
);
tester1.chain->produce_blocks();
tester1.shutdown();
tester1.action_blacklist = {{config::system_account_name, N(onerror)}};
tester1.init(false);
tester1.chain->push_action( N(bob), N(defercall), N(alice), mvo()
( "payer", "alice" )
( "sender_id", 0 )
( "contract", "charlie" )
( "payload", 13 )
);
BOOST_CHECK_EXCEPTION( tester1.chain->produce_blocks(), fc::exception,
fc_exception_message_is("action 'cubetrain::onerror' is on the action blacklist")
);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_SUITE_END()
| 38.438914 | 140 | 0.597234 | [
"vector"
] |
f574a8fd8c6f6241b393d2bd7b95575cc144bc0e | 13,286 | hpp | C++ | external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmComputeShaderTestUtil.hpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmComputeShaderTestUtil.hpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmComputeShaderTestUtil.hpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | #ifndef _VKTSPVASMCOMPUTESHADERTESTUTIL_HPP
#define _VKTSPVASMCOMPUTESHADERTESTUTIL_HPP
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Compute Shader Based Test Case Utility Structs/Functions
*//*--------------------------------------------------------------------*/
#include "deDefs.h"
#include "deFloat16.h"
#include "deRandom.hpp"
#include "deSharedPtr.hpp"
#include "tcuTestLog.hpp"
#include "tcuVector.hpp"
#include "tcuTestLog.hpp"
#include "vkMemUtil.hpp"
#include "vktSpvAsmUtils.hpp"
#include <string>
#include <vector>
#include <map>
using namespace vk;
namespace vkt
{
namespace SpirVAssembly
{
enum OpAtomicType
{
OPATOMIC_IADD = 0,
OPATOMIC_ISUB,
OPATOMIC_IINC,
OPATOMIC_IDEC,
OPATOMIC_LOAD,
OPATOMIC_STORE,
OPATOMIC_COMPEX,
OPATOMIC_LAST
};
enum BufferType
{
BUFFERTYPE_INPUT = 0,
BUFFERTYPE_EXPECTED,
BUFFERTYPE_ATOMIC_RET,
BUFFERTYPE_LAST
};
static void fillRandomScalars (de::Random& rnd, deInt32 minValue, deInt32 maxValue, deInt32* dst, deInt32 numValues)
{
for (int i = 0; i < numValues; i++)
dst[i] = rnd.getInt(minValue, maxValue);
}
typedef de::MovePtr<vk::Allocation> AllocationMp;
typedef de::SharedPtr<vk::Allocation> AllocationSp;
/*--------------------------------------------------------------------*//*!
* \brief Abstract class for an input/output storage buffer object
*//*--------------------------------------------------------------------*/
class BufferInterface
{
public:
virtual ~BufferInterface (void) {}
virtual void getBytes (std::vector<deUint8>& bytes) const = 0;
virtual size_t getByteSize (void) const = 0;
};
typedef de::SharedPtr<BufferInterface> BufferSp;
/*--------------------------------------------------------------------*//*!
* \brief Concrete class for an input/output storage buffer object used for OpAtomic tests
*//*--------------------------------------------------------------------*/
class OpAtomicBuffer : public BufferInterface
{
public:
OpAtomicBuffer (const deUint32 numInputElements, const deUint32 numOuptutElements, const OpAtomicType opAtomic, const BufferType type)
: m_numInputElements (numInputElements)
, m_numOutputElements (numOuptutElements)
, m_opAtomic (opAtomic)
, m_type (type)
{}
void getBytes (std::vector<deUint8>& bytes) const
{
std::vector<deInt32> inputInts (m_numInputElements, 0);
de::Random rnd (m_opAtomic);
fillRandomScalars(rnd, 1, 100, &inputInts.front(), m_numInputElements);
// Return input values as is
if (m_type == BUFFERTYPE_INPUT)
{
size_t inputSize = m_numInputElements * sizeof(deInt32);
bytes.resize(inputSize);
deMemcpy(&bytes.front(), &inputInts.front(), inputSize);
}
// Calculate expected output values
else if (m_type == BUFFERTYPE_EXPECTED)
{
size_t outputSize = m_numOutputElements * sizeof(deInt32);
bytes.resize(outputSize, 0xffu);
for (size_t ndx = 0; ndx < m_numInputElements; ndx++)
{
deInt32* const bytesAsInt = reinterpret_cast<deInt32*>(&bytes.front());
switch (m_opAtomic)
{
case OPATOMIC_IADD: bytesAsInt[0] += inputInts[ndx]; break;
case OPATOMIC_ISUB: bytesAsInt[0] -= inputInts[ndx]; break;
case OPATOMIC_IINC: bytesAsInt[0]++; break;
case OPATOMIC_IDEC: bytesAsInt[0]--; break;
case OPATOMIC_LOAD: bytesAsInt[ndx] = inputInts[ndx]; break;
case OPATOMIC_STORE: bytesAsInt[ndx] = inputInts[ndx]; break;
case OPATOMIC_COMPEX: bytesAsInt[ndx] = (inputInts[ndx] % 2) == 0 ? -1 : 1; break;
default: DE_FATAL("Unknown OpAtomic type");
}
}
}
else if (m_type == BUFFERTYPE_ATOMIC_RET)
{
bytes.resize(m_numInputElements * sizeof(deInt32), 0xff);
if (m_opAtomic == OPATOMIC_COMPEX)
{
deInt32* const bytesAsInt = reinterpret_cast<deInt32*>(&bytes.front());
for (size_t ndx = 0; ndx < m_numInputElements; ndx++)
bytesAsInt[ndx] = inputInts[ndx] % 2;
}
}
else
DE_FATAL("Unknown buffer type");
}
size_t getByteSize (void) const
{
switch (m_type)
{
case BUFFERTYPE_ATOMIC_RET:
case BUFFERTYPE_INPUT:
return m_numInputElements * sizeof(deInt32);
case BUFFERTYPE_EXPECTED:
return m_numOutputElements * sizeof(deInt32);
default:
DE_FATAL("Unknown buffer type");
return 0;
}
}
template <int OpAtomic>
static bool compareWithRetvals (const std::vector<BufferSp>& inputs, const std::vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, tcu::TestLog& log)
{
if (outputAllocs.size() != 2 || inputs.size() != 1)
DE_FATAL("Wrong number of buffers to compare");
for (size_t i = 0; i < outputAllocs.size(); ++i)
{
const deUint32* values = reinterpret_cast<deUint32*>(outputAllocs[i]->getHostPtr());
if (i == 1 && OpAtomic != OPATOMIC_COMPEX)
{
// BUFFERTYPE_ATOMIC_RET for arithmetic operations must be verified manually by matching return values to inputs
std::vector<deUint8> inputBytes;
inputs[0]->getBytes(inputBytes);
const deUint32* inputValues = reinterpret_cast<deUint32*>(&inputBytes.front());
const size_t inputValuesCount = inputBytes.size() / sizeof(deUint32);
// result of all atomic operations
const deUint32 resultValue = *reinterpret_cast<deUint32*>(outputAllocs[0]->getHostPtr());
if (!compareRetVals<OpAtomic>(inputValues, inputValuesCount, resultValue, values))
{
log << tcu::TestLog::Message << "Wrong contents of buffer with return values after atomic operation." << tcu::TestLog::EndMessage;
return false;
}
}
else
{
const BufferSp& expectedOutput = expectedOutputs[i];
std::vector<deUint8> expectedBytes;
expectedOutput->getBytes(expectedBytes);
if (deMemCmp(&expectedBytes.front(), values, expectedBytes.size()))
{
log << tcu::TestLog::Message << "Wrong contents of buffer after atomic operation" << tcu::TestLog::EndMessage;
return false;
}
}
}
return true;
}
template <int OpAtomic>
static bool compareRetVals (const deUint32* inputValues, const size_t inputValuesCount, const deUint32 resultValue, const deUint32* returnValues)
{
// as the order of execution is undefined, validation of return values for atomic operations is tricky:
// each inputValue stands for one atomic operation. Iterate through all of
// done operations in time, each time finding one matching current result and un-doing it.
std::vector<bool> operationsUndone (inputValuesCount, false);
deUint32 currentResult = resultValue;
for (size_t operationUndone = 0; operationUndone < inputValuesCount; ++operationUndone)
{
// find which of operations was done at this moment
size_t ndx;
for (ndx = 0; ndx < inputValuesCount; ++ndx)
{
if (operationsUndone[ndx]) continue;
deUint32 previousResult = currentResult;
switch (OpAtomic)
{
// operations are undone here, so the actual opeation is reversed
case OPATOMIC_IADD: previousResult -= inputValues[ndx]; break;
case OPATOMIC_ISUB: previousResult += inputValues[ndx]; break;
case OPATOMIC_IINC: previousResult--; break;
case OPATOMIC_IDEC: previousResult++; break;
default: DE_FATAL("Unsupported OpAtomic type for return value compare");
}
if (previousResult == returnValues[ndx])
{
// found matching operation
currentResult = returnValues[ndx];
operationsUndone[ndx] = true;
break;
}
}
if (ndx == inputValuesCount)
{
// no operation matches the current result value
return false;
}
}
return true;
}
private:
const deUint32 m_numInputElements;
const deUint32 m_numOutputElements;
const OpAtomicType m_opAtomic;
const BufferType m_type;
};
/*--------------------------------------------------------------------*//*!
* \brief Concrete class for an input/output storage buffer object
*//*--------------------------------------------------------------------*/
template<typename E>
class Buffer : public BufferInterface
{
public:
Buffer (const std::vector<E>& elements)
: m_elements(elements)
{}
void getBytes (std::vector<deUint8>& bytes) const
{
const size_t size = m_elements.size() * sizeof(E);
bytes.resize(size);
deMemcpy(&bytes.front(), &m_elements.front(), size);
}
size_t getByteSize (void) const
{
return m_elements.size() * sizeof(E);
}
private:
std::vector<E> m_elements;
};
DE_STATIC_ASSERT(sizeof(tcu::Vec4) == 4 * sizeof(float));
typedef Buffer<float> Float32Buffer;
typedef Buffer<deFloat16> Float16Buffer;
typedef Buffer<deInt64> Int64Buffer;
typedef Buffer<deInt32> Int32Buffer;
typedef Buffer<deInt16> Int16Buffer;
typedef Buffer<deUint16> Uint16Buffer;
typedef Buffer<deInt8> Int8Buffer;
typedef Buffer<deUint32> Uint32Buffer;
typedef Buffer<deUint64> Uint64Buffer;
typedef Buffer<tcu::Vec4> Vec4Buffer;
typedef bool (*ComputeVerifyIOFunc) (const std::vector<BufferSp>& inputs,
const std::vector<AllocationSp>& outputAllocations,
const std::vector<BufferSp>& expectedOutputs,
tcu::TestLog& log);
typedef bool (*ComputeVerifyBinaryFunc) (const ProgramBinary& binary);
/*--------------------------------------------------------------------*//*!
* \brief Specification for a compute shader.
*
* This struct bundles SPIR-V assembly code, input and expected output
* together.
*//*--------------------------------------------------------------------*/
struct ComputeShaderSpec
{
std::string assembly;
std::string entryPoint;
std::vector<BufferSp> inputs;
// Mapping from input index (in the inputs field) to the descriptor type.
std::map<deUint32, VkDescriptorType> inputTypes;
std::vector<BufferSp> outputs;
tcu::IVec3 numWorkGroups;
std::vector<deUint32> specConstants;
BufferSp pushConstants;
std::vector<std::string> extensions;
VulkanFeatures requestedVulkanFeatures;
qpTestResult failResult;
std::string failMessage;
// If null, a default verification will be performed by comparing the memory pointed to by outputAllocations
// and the contents of expectedOutputs. Otherwise the function pointed to by verifyIO will be called.
// If true is returned, then the test case is assumed to have passed, if false is returned, then the test
// case is assumed to have failed. Exact meaning of failure can be customized with failResult.
ComputeVerifyIOFunc verifyIO;
ComputeVerifyBinaryFunc verifyBinary;
SpirvVersion spirvVersion;
bool coherentMemory;
ComputeShaderSpec (void)
: entryPoint ("main")
, pushConstants (DE_NULL)
, requestedVulkanFeatures ()
, failResult (QP_TEST_RESULT_FAIL)
, failMessage ("Output doesn't match with expected")
, verifyIO (DE_NULL)
, verifyBinary (DE_NULL)
, spirvVersion (SPIRV_VERSION_1_0)
, coherentMemory (false)
{}
};
/*--------------------------------------------------------------------*//*!
* \brief Helper functions for SPIR-V assembly shared by various tests
*//*--------------------------------------------------------------------*/
const char* getComputeAsmShaderPreamble (void);
const char* getComputeAsmShaderPreambleWithoutLocalSize (void);
std::string getComputeAsmCommonTypes (std::string blockStorageClass = "Uniform");
const char* getComputeAsmCommonInt64Types (void);
/*--------------------------------------------------------------------*//*!
* Declares two uniform variables (indata, outdata) of type
* "struct { float[] }". Depends on type "f32arr" (for "float[]").
*//*--------------------------------------------------------------------*/
const char* getComputeAsmInputOutputBuffer (void);
/*--------------------------------------------------------------------*//*!
* Declares buffer type and layout for uniform variables indata and
* outdata. Both of them are SSBO bounded to descriptor set 0.
* indata is at binding point 0, while outdata is at 1.
*//*--------------------------------------------------------------------*/
const char* getComputeAsmInputOutputBufferTraits (void);
bool verifyOutput (const std::vector<BufferSp>&,
const std::vector<AllocationSp>& outputAllocs,
const std::vector<BufferSp>& expectedOutputs,
tcu::TestLog& log);
} // SpirVAssembly
} // vkt
#endif // _VKTSPVASMCOMPUTESHADERTESTUTIL_HPP
| 33.892857 | 181 | 0.636459 | [
"object",
"vector"
] |
f5756dd3fdf724b3f011ee8711f05d776e6c1acc | 6,565 | cpp | C++ | examples/tm_mobilefacenet_uint8.cpp | zhouzy-creator/Tengine | fea5c064da7b8ed0e24212dcc65d30fda3c7477c | [
"Apache-2.0"
] | 4,697 | 2017-12-30T12:15:43.000Z | 2022-03-25T08:22:31.000Z | examples/tm_mobilefacenet_uint8.cpp | zhouzy-creator/Tengine | fea5c064da7b8ed0e24212dcc65d30fda3c7477c | [
"Apache-2.0"
] | 943 | 2018-01-02T06:15:00.000Z | 2022-03-31T05:32:32.000Z | examples/tm_mobilefacenet_uint8.cpp | crouchggj/Tengine | 587220f924198966c503c1bd15c83451d22f56ad | [
"Apache-2.0"
] | 1,076 | 2017-12-30T12:15:46.000Z | 2022-03-30T01:28:56.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include <cstdlib>
#include <cstdio>
#include <vector>
#include "common.h"
#include "tengine/c_api.h"
#include "tengine_operations.h"
#define DEFAULT_MEAN1 127.5
#define DEFAULT_MEAN2 127.5
#define DEFAULT_MEAN3 127.5
#define DEFAULT_SCALE1 0.0078
#define DEFAULT_SCALE2 0.0078
#define DEFAULT_SCALE3 0.0078
#define MOBILE_FACE_HEIGHT 112
#define MOBILE_FACE_WIDTH 112
graph_t graph;
tensor_t input_tensor;
tensor_t output_tensor;
int feature_len;
void init(const char* modelfile)
{
/* set runtime options */
struct options opt;
opt.num_thread = 1;
opt.cluster = TENGINE_CLUSTER_ALL;
opt.precision = TENGINE_MODE_UINT8;
opt.affinity = 0x01;
int dims[4] = {1, 3, MOBILE_FACE_HEIGHT, MOBILE_FACE_WIDTH};
init_tengine();
fprintf(stderr, "tengine version: %s\n", get_tengine_version());
graph = create_graph(NULL, "tengine", modelfile);
if (graph == NULL)
{
fprintf(stderr, "graph is nullptr.\n");
}
else
{
fprintf(stderr, "success init graph\n");
}
input_tensor = get_graph_input_tensor(graph, 0, 0);
set_tensor_shape(input_tensor, dims, 4);
/* prerun graph, set work options(num_thread, cluster, precision) */
int rc = prerun_graph_multithread(graph, opt);
output_tensor = get_graph_output_tensor(graph, 0, 0);
get_tensor_shape(output_tensor, dims, 4);
feature_len = dims[1];
fprintf(stderr, "mobilefacenet prerun %d\n", rc);
fprintf(stderr, "mobilefacenet output feature len %d\n", feature_len);
}
void get_input_uint8_data(const char* image_file, uint8_t* input_data, int img_h, int img_w, float* mean, float* scale,
float input_scale, int zero_point)
{
image img = imread_process(image_file, img_w, img_h, mean, scale);
float* image_data = (float*)img.data;
for (int i = 0; i < img_w * img_h * 3; i++)
{
int udata = (round)(image_data[i] / input_scale + zero_point);
if (udata > 255)
udata = 255;
else if (udata < 0)
udata = 0;
input_data[i] = udata;
}
free_image(img);
}
int getFeature(const char* imagefile, float* feature)
{
int height = MOBILE_FACE_HEIGHT;
int width = MOBILE_FACE_WIDTH;
int img_size = height * width * 3;
int dims[] = {1, 3, height, width};
float means[3] = {DEFAULT_MEAN1, DEFAULT_MEAN2, DEFAULT_MEAN3};
float scales[3] = {DEFAULT_SCALE1, DEFAULT_SCALE2, DEFAULT_SCALE3};
std::vector<uint8_t> input_data(img_size);
float input_scale = 0.f;
int input_zero_point = 0;
get_tensor_quant_param(input_tensor, &input_scale, &input_zero_point, 1);
get_input_uint8_data(imagefile, input_data.data(), height, width, means, scales, input_scale, input_zero_point);
set_tensor_buffer(input_tensor, input_data.data(), img_size * sizeof(uint8_t));
if (run_graph(graph, 1) < 0)
{
fprintf(stderr, "run_graph fail");
return -1;
}
/* get the result of classification */
output_tensor = get_graph_output_tensor(graph, 0, 0);
uint8_t* output_u8 = (uint8_t*)get_tensor_buffer(output_tensor);
int output_size = get_tensor_buffer_size(output_tensor);
/* dequant */
float output_scale = 0.f;
int output_zero_point = 0;
get_tensor_quant_param(output_tensor, &output_scale, &output_zero_point, 1);
for (int i = 0; i < output_size; i++)
feature[i] = ((float)output_u8[i] - (float)output_zero_point) * output_scale;
return output_size;
}
void normlize(float* feature, int size)
{
float norm = 0;
for (int i = 0; i < size; ++i)
{
norm += feature[i] * feature[i];
}
for (int i = 0; i < size; ++i)
{
feature[i] /= sqrt(norm);
}
}
void release()
{
release_graph_tensor(input_tensor);
release_graph_tensor(output_tensor);
destroy_graph(graph);
}
void show_usage()
{
fprintf(stderr, "[Usage]: [-h]\n [-m model_file] [-a person_a -b person_b]\n [-t thread_count]\n");
fprintf(stderr, "\nmobilefacenet example: \n ./mobilefacenet -m /path/to/mobilenet.tmfile -a "
"/path/to/person_a.jpg -b /path/to/person_b.jpg\n");
}
int main(int argc, char* argv[])
{
char* model_file = NULL;
char* person_a = NULL;
char* person_b = NULL;
int res;
while ((res = getopt(argc, argv, "m:a:b:h")) != -1)
{
switch (res)
{
case 'm':
model_file = optarg;
break;
case 'a':
person_a = optarg;
break;
case 'b':
person_b = optarg;
break;
case 'h':
show_usage();
return 0;
default:
break;
}
}
/* check files */
if (model_file == NULL)
{
fprintf(stderr, "Error: Tengine model file not specified!\n");
show_usage();
return -1;
}
if (!check_file_exist(model_file) || !check_file_exist(person_a) || !check_file_exist(person_b))
return -1;
init(model_file);
std::vector<float> featurea(feature_len);
std::vector<float> featureb(feature_len);
int outputsizea = getFeature(person_a, featurea.data());
int outputsizeb = getFeature(person_b, featureb.data());
if (outputsizea != feature_len || outputsizeb != feature_len)
{
fprintf(stderr, "getFeature feature out len error");
}
normlize(featurea.data(), feature_len);
normlize(featureb.data(), feature_len);
float sim = 0;
for (int i = 0; i < feature_len; ++i)
{
sim += featurea[i] * featureb[i];
}
fprintf(stderr, "the cosine sim of person_a and person_b is %f\n", sim);
release();
return 0;
} | 28.543478 | 119 | 0.645088 | [
"vector",
"model"
] |
f57583af42ce41190797b49132f1b3275d485b77 | 69,880 | cpp | C++ | src/init.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | src/init.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | src/init.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | // copyright (c) 2009-2010 satoshi nakamoto
// copyright (c) 2009-2014 the moorecoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.
#if defined(have_config_h)
#include "config/moorecoin-config.h"
#endif
#include "init.h"
#include "addrman.h"
#include "amount.h"
#include "checkpoints.h"
#include "compat/sanity.h"
#include "consensus/validation.h"
#include "key.h"
#include "main.h"
#include "miner.h"
#include "net.h"
#include "rpcserver.h"
#include "script/standard.h"
#include "scheduler.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#ifdef enable_wallet
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#endif
#include <stdint.h>
#include <stdio.h>
#ifndef win32
#include <signal.h>
#endif
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
using namespace std;
#ifdef enable_wallet
cwallet* pwalletmain = null;
#endif
bool ffeeestimatesinitialized = false;
#ifdef win32
// win32 leveldb doesn't use filedescriptors, and the ones used for
// accessing block files don't count towards the fd_set size limit
// anyway.
#define min_core_filedescriptors 0
#else
#define min_core_filedescriptors 150
#endif
/** used to pass flags to the bind() function */
enum bindflags {
bf_none = 0,
bf_explicit = (1u << 0),
bf_report_error = (1u << 1),
bf_whitelist = (1u << 2),
};
static const char* fee_estimates_filename="fee_estimates.dat";
cclientuiinterface uiinterface; // declared but not defined in ui_interface.h
//////////////////////////////////////////////////////////////////////////////
//
// shutdown
//
//
// thread management and startup/shutdown:
//
// the network-processing threads are all part of a thread group
// created by appinit() or the qt main() function.
//
// a clean exit happens when startshutdown() or the sigterm
// signal handler sets frequestshutdown, which triggers
// the detectshutdownthread(), which interrupts the main thread group.
// detectshutdownthread() then exits, which causes appinit() to
// continue (it .joins the shutdown thread).
// shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// note that if running -daemon the parent process returns from appinit2
// before adding any threads to the threadgroup, so .join_all() returns
// immediately and the parent exits from main().
//
// shutdown for qt is very similar, only it uses a qtimer to detect
// frequestshutdown getting set, and then does the normal qt
// shutdown thing.
//
volatile bool frequestshutdown = false;
void startshutdown()
{
frequestshutdown = true;
}
bool shutdownrequested()
{
return frequestshutdown;
}
class ccoinsviewerrorcatcher : public ccoinsviewbacked
{
public:
ccoinsviewerrorcatcher(ccoinsview* view) : ccoinsviewbacked(view) {}
bool getcoins(const uint256 &txid, ccoins &coins) const {
try {
return ccoinsviewbacked::getcoins(txid, coins);
} catch(const std::runtime_error& e) {
uiinterface.threadsafemessagebox(_("error reading from database, shutting down."), "", cclientuiinterface::msg_error);
logprintf("error reading from database: %s\n", e.what());
// starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpretation. just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
abort();
}
}
// writes do not need similar protection, as failure to write is handled by the caller.
};
static ccoinsviewdb *pcoinsdbview = null;
static ccoinsviewerrorcatcher *pcoinscatcher = null;
void shutdown()
{
logprintf("%s: in progress...\n", __func__);
static ccriticalsection cs_shutdown;
try_lock(cs_shutdown, lockshutdown);
if (!lockshutdown)
return;
/// note: shutdown() must be able to handle cases in which appinit2() failed part of the way,
/// for example if the data directory was found to be locked.
/// be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
renamethread("moorecoin-shutoff");
mempool.addtransactionsupdated(1);
stoprpcthreads();
#ifdef enable_wallet
if (pwalletmain)
pwalletmain->flush(false);
generatemoorecoins(false, null, 0);
#endif
stopnode();
unregisternodesignals(getnodesignals());
if (ffeeestimatesinitialized)
{
boost::filesystem::path est_path = getdatadir() / fee_estimates_filename;
cautofile est_fileout(fopen(est_path.string().c_str(), "wb"), ser_disk, client_version);
if (!est_fileout.isnull())
mempool.writefeeestimates(est_fileout);
else
logprintf("%s: failed to write fee estimates to %s\n", __func__, est_path.string());
ffeeestimatesinitialized = false;
}
{
lock(cs_main);
if (pcoinstip != null) {
flushstatetodisk();
}
delete pcoinstip;
pcoinstip = null;
delete pcoinscatcher;
pcoinscatcher = null;
delete pcoinsdbview;
pcoinsdbview = null;
delete pblocktree;
pblocktree = null;
}
#ifdef enable_wallet
if (pwalletmain)
pwalletmain->flush(true);
#endif
#ifndef win32
try {
boost::filesystem::remove(getpidfile());
} catch (const boost::filesystem::filesystem_error& e) {
logprintf("%s: unable to remove pidfile: %s\n", __func__, e.what());
}
#endif
unregisterallvalidationinterfaces();
#ifdef enable_wallet
delete pwalletmain;
pwalletmain = null;
#endif
ecc_stop();
logprintf("%s: done\n", __func__);
}
/**
* signal handlers are very limited in what they are allowed to do, so:
*/
void handlesigterm(int)
{
frequestshutdown = true;
}
void handlesighup(int)
{
freopendebuglog = true;
}
bool static initerror(const std::string &str)
{
uiinterface.threadsafemessagebox(str, "", cclientuiinterface::msg_error);
return false;
}
bool static initwarning(const std::string &str)
{
uiinterface.threadsafemessagebox(str, "", cclientuiinterface::msg_warning);
return true;
}
bool static bind(const cservice &addr, unsigned int flags) {
if (!(flags & bf_explicit) && islimited(addr))
return false;
std::string strerror;
if (!bindlistenport(addr, strerror, (flags & bf_whitelist) != 0)) {
if (flags & bf_report_error)
return initerror(strerror);
return false;
}
return true;
}
void onrpcstopped()
{
cvblockchange.notify_all();
logprint("rpc", "rpc stopped.\n");
}
void onrpcprecommand(const crpccommand& cmd)
{
// observe safe mode
string strwarning = getwarnings("rpc");
if (strwarning != "" && !getboolarg("-disablesafemode", false) &&
!cmd.oksafemode)
throw jsonrpcerror(rpc_forbidden_by_safe_mode, string("safe mode: ") + strwarning);
}
std::string helpmessage(helpmessagemode mode)
{
const bool showdebug = getboolarg("-help-debug", false);
// when adding new options to the categories, please keep and ensure alphabetical ordering.
// do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators.
string strusage = helpmessagegroup(_("options:"));
strusage += helpmessageopt("-?", _("this help message"));
strusage += helpmessageopt("-alerts", strprintf(_("receive and display p2p network alerts (default: %u)"), default_alerts));
strusage += helpmessageopt("-alertnotify=<cmd>", _("execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
strusage += helpmessageopt("-blocknotify=<cmd>", _("execute command when the best block changes (%s in cmd is replaced by block hash)"));
strusage += helpmessageopt("-checkblocks=<n>", strprintf(_("how many blocks to check at startup (default: %u, 0 = all)"), 288));
strusage += helpmessageopt("-checklevel=<n>", strprintf(_("how thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
strusage += helpmessageopt("-conf=<file>", strprintf(_("specify configuration file (default: %s)"), "moorecoin.conf"));
if (mode == hmm_moorecoind)
{
#if !defined(win32)
strusage += helpmessageopt("-daemon", _("run in the background as a daemon and accept commands"));
#endif
}
strusage += helpmessageopt("-datadir=<dir>", _("specify data directory"));
strusage += helpmessageopt("-dbcache=<n>", strprintf(_("set database cache size in megabytes (%d to %d, default: %d)"), nmindbcache, nmaxdbcache, ndefaultdbcache));
strusage += helpmessageopt("-loadblock=<file>", _("imports blocks from external blk000??.dat file") + " " + _("on startup"));
strusage += helpmessageopt("-maxorphantx=<n>", strprintf(_("keep at most <n> unconnectable transactions in memory (default: %u)"), default_max_orphan_transactions));
strusage += helpmessageopt("-par=<n>", strprintf(_("set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
-(int)boost::thread::hardware_concurrency(), max_scriptcheck_threads, default_scriptcheck_threads));
#ifndef win32
strusage += helpmessageopt("-pid=<file>", strprintf(_("specify pid file (default: %s)"), "moorecoind.pid"));
#endif
strusage += helpmessageopt("-prune=<n>", strprintf(_("reduce storage requirements by pruning (deleting) old blocks. this mode disables wallet support and is incompatible with -txindex. "
"warning: reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, >%u = target size in mib to use for block files)"), min_disk_space_for_block_files / 1024 / 1024));
strusage += helpmessageopt("-reindex", _("rebuild block chain index from current blk000??.dat files on startup"));
#if !defined(win32)
strusage += helpmessageopt("-sysperms", _("create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
#endif
strusage += helpmessageopt("-txindex", strprintf(_("maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
strusage += helpmessagegroup(_("connection options:"));
strusage += helpmessageopt("-addnode=<ip>", _("add a node to connect to and attempt to keep the connection open"));
strusage += helpmessageopt("-banscore=<n>", strprintf(_("threshold for disconnecting misbehaving peers (default: %u)"), 100));
strusage += helpmessageopt("-bantime=<n>", strprintf(_("number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
strusage += helpmessageopt("-bind=<addr>", _("bind to given address and always listen on it. use [host]:port notation for ipv6"));
strusage += helpmessageopt("-connect=<ip>", _("connect only to the specified node(s)"));
strusage += helpmessageopt("-discover", _("discover own ip addresses (default: 1 when listening and no -externalip or -proxy)"));
strusage += helpmessageopt("-dns", _("allow dns lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
strusage += helpmessageopt("-dnsseed", _("query for peer addresses via dns lookup, if low on addresses (default: 1 unless -connect)"));
strusage += helpmessageopt("-externalip=<ip>", _("specify your own public address"));
strusage += helpmessageopt("-forcednsseed", strprintf(_("always query for peer addresses via dns lookup (default: %u)"), 0));
strusage += helpmessageopt("-listen", _("accept connections from outside (default: 1 if no -proxy or -connect)"));
strusage += helpmessageopt("-maxconnections=<n>", strprintf(_("maintain at most <n> connections to peers (default: %u)"), 125));
strusage += helpmessageopt("-maxreceivebuffer=<n>", strprintf(_("maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
strusage += helpmessageopt("-maxsendbuffer=<n>", strprintf(_("maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
strusage += helpmessageopt("-onion=<ip:port>", strprintf(_("use separate socks5 proxy to reach peers via tor hidden services (default: %s)"), "-proxy"));
strusage += helpmessageopt("-onlynet=<net>", _("only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
strusage += helpmessageopt("-permitbaremultisig", strprintf(_("relay non-p2sh multisig (default: %u)"), 1));
strusage += helpmessageopt("-port=<port>", strprintf(_("listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333));
strusage += helpmessageopt("-proxy=<ip:port>", _("connect through socks5 proxy"));
strusage += helpmessageopt("-proxyrandomize", strprintf(_("randomize credentials for every proxy connection. this enables tor stream isolation (default: %u)"), 1));
strusage += helpmessageopt("-seednode=<ip>", _("connect to a node to retrieve peer addresses, and disconnect"));
strusage += helpmessageopt("-timeout=<n>", strprintf(_("specify connection timeout in milliseconds (minimum: 1, default: %d)"), default_connect_timeout));
#ifdef use_upnp
#if use_upnp
strusage += helpmessageopt("-upnp", _("use upnp to map the listening port (default: 1 when listening and no -proxy)"));
#else
strusage += helpmessageopt("-upnp", strprintf(_("use upnp to map the listening port (default: %u)"), 0));
#endif
#endif
strusage += helpmessageopt("-whitebind=<addr>", _("bind to given address and whitelist peers connecting to it. use [host]:port notation for ipv6"));
strusage += helpmessageopt("-whitelist=<netmask>", _("whitelist peers connecting from the given netmask or ip address. can be specified multiple times.") +
" " + _("whitelisted peers cannot be dos banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
#ifdef enable_wallet
strusage += helpmessagegroup(_("wallet options:"));
strusage += helpmessageopt("-disablewallet", _("do not load the wallet and disable wallet rpc calls"));
strusage += helpmessageopt("-keypool=<n>", strprintf(_("set key pool size to <n> (default: %u)"), 100));
if (showdebug)
strusage += helpmessageopt("-mintxfee=<amt>", strprintf("fees (in btc/kb) smaller than this are considered zero fee for transaction creation (default: %s)",
formatmoney(cwallet::mintxfee.getfeeperk())));
strusage += helpmessageopt("-paytxfee=<amt>", strprintf(_("fee (in btc/kb) to add to transactions you send (default: %s)"), formatmoney(paytxfee.getfeeperk())));
strusage += helpmessageopt("-rescan", _("rescan the block chain for missing wallet transactions") + " " + _("on startup"));
strusage += helpmessageopt("-salvagewallet", _("attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
strusage += helpmessageopt("-sendfreetransactions", strprintf(_("send transactions as zero-fee transactions if possible (default: %u)"), 0));
strusage += helpmessageopt("-spendzeroconfchange", strprintf(_("spend unconfirmed change when sending transactions (default: %u)"), 1));
strusage += helpmessageopt("-txconfirmtarget=<n>", strprintf(_("if paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), default_tx_confirm_target));
strusage += helpmessageopt("-maxtxfee=<amt>", strprintf(_("maximum total fees to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)"),
formatmoney(maxtxfee)));
strusage += helpmessageopt("-upgradewallet", _("upgrade wallet to latest format") + " " + _("on startup"));
strusage += helpmessageopt("-wallet=<file>", _("specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
strusage += helpmessageopt("-walletbroadcast", _("make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
strusage += helpmessageopt("-walletnotify=<cmd>", _("execute command when a wallet transaction changes (%s in cmd is replaced by txid)"));
strusage += helpmessageopt("-zapwallettxes=<mode>", _("delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
" " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
#endif
strusage += helpmessagegroup(_("debugging/testing options:"));
if (showdebug)
{
strusage += helpmessageopt("-checkpoints", strprintf("disable expensive verification for known chain history (default: %u)", 1));
strusage += helpmessageopt("-dblogsize=<n>", strprintf("flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
strusage += helpmessageopt("-disablesafemode", strprintf("disable safemode, override a real safe mode event (default: %u)", 0));
strusage += helpmessageopt("-testsafemode", strprintf("force safe mode (default: %u)", 0));
strusage += helpmessageopt("-dropmessagestest=<n>", "randomly drop 1 of every <n> network messages");
strusage += helpmessageopt("-fuzzmessagestest=<n>", "randomly fuzz 1 of every <n> network messages");
strusage += helpmessageopt("-flushwallet", strprintf("run a thread to flush wallet periodically (default: %u)", 1));
strusage += helpmessageopt("-stopafterblockimport", strprintf("stop running after importing blocks from disk (default: %u)", 0));
}
string debugcategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, net, proxy, prune"; // don't translate these and qt below
if (mode == hmm_moorecoin_qt)
debugcategories += ", qt";
strusage += helpmessageopt("-debug=<category>", strprintf(_("output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
_("if <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugcategories + ".");
#ifdef enable_wallet
strusage += helpmessageopt("-gen", strprintf(_("generate coins (default: %u)"), 0));
strusage += helpmessageopt("-genproclimit=<n>", strprintf(_("set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
#endif
strusage += helpmessageopt("-help-debug", _("show all debugging options (usage: --help -help-debug)"));
strusage += helpmessageopt("-logips", strprintf(_("include ip addresses in debug output (default: %u)"), 0));
strusage += helpmessageopt("-logtimestamps", strprintf(_("prepend debug output with timestamp (default: %u)"), 1));
if (showdebug)
{
strusage += helpmessageopt("-limitfreerelay=<n>", strprintf("continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
strusage += helpmessageopt("-relaypriority", strprintf("require high priority for relaying free or low-fee transactions (default: %u)", 1));
strusage += helpmessageopt("-maxsigcachesize=<n>", strprintf("limit size of signature cache to <n> entries (default: %u)", 50000));
}
strusage += helpmessageopt("-minrelaytxfee=<amt>", strprintf(_("fees (in btc/kb) smaller than this are considered zero fee for relaying (default: %s)"), formatmoney(::minrelaytxfee.getfeeperk())));
strusage += helpmessageopt("-printtoconsole", _("send trace/debug info to console instead of debug.log file"));
if (showdebug)
{
strusage += helpmessageopt("-printpriority", strprintf("log transaction priority and fee per kb when mining blocks (default: %u)", 0));
strusage += helpmessageopt("-privdb", strprintf("sets the db_private flag in the wallet db environment (default: %u)", 1));
strusage += helpmessageopt("-regtest", "enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"this is intended for regression testing tools and app development.");
}
strusage += helpmessageopt("-shrinkdebugfile", _("shrink debug.log file on client startup (default: 1 when no -debug)"));
strusage += helpmessageopt("-testnet", _("use the test network"));
strusage += helpmessagegroup(_("node relay options:"));
strusage += helpmessageopt("-datacarrier", strprintf(_("relay and mine data carrier transactions (default: %u)"), 1));
strusage += helpmessageopt("-datacarriersize", strprintf(_("maximum size of data in data carrier transactions we relay and mine (default: %u)"), max_op_return_relay));
strusage += helpmessagegroup(_("block creation options:"));
strusage += helpmessageopt("-blockminsize=<n>", strprintf(_("set minimum block size in bytes (default: %u)"), 0));
strusage += helpmessageopt("-blockmaxsize=<n>", strprintf(_("set maximum block size in bytes (default: %d)"), default_block_max_size));
strusage += helpmessageopt("-blockprioritysize=<n>", strprintf(_("set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), default_block_priority_size));
if (showdebug)
strusage += helpmessageopt("-blockversion=<n>", strprintf("override block version to test forking scenarios (default: %d)", (int)cblock::current_version));
strusage += helpmessagegroup(_("rpc server options:"));
strusage += helpmessageopt("-server", _("accept command line and json-rpc commands"));
strusage += helpmessageopt("-rest", strprintf(_("accept public rest requests (default: %u)"), 0));
strusage += helpmessageopt("-rpcbind=<addr>", _("bind to given address to listen for json-rpc connections. use [host]:port notation for ipv6. this option can be specified multiple times (default: bind to all interfaces)"));
strusage += helpmessageopt("-rpcuser=<user>", _("username for json-rpc connections"));
strusage += helpmessageopt("-rpcpassword=<pw>", _("password for json-rpc connections"));
strusage += helpmessageopt("-rpcport=<port>", strprintf(_("listen for json-rpc connections on <port> (default: %u or testnet: %u)"), 8332, 18332));
strusage += helpmessageopt("-rpcallowip=<ip>", _("allow json-rpc connections from specified source. valid for <ip> are a single ip (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/cidr (e.g. 1.2.3.4/24). this option can be specified multiple times"));
strusage += helpmessageopt("-rpcthreads=<n>", strprintf(_("set the number of threads to service rpc calls (default: %d)"), 4));
strusage += helpmessageopt("-rpckeepalive", strprintf(_("rpc support for http persistent connections (default: %d)"), 1));
strusage += helpmessagegroup(_("rpc ssl options: (see the moorecoin wiki for ssl setup instructions)"));
strusage += helpmessageopt("-rpcssl", _("use openssl (https) for json-rpc connections"));
strusage += helpmessageopt("-rpcsslcertificatechainfile=<file.cert>", strprintf(_("server certificate file (default: %s)"), "server.cert"));
strusage += helpmessageopt("-rpcsslprivatekeyfile=<file.pem>", strprintf(_("server private key (default: %s)"), "server.pem"));
strusage += helpmessageopt("-rpcsslciphers=<ciphers>", strprintf(_("acceptable ciphers (default: %s)"), "tlsv1.2+high:tlsv1+high:!sslv2:!anull:!enull:!3des:@strength"));
if (mode == hmm_moorecoin_qt)
{
strusage += helpmessagegroup(_("ui options:"));
if (showdebug) {
strusage += helpmessageopt("-allowselfsignedrootcertificates", "allow self signed root certificates (default: 0)");
}
strusage += helpmessageopt("-choosedatadir", _("choose data directory on startup (default: 0)"));
strusage += helpmessageopt("-lang=<lang>", _("set language, for example \"de_de\" (default: system locale)"));
strusage += helpmessageopt("-min", _("start minimized"));
strusage += helpmessageopt("-rootcertificates=<file>", _("set ssl root certificates for payment request (default: -system-)"));
strusage += helpmessageopt("-splash", _("show splash screen on startup (default: 1)"));
}
return strusage;
}
std::string licenseinfo()
{
return formatparagraph(strprintf(_("copyright (c) 2009-%i the moorecoin core developers"), copyright_year)) + "\n" +
"\n" +
formatparagraph(_("this is experimental software.")) + "\n" +
"\n" +
formatparagraph(_("distributed under the mit software license, see the accompanying file copying or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
"\n" +
formatparagraph(_("this product includes software developed by the openssl project for use in the openssl toolkit <https://www.openssl.org/> and cryptographic software written by eric young and upnp software written by thomas bernard.")) +
"\n";
}
static void blocknotifycallback(const uint256& hashnewtip)
{
std::string strcmd = getarg("-blocknotify", "");
boost::replace_all(strcmd, "%s", hashnewtip.gethex());
boost::thread t(runcommand, strcmd); // thread runs free
}
struct cimportingnow
{
cimportingnow() {
assert(fimporting == false);
fimporting = true;
}
~cimportingnow() {
assert(fimporting == true);
fimporting = false;
}
};
// if we're using -prune with -reindex, then delete block files that will be ignored by the
// reindex. since reindexing works by starting at block file 0 and looping until a blockfile
// is missing, do the same here to delete any later block files after a gap. also delete all
// rev files since they'll be rewritten by the reindex anyway. this ensures that vinfoblockfile
// is in sync with what's actually on disk by the time we start downloading, so that pruning
// works correctly.
void cleanupblockrevfiles()
{
using namespace boost::filesystem;
map<string, path> mapblockfiles;
// glob all blk?????.dat and rev?????.dat files from the blocks directory.
// remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
logprintf("removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
path blocksdir = getdatadir() / "blocks";
for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
if (is_regular_file(*it) &&
it->path().filename().string().length() == 12 &&
it->path().filename().string().substr(8,4) == ".dat")
{
if (it->path().filename().string().substr(0,3) == "blk")
mapblockfiles[it->path().filename().string().substr(3,5)] = it->path();
else if (it->path().filename().string().substr(0,3) == "rev")
remove(it->path());
}
}
// remove all block files that aren't part of a contiguous set starting at
// zero by walking the ordered map (keys are block file indices) by
// keeping a separate counter. once we hit a gap (or if 0 doesn't exist)
// start removing block files.
int ncontigcounter = 0;
boost_foreach(const pairtype(string, path)& item, mapblockfiles) {
if (atoi(item.first) == ncontigcounter) {
ncontigcounter++;
continue;
}
remove(item.second);
}
}
void threadimport(std::vector<boost::filesystem::path> vimportfiles)
{
renamethread("moorecoin-loadblk");
// -reindex
if (freindex) {
cimportingnow imp;
int nfile = 0;
while (true) {
cdiskblockpos pos(nfile, 0);
if (!boost::filesystem::exists(getblockposfilename(pos, "blk")))
break; // no block files left to reindex
file *file = openblockfile(pos, true);
if (!file)
break; // this error is logged in openblockfile
logprintf("reindexing block file blk%05u.dat...\n", (unsigned int)nfile);
loadexternalblockfile(file, &pos);
nfile++;
}
pblocktree->writereindexing(false);
freindex = false;
logprintf("reindexing finished\n");
// to avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
initblockindex();
}
// hardcoded $datadir/bootstrap.dat
boost::filesystem::path pathbootstrap = getdatadir() / "bootstrap.dat";
if (boost::filesystem::exists(pathbootstrap)) {
file *file = fopen(pathbootstrap.string().c_str(), "rb");
if (file) {
cimportingnow imp;
boost::filesystem::path pathbootstrapold = getdatadir() / "bootstrap.dat.old";
logprintf("importing bootstrap.dat...\n");
loadexternalblockfile(file);
renameover(pathbootstrap, pathbootstrapold);
} else {
logprintf("warning: could not open bootstrap file %s\n", pathbootstrap.string());
}
}
// -loadblock=
boost_foreach(const boost::filesystem::path& path, vimportfiles) {
file *file = fopen(path.string().c_str(), "rb");
if (file) {
cimportingnow imp;
logprintf("importing blocks file %s...\n", path.string());
loadexternalblockfile(file);
} else {
logprintf("warning: could not open blocks file %s\n", path.string());
}
}
if (getboolarg("-stopafterblockimport", false)) {
logprintf("stopping after block import\n");
startshutdown();
}
}
/** sanity checks
* ensure that moorecoin is running in a usable environment with all
* necessary library support.
*/
bool initsanitycheck(void)
{
if(!ecc_initsanitycheck()) {
initerror("openssl appears to lack support for elliptic curve cryptography. for more "
"information, visit https://en.moorecoin.it/wiki/openssl_and_ec_libraries");
return false;
}
if (!glibc_sanity_test() || !glibcxx_sanity_test())
return false;
return true;
}
/** initialize moorecoin.
* @pre parameters should be parsed and config file should be read.
*/
bool appinit2(boost::thread_group& threadgroup, cscheduler& scheduler)
{
// ********************************************************* step 1: setup
#ifdef _msc_ver
// turn off microsoft heap dump noise
_crtsetreportmode(_crt_warn, _crtdbg_mode_file);
_crtsetreportfile(_crt_warn, createfilea("nul", generic_write, 0, null, open_existing, 0, 0));
#endif
#if _msc_ver >= 1400
// disable confusing "helpful" text message on abort, ctrl-c
_set_abort_behavior(0, _write_abort_msg | _call_reportfault);
#endif
#ifdef win32
// enable data execution prevention (dep)
// minimum supported os versions: winxp sp3, winvista >= sp1, win server 2008
// a failure is non-critical and needs no further attention!
#ifndef process_dep_enable
// we define this here, because gccs winbase.h limits this to _win32_winnt >= 0x0601 (windows 7),
// which is not correct. can be removed, when gccs winbase.h is fixed!
#define process_dep_enable 0x00000001
#endif
typedef bool (winapi *psetprocdeppol)(dword);
psetprocdeppol setprocdeppol = (psetprocdeppol)getprocaddress(getmodulehandlea("kernel32.dll"), "setprocessdeppolicy");
if (setprocdeppol != null) setprocdeppol(process_dep_enable);
// initialize windows sockets
wsadata wsadata;
int ret = wsastartup(makeword(2,2), &wsadata);
if (ret != no_error || lobyte(wsadata.wversion ) != 2 || hibyte(wsadata.wversion) != 2)
{
return initerror(strprintf("error: winsock library failed to start (wsastartup returned error %d)", ret));
}
#endif
#ifndef win32
if (getboolarg("-sysperms", false)) {
#ifdef enable_wallet
if (!getboolarg("-disablewallet", false))
return initerror("error: -sysperms is not allowed in combination with enabled wallet functionality");
#endif
} else {
umask(077);
}
// clean shutdown on sigterm
struct sigaction sa;
sa.sa_handler = handlesigterm;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(sigterm, &sa, null);
sigaction(sigint, &sa, null);
// reopen debug.log on sighup
struct sigaction sa_hup;
sa_hup.sa_handler = handlesighup;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(sighup, &sa_hup, null);
#if defined (__svr4) && defined (__sun)
// ignore sigpipe on solaris
signal(sigpipe, sig_ign);
#endif
#endif
// ********************************************************* step 2: parameter interactions
const cchainparams& chainparams = params();
// set this early so that parameter interactions go to console
fprinttoconsole = getboolarg("-printtoconsole", false);
flogtimestamps = getboolarg("-logtimestamps", true);
flogips = getboolarg("-logips", false);
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (mapargs.count("-bind")) {
if (softsetboolarg("-listen", true))
logprintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
if (mapargs.count("-whitebind")) {
if (softsetboolarg("-listen", true))
logprintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
}
if (mapargs.count("-connect") && mapmultiargs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via dns, or listen by default
if (softsetboolarg("-dnsseed", false))
logprintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
if (softsetboolarg("-listen", false))
logprintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
}
if (mapargs.count("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
if (softsetboolarg("-listen", false))
logprintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use upnp when a proxy is set. the user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
if (softsetboolarg("-upnp", false))
logprintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
if (softsetboolarg("-discover", false))
logprintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
}
if (!getboolarg("-listen", default_listen)) {
// do not map ports or try to retrieve public ip when not listening (pointless)
if (softsetboolarg("-upnp", false))
logprintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
if (softsetboolarg("-discover", false))
logprintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
}
if (mapargs.count("-externalip")) {
// if an explicit public ip is specified, do not try to find others
if (softsetboolarg("-discover", false))
logprintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
}
if (getboolarg("-salvagewallet", false)) {
// rewrite just private keys: rescan to find transactions
if (softsetboolarg("-rescan", true))
logprintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
}
// -zapwallettx implies a rescan
if (getboolarg("-zapwallettxes", false)) {
if (softsetboolarg("-rescan", true))
logprintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
}
// make sure enough file descriptors are available
int nbind = std::max((int)mapargs.count("-bind") + (int)mapargs.count("-whitebind"), 1);
nmaxconnections = getarg("-maxconnections", 125);
nmaxconnections = std::max(std::min(nmaxconnections, (int)(fd_setsize - nbind - min_core_filedescriptors)), 0);
int nfd = raisefiledescriptorlimit(nmaxconnections + min_core_filedescriptors);
if (nfd < min_core_filedescriptors)
return initerror(_("not enough file descriptors available."));
if (nfd - min_core_filedescriptors < nmaxconnections)
nmaxconnections = nfd - min_core_filedescriptors;
// if using block pruning, then disable txindex
if (getarg("-prune", 0)) {
if (getboolarg("-txindex", false))
return initerror(_("prune mode is incompatible with -txindex."));
#ifdef enable_wallet
if (getboolarg("-rescan", false)) {
return initerror(_("rescans are not possible in pruned mode. you will need to use -reindex which will download the whole blockchain again."));
}
#endif
}
// ********************************************************* step 3: parameter-to-internal-flags
fdebug = !mapmultiargs["-debug"].empty();
// special-case: if -debug=0/-nodebug is set, turn off debugging messages
const vector<string>& categories = mapmultiargs["-debug"];
if (getboolarg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
fdebug = false;
// check for -debugnet
if (getboolarg("-debugnet", false))
initwarning(_("warning: unsupported argument -debugnet ignored, use -debug=net."));
// check for -socks - as this is a privacy risk to continue, exit here
if (mapargs.count("-socks"))
return initerror(_("error: unsupported argument -socks found. setting socks version isn't possible anymore, only socks5 proxies are supported."));
// check for -tor - as this is a privacy risk to continue, exit here
if (getboolarg("-tor", false))
return initerror(_("error: unsupported argument -tor found, use -onion."));
if (getboolarg("-benchmark", false))
initwarning(_("warning: unsupported argument -benchmark ignored, use -debug=bench."));
// checkmempool and checkblockindex default to true in regtest mode
mempool.setsanitycheck(getboolarg("-checkmempool", chainparams.defaultconsistencychecks()));
fcheckblockindex = getboolarg("-checkblockindex", chainparams.defaultconsistencychecks());
fcheckpointsenabled = getboolarg("-checkpoints", true);
// -par=0 means autodetect, but nscriptcheckthreads==0 means no concurrency
nscriptcheckthreads = getarg("-par", default_scriptcheck_threads);
if (nscriptcheckthreads <= 0)
nscriptcheckthreads += boost::thread::hardware_concurrency();
if (nscriptcheckthreads <= 1)
nscriptcheckthreads = 0;
else if (nscriptcheckthreads > max_scriptcheck_threads)
nscriptcheckthreads = max_scriptcheck_threads;
fserver = getboolarg("-server", false);
// block pruning; get the amount of disk space (in mb) to allot for block & undo files
int64_t nsignedprunetarget = getarg("-prune", 0) * 1024 * 1024;
if (nsignedprunetarget < 0) {
return initerror(_("prune cannot be configured with a negative value."));
}
nprunetarget = (uint64_t) nsignedprunetarget;
if (nprunetarget) {
if (nprunetarget < min_disk_space_for_block_files) {
return initerror(strprintf(_("prune configured below the minimum of %d mb. please use a higher number."), min_disk_space_for_block_files / 1024 / 1024));
}
logprintf("prune configured to target %umib on disk for block and undo files.\n", nprunetarget / 1024 / 1024);
fprunemode = true;
}
#ifdef enable_wallet
bool fdisablewallet = getboolarg("-disablewallet", false);
#endif
nconnecttimeout = getarg("-timeout", default_connect_timeout);
if (nconnecttimeout <= 0)
nconnecttimeout = default_connect_timeout;
// fee-per-kilobyte amount considered the same as "free"
// if you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. it should be set above the real
// cost to you of processing a transaction.
if (mapargs.count("-minrelaytxfee"))
{
camount n = 0;
if (parsemoney(mapargs["-minrelaytxfee"], n) && n > 0)
::minrelaytxfee = cfeerate(n);
else
return initerror(strprintf(_("invalid amount for -minrelaytxfee=<amount>: '%s'"), mapargs["-minrelaytxfee"]));
}
#ifdef enable_wallet
if (mapargs.count("-mintxfee"))
{
camount n = 0;
if (parsemoney(mapargs["-mintxfee"], n) && n > 0)
cwallet::mintxfee = cfeerate(n);
else
return initerror(strprintf(_("invalid amount for -mintxfee=<amount>: '%s'"), mapargs["-mintxfee"]));
}
if (mapargs.count("-paytxfee"))
{
camount nfeeperk = 0;
if (!parsemoney(mapargs["-paytxfee"], nfeeperk))
return initerror(strprintf(_("invalid amount for -paytxfee=<amount>: '%s'"), mapargs["-paytxfee"]));
if (nfeeperk > nhightransactionfeewarning)
initwarning(_("warning: -paytxfee is set very high! this is the transaction fee you will pay if you send a transaction."));
paytxfee = cfeerate(nfeeperk, 1000);
if (paytxfee < ::minrelaytxfee)
{
return initerror(strprintf(_("invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
mapargs["-paytxfee"], ::minrelaytxfee.tostring()));
}
}
if (mapargs.count("-maxtxfee"))
{
camount nmaxfee = 0;
if (!parsemoney(mapargs["-maxtxfee"], nmaxfee))
return initerror(strprintf(_("invalid amount for -maxtxfee=<amount>: '%s'"), mapargs["-maptxfee"]));
if (nmaxfee > nhightransactionmaxfeewarning)
initwarning(_("warning: -maxtxfee is set very high! fees this large could be paid on a single transaction."));
maxtxfee = nmaxfee;
if (cfeerate(maxtxfee, 1000) < ::minrelaytxfee)
{
return initerror(strprintf(_("invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
mapargs["-maxtxfee"], ::minrelaytxfee.tostring()));
}
}
ntxconfirmtarget = getarg("-txconfirmtarget", default_tx_confirm_target);
bspendzeroconfchange = getboolarg("-spendzeroconfchange", true);
fsendfreetransactions = getboolarg("-sendfreetransactions", false);
std::string strwalletfile = getarg("-wallet", "wallet.dat");
#endif // enable_wallet
fisbaremultisigstd = getboolarg("-permitbaremultisig", true);
nmaxdatacarrierbytes = getarg("-datacarriersize", nmaxdatacarrierbytes);
falerts = getboolarg("-alerts", default_alerts);
// ********************************************************* step 4: application initialization: dir lock, daemonize, pidfile, debug log
// initialize elliptic curve code
ecc_start();
// sanity check
if (!initsanitycheck())
return initerror(_("initialization sanity check failed. moorecoin core is shutting down."));
std::string strdatadir = getdatadir().string();
#ifdef enable_wallet
// wallet file must be a plain filename without a directory
if (strwalletfile != boost::filesystem::basename(strwalletfile) + boost::filesystem::extension(strwalletfile))
return initerror(strprintf(_("wallet %s resides outside data directory %s"), strwalletfile, strdatadir));
#endif
// make sure only a single moorecoin process is using the data directory.
boost::filesystem::path pathlockfile = getdatadir() / ".lock";
file* file = fopen(pathlockfile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
try {
static boost::interprocess::file_lock lock(pathlockfile.string().c_str());
if (!lock.try_lock())
return initerror(strprintf(_("cannot obtain a lock on data directory %s. moorecoin core is probably already running."), strdatadir));
} catch(const boost::interprocess::interprocess_exception& e) {
return initerror(strprintf(_("cannot obtain a lock on data directory %s. moorecoin core is probably already running.") + " %s.", strdatadir, e.what()));
}
#ifndef win32
createpidfile(getpidfile(), getpid());
#endif
if (getboolarg("-shrinkdebugfile", !fdebug))
shrinkdebugfile();
logprintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
logprintf("moorecoin version %s (%s)\n", formatfullversion(), client_date);
logprintf("using openssl version %s\n", ssleay_version(ssleay_version));
#ifdef enable_wallet
logprintf("using berkeleydb version %s\n", dbenv::version(0, 0, 0));
#endif
if (!flogtimestamps)
logprintf("startup time: %s\n", datetimestrformat("%y-%m-%d %h:%m:%s", gettime()));
logprintf("default data directory %s\n", getdefaultdatadir().string());
logprintf("using data directory %s\n", strdatadir);
logprintf("using config file %s\n", getconfigfile().string());
logprintf("using at most %i connections (%i file descriptors available)\n", nmaxconnections, nfd);
std::ostringstream strerrors;
logprintf("using %u threads for script verification\n", nscriptcheckthreads);
if (nscriptcheckthreads) {
for (int i=0; i<nscriptcheckthreads-1; i++)
threadgroup.create_thread(&threadscriptcheck);
}
// start the lightweight task scheduler thread
cscheduler::function serviceloop = boost::bind(&cscheduler::servicequeue, &scheduler);
threadgroup.create_thread(boost::bind(&tracethread<cscheduler::function>, "scheduler", serviceloop));
/* start the rpc server already. it will be started in "warmup" mode
* and not really process calls already (but it will signify connections
* that the server is there and will be ready later). warmup mode will
* be disabled when initialisation is finished.
*/
if (fserver)
{
uiinterface.initmessage.connect(setrpcwarmupstatus);
rpcserver::onstopped(&onrpcstopped);
rpcserver::onprecommand(&onrpcprecommand);
startrpcthreads();
}
int64_t nstart;
// ********************************************************* step 5: verify wallet database integrity
#ifdef enable_wallet
if (!fdisablewallet) {
logprintf("using wallet %s\n", strwalletfile);
uiinterface.initmessage(_("verifying wallet..."));
std::string warningstring;
std::string errorstring;
if (!cwallet::verify(strwalletfile, warningstring, errorstring))
return false;
if (!warningstring.empty())
initwarning(warningstring);
if (!errorstring.empty())
return initerror(warningstring);
} // (!fdisablewallet)
#endif // enable_wallet
// ********************************************************* step 6: network initialization
registernodesignals(getnodesignals());
if (mapargs.count("-onlynet")) {
std::set<enum network> nets;
boost_foreach(const std::string& snet, mapmultiargs["-onlynet"]) {
enum network net = parsenetwork(snet);
if (net == net_unroutable)
return initerror(strprintf(_("unknown network specified in -onlynet: '%s'"), snet));
nets.insert(net);
}
for (int n = 0; n < net_max; n++) {
enum network net = (enum network)n;
if (!nets.count(net))
setlimited(net);
}
}
if (mapargs.count("-whitelist")) {
boost_foreach(const std::string& net, mapmultiargs["-whitelist"]) {
csubnet subnet(net);
if (!subnet.isvalid())
return initerror(strprintf(_("invalid netmask specified in -whitelist: '%s'"), net));
cnode::addwhitelistedrange(subnet);
}
}
bool proxyrandomize = getboolarg("-proxyrandomize", true);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
std::string proxyarg = getarg("-proxy", "");
if (proxyarg != "" && proxyarg != "0") {
proxytype addrproxy = proxytype(cservice(proxyarg, 9050), proxyrandomize);
if (!addrproxy.isvalid())
return initerror(strprintf(_("invalid -proxy address: '%s'"), proxyarg));
setproxy(net_ipv4, addrproxy);
setproxy(net_ipv6, addrproxy);
setproxy(net_tor, addrproxy);
setnameproxy(addrproxy);
setreachable(net_tor); // by default, -proxy sets onion as reachable, unless -noonion later
}
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// an empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
std::string onionarg = getarg("-onion", "");
if (onionarg != "") {
if (onionarg == "0") { // handle -noonion/-onion=0
setreachable(net_tor, false); // set onions as unreachable
} else {
proxytype addronion = proxytype(cservice(onionarg, 9050), proxyrandomize);
if (!addronion.isvalid())
return initerror(strprintf(_("invalid -onion address: '%s'"), onionarg));
setproxy(net_tor, addronion);
setreachable(net_tor);
}
}
// see step 2: parameter interactions for more information about these
flisten = getboolarg("-listen", default_listen);
fdiscover = getboolarg("-discover", true);
fnamelookup = getboolarg("-dns", true);
bool fbound = false;
if (flisten) {
if (mapargs.count("-bind") || mapargs.count("-whitebind")) {
boost_foreach(const std::string& strbind, mapmultiargs["-bind"]) {
cservice addrbind;
if (!lookup(strbind.c_str(), addrbind, getlistenport(), false))
return initerror(strprintf(_("cannot resolve -bind address: '%s'"), strbind));
fbound |= bind(addrbind, (bf_explicit | bf_report_error));
}
boost_foreach(const std::string& strbind, mapmultiargs["-whitebind"]) {
cservice addrbind;
if (!lookup(strbind.c_str(), addrbind, 0, false))
return initerror(strprintf(_("cannot resolve -whitebind address: '%s'"), strbind));
if (addrbind.getport() == 0)
return initerror(strprintf(_("need to specify a port with -whitebind: '%s'"), strbind));
fbound |= bind(addrbind, (bf_explicit | bf_report_error | bf_whitelist));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = inaddr_any;
fbound |= bind(cservice(in6addr_any, getlistenport()), bf_none);
fbound |= bind(cservice(inaddr_any, getlistenport()), !fbound ? bf_report_error : bf_none);
}
if (!fbound)
return initerror(_("failed to listen on any port. use -listen=0 if you want this."));
}
if (mapargs.count("-externalip")) {
boost_foreach(const std::string& straddr, mapmultiargs["-externalip"]) {
cservice addrlocal(straddr, getlistenport(), fnamelookup);
if (!addrlocal.isvalid())
return initerror(strprintf(_("cannot resolve -externalip address: '%s'"), straddr));
addlocal(cservice(straddr, getlistenport(), fnamelookup), local_manual);
}
}
boost_foreach(const std::string& strdest, mapmultiargs["-seednode"])
addoneshot(strdest);
// ********************************************************* step 7: load block chain
freindex = getboolarg("-reindex", false);
// upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
boost::filesystem::path blocksdir = getdatadir() / "blocks";
if (!boost::filesystem::exists(blocksdir))
{
boost::filesystem::create_directories(blocksdir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
boost::filesystem::path source = getdatadir() / strprintf("blk%04u.dat", i);
if (!boost::filesystem::exists(source)) break;
boost::filesystem::path dest = blocksdir / strprintf("blk%05u.dat", i-1);
try {
boost::filesystem::create_hard_link(source, dest);
logprintf("hardlinked %s -> %s\n", source.string(), dest.string());
linked = true;
} catch (const boost::filesystem::filesystem_error& e) {
// note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
logprintf("error hardlinking blk%04u.dat: %s\n", i, e.what());
break;
}
}
if (linked)
{
freindex = true;
}
}
// cache size calculations
int64_t ntotalcache = (getarg("-dbcache", ndefaultdbcache) << 20);
ntotalcache = std::max(ntotalcache, nmindbcache << 20); // total cache cannot be less than nmindbcache
ntotalcache = std::min(ntotalcache, nmaxdbcache << 20); // total cache cannot be greated than nmaxdbcache
int64_t nblocktreedbcache = ntotalcache / 8;
if (nblocktreedbcache > (1 << 21) && !getboolarg("-txindex", false))
nblocktreedbcache = (1 << 21); // block tree db cache shouldn't be larger than 2 mib
ntotalcache -= nblocktreedbcache;
int64_t ncoindbcache = std::min(ntotalcache / 2, (ntotalcache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
ntotalcache -= ncoindbcache;
ncoincacheusage = ntotalcache; // the rest goes to in-memory cache
logprintf("cache configuration:\n");
logprintf("* using %.1fmib for block index database\n", nblocktreedbcache * (1.0 / 1024 / 1024));
logprintf("* using %.1fmib for chain state database\n", ncoindbcache * (1.0 / 1024 / 1024));
logprintf("* using %.1fmib for in-memory utxo set\n", ncoincacheusage * (1.0 / 1024 / 1024));
bool floaded = false;
while (!floaded) {
bool freset = freindex;
std::string strloaderror;
uiinterface.initmessage(_("loading block index..."));
nstart = gettimemillis();
do {
try {
unloadblockindex();
delete pcoinstip;
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
pblocktree = new cblocktreedb(nblocktreedbcache, false, freindex);
pcoinsdbview = new ccoinsviewdb(ncoindbcache, false, freindex);
pcoinscatcher = new ccoinsviewerrorcatcher(pcoinsdbview);
pcoinstip = new ccoinsviewcache(pcoinscatcher);
if (freindex) {
pblocktree->writereindexing(true);
//if we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fprunemode)
cleanupblockrevfiles();
}
if (!loadblockindex()) {
strloaderror = _("error loading block database");
break;
}
// if the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapblockindex.empty() && mapblockindex.count(chainparams.getconsensus().hashgenesisblock) == 0)
return initerror(_("incorrect or no genesis block found. wrong datadir for network?"));
// initialize the block index (no-op if non-empty database was already loaded)
if (!initblockindex()) {
strloaderror = _("error initializing block database");
break;
}
// check for changed -txindex state
if (ftxindex != getboolarg("-txindex", false)) {
strloaderror = _("you need to rebuild the database using -reindex to change -txindex");
break;
}
// check for changed -prune state. what we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fhavepruned && !fprunemode) {
strloaderror = _("you need to rebuild the database using -reindex to go back to unpruned mode. this will redownload the entire blockchain");
break;
}
uiinterface.initmessage(_("verifying blocks..."));
if (fhavepruned && getarg("-checkblocks", 288) > min_blocks_to_keep) {
logprintf("prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
min_blocks_to_keep, getarg("-checkblocks", 288));
}
if (!cverifydb().verifydb(pcoinsdbview, getarg("-checklevel", 3),
getarg("-checkblocks", 288))) {
strloaderror = _("corrupted block database detected");
break;
}
} catch (const std::exception& e) {
if (fdebug) logprintf("%s\n", e.what());
strloaderror = _("error opening block database");
break;
}
floaded = true;
} while(false);
if (!floaded) {
// first suggest a reindex
if (!freset) {
bool fret = uiinterface.threadsafemessagebox(
strloaderror + ".\n\n" + _("do you want to rebuild the block database now?"),
"", cclientuiinterface::msg_error | cclientuiinterface::btn_abort);
if (fret) {
freindex = true;
frequestshutdown = false;
} else {
logprintf("aborted block database rebuild. exiting.\n");
return false;
}
} else {
return initerror(strloaderror);
}
}
}
// as loadblockindex can take several minutes, it's possible the user
// requested to kill the gui during the last operation. if so, exit.
// as the program has not fully started yet, shutdown() is possibly overkill.
if (frequestshutdown)
{
logprintf("shutdown requested. exiting.\n");
return false;
}
logprintf(" block index %15dms\n", gettimemillis() - nstart);
boost::filesystem::path est_path = getdatadir() / fee_estimates_filename;
cautofile est_filein(fopen(est_path.string().c_str(), "rb"), ser_disk, client_version);
// allowed to fail as this file is missing on first startup.
if (!est_filein.isnull())
mempool.readfeeestimates(est_filein);
ffeeestimatesinitialized = true;
// if prune mode, unset node_network and prune block files
if (fprunemode) {
logprintf("unsetting node_network on prune mode\n");
nlocalservices &= ~node_network;
if (!freindex) {
pruneandflush();
}
}
// ********************************************************* step 8: load wallet
#ifdef enable_wallet
if (fdisablewallet) {
pwalletmain = null;
logprintf("wallet disabled!\n");
} else {
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<cwallettx> vwtx;
if (getboolarg("-zapwallettxes", false)) {
uiinterface.initmessage(_("zapping all transactions from wallet..."));
pwalletmain = new cwallet(strwalletfile);
dberrors nzapwalletret = pwalletmain->zapwallettx(vwtx);
if (nzapwalletret != db_load_ok) {
uiinterface.initmessage(_("error loading wallet.dat: wallet corrupted"));
return false;
}
delete pwalletmain;
pwalletmain = null;
}
uiinterface.initmessage(_("loading wallet..."));
nstart = gettimemillis();
bool ffirstrun = true;
pwalletmain = new cwallet(strwalletfile);
dberrors nloadwalletret = pwalletmain->loadwallet(ffirstrun);
if (nloadwalletret != db_load_ok)
{
if (nloadwalletret == db_corrupt)
strerrors << _("error loading wallet.dat: wallet corrupted") << "\n";
else if (nloadwalletret == db_noncritical_error)
{
string msg(_("warning: error reading wallet.dat! all keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
initwarning(msg);
}
else if (nloadwalletret == db_too_new)
strerrors << _("error loading wallet.dat: wallet requires newer version of moorecoin core") << "\n";
else if (nloadwalletret == db_need_rewrite)
{
strerrors << _("wallet needed to be rewritten: restart moorecoin core to complete") << "\n";
logprintf("%s", strerrors.str());
return initerror(strerrors.str());
}
else
strerrors << _("error loading wallet.dat") << "\n";
}
if (getboolarg("-upgradewallet", ffirstrun))
{
int nmaxversion = getarg("-upgradewallet", 0);
if (nmaxversion == 0) // the -upgradewallet without argument case
{
logprintf("performing wallet upgrade to %i\n", feature_latest);
nmaxversion = client_version;
pwalletmain->setminversion(feature_latest); // permanently upgrade the wallet immediately
}
else
logprintf("allowing wallet upgrade up to %i\n", nmaxversion);
if (nmaxversion < pwalletmain->getversion())
strerrors << _("cannot downgrade wallet") << "\n";
pwalletmain->setmaxversion(nmaxversion);
}
if (ffirstrun)
{
// create new keyuser and set as default key
randaddseedperfmon();
cpubkey newdefaultkey;
if (pwalletmain->getkeyfrompool(newdefaultkey)) {
pwalletmain->setdefaultkey(newdefaultkey);
if (!pwalletmain->setaddressbook(pwalletmain->vchdefaultkey.getid(), "", "receive"))
strerrors << _("cannot write default address") << "\n";
}
pwalletmain->setbestchain(chainactive.getlocator());
}
logprintf("%s", strerrors.str());
logprintf(" wallet %15dms\n", gettimemillis() - nstart);
registervalidationinterface(pwalletmain);
cblockindex *pindexrescan = chainactive.tip();
if (getboolarg("-rescan", false))
pindexrescan = chainactive.genesis();
else
{
cwalletdb walletdb(strwalletfile);
cblocklocator locator;
if (walletdb.readbestblock(locator))
pindexrescan = findforkinglobalindex(chainactive, locator);
else
pindexrescan = chainactive.genesis();
}
if (chainactive.tip() && chainactive.tip() != pindexrescan)
{
//we can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses a old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fprunemode)
{
cblockindex *block = chainactive.tip();
while (block && block->pprev && (block->pprev->nstatus & block_have_data) && block->pprev->ntx > 0 && pindexrescan != block)
block = block->pprev;
if (pindexrescan != block)
return initerror(_("prune: last wallet synchronisation goes beyond pruned data. you need to -reindex (download the whole blockchain again in case of pruned node)"));
}
uiinterface.initmessage(_("rescanning..."));
logprintf("rescanning last %i blocks (from block %i)...\n", chainactive.height() - pindexrescan->nheight, pindexrescan->nheight);
nstart = gettimemillis();
pwalletmain->scanforwallettransactions(pindexrescan, true);
logprintf(" rescan %15dms\n", gettimemillis() - nstart);
pwalletmain->setbestchain(chainactive.getlocator());
nwalletdbupdated++;
// restore wallet transaction metadata after -zapwallettxes=1
if (getboolarg("-zapwallettxes", false) && getarg("-zapwallettxes", "1") != "2")
{
cwalletdb walletdb(strwalletfile);
boost_foreach(const cwallettx& wtxold, vwtx)
{
uint256 hash = wtxold.gethash();
std::map<uint256, cwallettx>::iterator mi = pwalletmain->mapwallet.find(hash);
if (mi != pwalletmain->mapwallet.end())
{
const cwallettx* copyfrom = &wtxold;
cwallettx* copyto = &mi->second;
copyto->mapvalue = copyfrom->mapvalue;
copyto->vorderform = copyfrom->vorderform;
copyto->ntimereceived = copyfrom->ntimereceived;
copyto->ntimesmart = copyfrom->ntimesmart;
copyto->ffromme = copyfrom->ffromme;
copyto->strfromaccount = copyfrom->strfromaccount;
copyto->norderpos = copyfrom->norderpos;
copyto->writetodisk(&walletdb);
}
}
}
}
pwalletmain->setbroadcasttransactions(getboolarg("-walletbroadcast", true));
} // (!fdisablewallet)
#else // enable_wallet
logprintf("no wallet support compiled in!\n");
#endif // !enable_wallet
// ********************************************************* step 9: import blocks
if (mapargs.count("-blocknotify"))
uiinterface.notifyblocktip.connect(blocknotifycallback);
uiinterface.initmessage(_("activating best chain..."));
// scan for better chains in the block chain database, that are not yet connected in the active best chain
cvalidationstate state;
if (!activatebestchain(state))
strerrors << "failed to connect best block";
std::vector<boost::filesystem::path> vimportfiles;
if (mapargs.count("-loadblock"))
{
boost_foreach(const std::string& strfile, mapmultiargs["-loadblock"])
vimportfiles.push_back(strfile);
}
threadgroup.create_thread(boost::bind(&threadimport, vimportfiles));
if (chainactive.tip() == null) {
logprintf("waiting for genesis block to be imported...\n");
while (!frequestshutdown && chainactive.tip() == null)
millisleep(10);
}
// ********************************************************* step 10: start node
if (!checkdiskspace())
return false;
if (!strerrors.str().empty())
return initerror(strerrors.str());
randaddseedperfmon();
//// debug print
logprintf("mapblockindex.size() = %u\n", mapblockindex.size());
logprintf("nbestheight = %d\n", chainactive.height());
#ifdef enable_wallet
logprintf("setkeypool.size() = %u\n", pwalletmain ? pwalletmain->setkeypool.size() : 0);
logprintf("mapwallet.size() = %u\n", pwalletmain ? pwalletmain->mapwallet.size() : 0);
logprintf("mapaddressbook.size() = %u\n", pwalletmain ? pwalletmain->mapaddressbook.size() : 0);
#endif
startnode(threadgroup, scheduler);
// monitor the chain, and alert if we get blocks much quicker or slower than expected
int64_t npowtargetspacing = params().getconsensus().npowtargetspacing;
cscheduler::function f = boost::bind(&partitioncheck, &isinitialblockdownload,
boost::ref(cs_main), boost::cref(pindexbestheader), npowtargetspacing);
scheduler.scheduleevery(f, npowtargetspacing);
#ifdef enable_wallet
// generate coins in the background
if (pwalletmain)
generatemoorecoins(getboolarg("-gen", false), pwalletmain, getarg("-genproclimit", 1));
#endif
// ********************************************************* step 11: finished
setrpcwarmupfinished();
uiinterface.initmessage(_("done loading"));
#ifdef enable_wallet
if (pwalletmain) {
// add wallet transactions that aren't already in a block to maptransactions
pwalletmain->reacceptwallettransactions();
// run a thread to flush wallet periodically
threadgroup.create_thread(boost::bind(&threadflushwalletdb, boost::ref(pwalletmain->strwalletfile)));
}
#endif
return !frequestshutdown;
}
| 47.797538 | 282 | 0.639024 | [
"vector"
] |
f57e37cfbcdbff5870dc32d31c853b903d448b3c | 9,812 | hpp | C++ | include/neolib/io/tcp_packet_stream_server.hpp | i42output/neolib | 6fabf42de29141ea1be5e1857ae4008d56b4e4fc | [
"BSD-3-Clause"
] | 30 | 2018-05-21T07:44:51.000Z | 2022-02-12T11:28:48.000Z | include/neolib/io/tcp_packet_stream_server.hpp | i42output/neolib | 6fabf42de29141ea1be5e1857ae4008d56b4e4fc | [
"BSD-3-Clause"
] | 21 | 2018-07-14T12:33:23.000Z | 2021-10-19T01:35:55.000Z | include/neolib/io/tcp_packet_stream_server.hpp | i42output/neolib | 6fabf42de29141ea1be5e1857ae4008d56b4e4fc | [
"BSD-3-Clause"
] | 6 | 2018-10-31T00:58:40.000Z | 2021-12-06T05:14:18.000Z | // tcp_packet_stream_server.hpp
/*
* Copyright (c) 2007 Leigh Johnston.
*
* 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 Leigh Johnston nor the names of any
* other contributors to this software 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.
*/
#pragma once
#include <neolib/neolib.hpp>
#include <stdexcept>
#include <vector>
#include <memory>
#include <neolib/core/lifetime.hpp>
#include <neolib/task/async_task.hpp>
#include <neolib/io/packet_stream.hpp>
namespace neolib
{
template <typename PacketType>
class tcp_packet_stream_server;
template <typename PacketType>
class tcp_packet_stream_server : public lifetime<>
{
typedef tcp_packet_stream_server<PacketType> self_type;
// types
public:
typedef PacketType packet_type;
typedef tcp_protocol protocol_type;
typedef packet_stream<packet_type, protocol_type> packet_stream_type;
// events
public:
define_event(PacketStreamAdded, packet_stream_added, packet_stream_type&)
define_event(PacketStreamRemoved, packet_stream_removed, packet_stream_type&)
define_event(FailedToAcceptPacketStream, failed_to_accept_packet_stream, const boost::system::error_code&)
// types
private:
typedef typename packet_stream_type::pointer packet_stream_pointer;
typedef std::vector<packet_stream_pointer> stream_list;
typedef protocol_type::endpoint endpoint_type;
typedef protocol_type::resolver resolver_type;
typedef protocol_type::acceptor acceptor_type;
private:
class handler_proxy
{
public:
handler_proxy(self_type& aParent) : iParent(aParent), iOrphaned(false)
{
}
public:
void operator()(const boost::system::error_code& aError)
{
if (!iOrphaned)
iParent.handle_accept(aError);
}
void orphan(bool aCreateNewHandlerProxy = true)
{
iOrphaned = true;
if (aCreateNewHandlerProxy)
iParent.iHandlerProxy = std::make_shared<handler_proxy>(iParent);
else
iParent.iHandlerProxy.reset();
}
private:
self_type& iParent;
bool iOrphaned;
};
// exceptions
public:
struct failed_to_resolve_local_host : std::runtime_error { failed_to_resolve_local_host() : std::runtime_error("neolib::tcp_packet_stream_server::failed_to_resolve_local_host") {} };
struct stream_not_found : std::logic_error { stream_not_found() : std::logic_error("neolib::tcp_packet_stream_server::stream_not_found") {} };
// construction
public:
tcp_packet_stream_server(i_async_task& aIoTask, unsigned short aLocalPort, bool aSecure = false, protocol_family aProtocolFamily = IPv4) :
iIoTask(aIoTask),
iHandlerProxy(new handler_proxy(*this)),
iLocalPort(aLocalPort),
iSecure(aSecure),
iProtocolFamily(aProtocolFamily & IPv4 ? protocol_type::v4() : protocol_type::v6()),
iLocalEndpoint(iProtocolFamily, iLocalPort),
iAcceptor(aIoTask.io_service().native_object<boost::asio::io_service>(), iLocalEndpoint)
{
accept_connection();
}
tcp_packet_stream_server(i_async_task& aIoTask, const std::string& aLocalHostName, unsigned short aLocalPort, bool aSecure = false, protocol_family aProtocolFamily = IPv4) :
iIoTask(aIoTask),
iHandlerProxy(new handler_proxy(*this)),
iLocalHostName(aLocalHostName),
iLocalPort(aLocalPort),
iSecure(aSecure),
iProtocolFamily(aProtocolFamily & IPv4 ? protocol_type::v4() : protocol_type::v6()),
iLocalEndpoint(resolve(aIoTask, iLocalHostName, iLocalPort, iProtocolFamily)),
iAcceptor(aIoTask.io_service().native_object<boost::asio::io_service>(), iLocalEndpoint)
{
accept_connection();
}
~tcp_packet_stream_server()
{
set_destroying();
for (typename stream_list::iterator i = iStreamList.begin(); i != iStreamList.end(); ++i)
*i = nullptr;
iStreamList.clear();
iHandlerProxy->orphan();
iAcceptor.close();
}
// operations
public:
unsigned short local_port() const
{
return iLocalPort;
}
packet_stream_pointer take_ownership(packet_stream_type& aStream)
{
for (typename stream_list::iterator i = iStreamList.begin(); i != iStreamList.end(); ++i)
if (*i == &aStream)
{
packet_stream_pointer found(*i);
iStreamList.erase(i);
aStream.remove_observer(*this);
return found;
}
throw stream_not_found();
}
// implementation
private:
// own
static endpoint_type resolve(async_task& aIoTask, const std::string& aHostname, unsigned short aPort, protocol_type aProtocolFamily)
{
resolver_type resolver(aIoTask.io_service().native_object());
boost::system::error_code ec;
typename resolver_type::iterator result = resolver.resolve(resolver_type::query(aHostname, std::to_string(aPort), ec));
if (!ec)
{
for (typename resolver_type::iterator i = result; i != resolver_type::iterator(); ++i)
{
endpoint_type endpoint = *i;
if (endpoint.protocol() == aProtocolFamily)
return endpoint;
}
return *result;
}
throw failed_to_resolve_local_host();
}
void accept_connection()
{
if (iAcceptingStream != nullptr)
return;
iAcceptingStream = std::make_unique<packet_stream_type>(iIoTask, iSecure, iLocalEndpoint.protocol() == protocol_type::v4() ? IPv4 : IPv6);
auto acceptingStream = &*iAcceptingStream;
iAcceptingStream->connection_closed([this, acceptingStream]()
{
if (is_alive())
{
for (typename stream_list::iterator i = iStreamList.begin(); i != iStreamList.end(); ++i)
if (&**i == acceptingStream)
{
packet_stream_pointer keepObjectAlive{ std::move(*i) };
iStreamList.erase(i);
PacketStreamRemoved.trigger(*acceptingStream);
break;
}
}
else
PacketStreamRemoved.trigger(*acceptingStream);
});
iAcceptingStream->connection().open(true);
iAcceptor.async_accept(iAcceptingStream->connection().socket(), boost::bind(&handler_proxy::operator(), iHandlerProxy, boost::asio::placeholders::error));
}
void handle_accept(const boost::system::error_code& aError)
{
if (!aError)
{
iAcceptingStream->connection().server_accept();
iStreamList.push_back(std::move(iAcceptingStream));
PacketStreamAdded.trigger(*iStreamList.back());
accept_connection();
}
else
FailedToAcceptPacketStream.trigger(aError);
}
// attributes
private:
i_async_task& iIoTask;
std::shared_ptr<handler_proxy> iHandlerProxy;
std::string iLocalHostName;
unsigned short iLocalPort;
bool iSecure;
protocol_type iProtocolFamily;
endpoint_type iLocalEndpoint;
acceptor_type iAcceptor;
packet_stream_pointer iAcceptingStream;
stream_list iStreamList;
};
typedef tcp_packet_stream_server<string_packet> tcp_string_packet_stream_server;
}
| 42.293103 | 191 | 0.603139 | [
"vector"
] |
f5852076b4ec686511a8ac171aeea36d220e19d7 | 5,360 | cc | C++ | src/node_trace_events.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | 2 | 2020-09-16T01:30:55.000Z | 2020-09-28T02:17:07.000Z | src/node_trace_events.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | null | null | null | src/node_trace_events.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | null | null | null | #include "base_object-inl.h"
#include "env-inl.h"
#include "memory_tracker-inl.h"
#include "node.h"
#include "node_internals.h"
#include "node_v8_platform-inl.h"
#include "tracing/agent.h"
#include "util-inl.h"
#include <set>
#include <string>
namespace node {
using v8::Array;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;
class NodeCategorySet : public BaseObject {
public:
static void Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv);
static void New(const FunctionCallbackInfo<Value>& args);
static void Enable(const FunctionCallbackInfo<Value>& args);
static void Disable(const FunctionCallbackInfo<Value>& args);
const std::set<std::string>& GetCategories() const { return categories_; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("categories", categories_);
}
SET_MEMORY_INFO_NAME(NodeCategorySet)
SET_SELF_SIZE(NodeCategorySet)
private:
NodeCategorySet(Environment* env,
Local<Object> wrap,
std::set<std::string>&& categories) :
BaseObject(env, wrap), categories_(std::move(categories)) {
MakeWeak();
}
bool enabled_ = false;
const std::set<std::string> categories_;
};
void NodeCategorySet::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
std::set<std::string> categories;
CHECK(args[0]->IsArray());
Local<Array> cats = args[0].As<Array>();
for (size_t n = 0; n < cats->Length(); n++) {
Local<Value> category;
if (!cats->Get(env->context(), n).ToLocal(&category)) return;
Utf8Value val(env->isolate(), category);
if (!*val) return;
categories.emplace(*val);
}
CHECK_NOT_NULL(GetTracingAgentWriter());
new NodeCategorySet(env, args.This(), std::move(categories));
}
void NodeCategorySet::Enable(const FunctionCallbackInfo<Value>& args) {
NodeCategorySet* category_set;
ASSIGN_OR_RETURN_UNWRAP(&category_set, args.Holder());
CHECK_NOT_NULL(category_set);
const auto& categories = category_set->GetCategories();
if (!category_set->enabled_ && !categories.empty()) {
// Starts the Tracing Agent if it wasn't started already (e.g. through
// a command line flag.)
StartTracingAgent();
GetTracingAgentWriter()->Enable(categories);
category_set->enabled_ = true;
}
}
void NodeCategorySet::Disable(const FunctionCallbackInfo<Value>& args) {
NodeCategorySet* category_set;
ASSIGN_OR_RETURN_UNWRAP(&category_set, args.Holder());
CHECK_NOT_NULL(category_set);
const auto& categories = category_set->GetCategories();
if (category_set->enabled_ && !categories.empty()) {
GetTracingAgentWriter()->Disable(categories);
category_set->enabled_ = false;
}
}
void GetEnabledCategories(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
std::string categories =
GetTracingAgentWriter()->agent()->GetEnabledCategories();
if (!categories.empty()) {
args.GetReturnValue().Set(
String::NewFromUtf8(env->isolate(),
categories.c_str(),
NewStringType::kNormal,
categories.size()).ToLocalChecked());
}
}
static void SetTraceCategoryStateUpdateHandler(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args[0]->IsFunction());
env->set_trace_category_state_function(args[0].As<Function>());
}
void NodeCategorySet::Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
Environment* env = Environment::GetCurrent(context);
env->SetMethod(target, "getEnabledCategories", GetEnabledCategories);
env->SetMethod(
target, "setTraceCategoryStateUpdateHandler",
SetTraceCategoryStateUpdateHandler);
Local<FunctionTemplate> category_set =
env->NewFunctionTemplate(NodeCategorySet::New);
category_set->InstanceTemplate()->SetInternalFieldCount(1);
env->SetProtoMethod(category_set, "enable", NodeCategorySet::Enable);
env->SetProtoMethod(category_set, "disable", NodeCategorySet::Disable);
target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(), "CategorySet"),
category_set->GetFunction(env->context()).ToLocalChecked())
.Check();
Local<String> isTraceCategoryEnabled =
FIXED_ONE_BYTE_STRING(env->isolate(), "isTraceCategoryEnabled");
Local<String> trace = FIXED_ONE_BYTE_STRING(env->isolate(), "trace");
// Grab the trace and isTraceCategoryEnabled intrinsics from the binding
// object and expose those to our binding layer.
Local<Object> binding = context->GetExtrasBindingObject();
target->Set(context, isTraceCategoryEnabled,
binding->Get(context, isTraceCategoryEnabled).ToLocalChecked())
.Check();
target->Set(context, trace,
binding->Get(context, trace).ToLocalChecked()).Check();
}
} // namespace node
NODE_MODULE_CONTEXT_AWARE_INTERNAL(trace_events,
node::NodeCategorySet::Initialize)
| 33.710692 | 77 | 0.692164 | [
"object"
] |
f588f2347d0f7c24d36f4dcbd8e69e8c3be32540 | 49,423 | cc | C++ | src/debug/debug-interface.cc | zingdle/v8 | 3abe95def30792089427750a4ccbe548addd2518 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T10:13:45.000Z | 2022-01-14T10:13:45.000Z | src/debug/debug-interface.cc | zingdle/v8 | 3abe95def30792089427750a4ccbe548addd2518 | [
"BSD-3-Clause"
] | null | null | null | src/debug/debug-interface.cc | zingdle/v8 | 3abe95def30792089427750a4ccbe548addd2518 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/debug/debug-interface.h"
#include "include/v8-function.h"
#include "src/api/api-inl.h"
#include "src/base/utils/random-number-generator.h"
#include "src/codegen/compiler.h"
#include "src/codegen/script-details.h"
#include "src/debug/debug-coverage.h"
#include "src/debug/debug-evaluate.h"
#include "src/debug/debug-property-iterator.h"
#include "src/debug/debug-type-profile.h"
#include "src/debug/debug.h"
#include "src/execution/vm-state-inl.h"
#include "src/objects/js-generator-inl.h"
#include "src/objects/stack-frame-info-inl.h"
#include "src/profiler/heap-profiler.h"
#include "src/strings/string-builder-inl.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/debug/debug-wasm-objects-inl.h"
#include "src/wasm/wasm-engine.h"
#endif // V8_ENABLE_WEBASSEMBLY
// Has to be the last include (doesn't have include guards):
#include "src/api/api-macros.h"
namespace v8 {
namespace debug {
void SetContextId(Local<Context> context, int id) {
Utils::OpenHandle(*context)->set_debug_context_id(i::Smi::FromInt(id));
}
int GetContextId(Local<Context> context) {
i::Object value = Utils::OpenHandle(*context)->debug_context_id();
return (value.IsSmi()) ? i::Smi::ToInt(value) : 0;
}
void SetInspector(Isolate* isolate, v8_inspector::V8Inspector* inspector) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i_isolate->set_inspector(inspector);
}
v8_inspector::V8Inspector* GetInspector(Isolate* isolate) {
return reinterpret_cast<i::Isolate*>(isolate)->inspector();
}
Local<String> GetFunctionDebugName(Local<StackFrame> frame) {
#if V8_ENABLE_WEBASSEMBLY
auto info = Utils::OpenHandle(*frame);
if (info->IsWasm()) {
auto isolate = info->GetIsolate();
auto instance = handle(info->GetWasmInstance(), isolate);
auto func_index = info->GetWasmFunctionIndex();
return Utils::ToLocal(
i::GetWasmFunctionDebugName(isolate, instance, func_index));
}
#endif // V8_ENABLE_WEBASSEMBLY
return frame->GetFunctionName();
}
Local<String> GetFunctionDescription(Local<Function> function) {
auto receiver = Utils::OpenHandle(*function);
if (receiver->IsJSBoundFunction()) {
return Utils::ToLocal(i::JSBoundFunction::ToString(
i::Handle<i::JSBoundFunction>::cast(receiver)));
}
if (receiver->IsJSFunction()) {
auto js_function = i::Handle<i::JSFunction>::cast(receiver);
#if V8_ENABLE_WEBASSEMBLY
if (js_function->shared().HasWasmExportedFunctionData()) {
auto isolate = js_function->GetIsolate();
auto func_index =
js_function->shared().wasm_exported_function_data().function_index();
auto instance = i::handle(
js_function->shared().wasm_exported_function_data().instance(),
isolate);
if (instance->module()->origin == i::wasm::kWasmOrigin) {
// For asm.js functions, we can still print the source
// code (hopefully), so don't bother with them here.
auto debug_name =
i::GetWasmFunctionDebugName(isolate, instance, func_index);
i::IncrementalStringBuilder builder(isolate);
builder.AppendCStringLiteral("function ");
builder.AppendString(debug_name);
builder.AppendCStringLiteral("() { [native code] }");
return Utils::ToLocal(builder.Finish().ToHandleChecked());
}
}
#endif // V8_ENABLE_WEBASSEMBLY
return Utils::ToLocal(i::JSFunction::ToString(js_function));
}
return Utils::ToLocal(
receiver->GetIsolate()->factory()->function_native_code_string());
}
void SetBreakOnNextFunctionCall(Isolate* isolate) {
reinterpret_cast<i::Isolate*>(isolate)->debug()->SetBreakOnNextFunctionCall();
}
void ClearBreakOnNextFunctionCall(Isolate* isolate) {
reinterpret_cast<i::Isolate*>(isolate)
->debug()
->ClearBreakOnNextFunctionCall();
}
MaybeLocal<Array> GetInternalProperties(Isolate* v8_isolate,
Local<Value> value) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::Handle<i::Object> val = Utils::OpenHandle(*value);
i::Handle<i::JSArray> result;
if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result))
return MaybeLocal<Array>();
return Utils::ToLocal(result);
}
namespace {
void CollectPrivateMethodsAndAccessorsFromContext(
i::Isolate* isolate, i::Handle<i::Context> context,
i::IsStaticFlag is_static_flag, std::vector<Local<Value>>* names_out,
std::vector<Local<Value>>* values_out) {
i::Handle<i::ScopeInfo> scope_info(context->scope_info(), isolate);
int local_count = scope_info->ContextLocalCount();
for (int j = 0; j < local_count; ++j) {
i::VariableMode mode = scope_info->ContextLocalMode(j);
i::IsStaticFlag flag = scope_info->ContextLocalIsStaticFlag(j);
if (!i::IsPrivateMethodOrAccessorVariableMode(mode) ||
flag != is_static_flag) {
continue;
}
i::Handle<i::String> name(scope_info->ContextLocalName(j), isolate);
int context_index = scope_info->ContextHeaderLength() + j;
i::Handle<i::Object> slot_value(context->get(context_index), isolate);
DCHECK_IMPLIES(mode == i::VariableMode::kPrivateMethod,
slot_value->IsJSFunction());
DCHECK_IMPLIES(mode != i::VariableMode::kPrivateMethod,
slot_value->IsAccessorPair());
names_out->push_back(Utils::ToLocal(name));
values_out->push_back(Utils::ToLocal(slot_value));
}
}
} // namespace
bool GetPrivateMembers(Local<Context> context, Local<Object> object,
std::vector<Local<Value>>* names_out,
std::vector<Local<Value>>* values_out) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
LOG_API(isolate, debug, GetPrivateMembers);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::Handle<i::JSReceiver> receiver = Utils::OpenHandle(*object);
i::Handle<i::JSArray> names;
i::Handle<i::FixedArray> values;
i::PropertyFilter key_filter =
static_cast<i::PropertyFilter>(i::PropertyFilter::PRIVATE_NAMES_ONLY);
i::Handle<i::FixedArray> keys;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, keys,
i::KeyAccumulator::GetKeys(receiver, i::KeyCollectionMode::kOwnOnly,
key_filter,
i::GetKeysConversion::kConvertToString),
false);
// Estimate number of private fields and private instance methods/accessors.
int private_entries_count = 0;
for (int i = 0; i < keys->length(); ++i) {
// Exclude the private brand symbols.
i::Handle<i::Symbol> key(i::Symbol::cast(keys->get(i)), isolate);
if (key->is_private_brand()) {
i::Handle<i::Object> value;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, value, i::Object::GetProperty(isolate, receiver, key),
false);
i::Handle<i::Context> value_context(i::Context::cast(*value), isolate);
i::Handle<i::ScopeInfo> scope_info(value_context->scope_info(), isolate);
// At least one slot contains the brand symbol so it does not count.
private_entries_count += (scope_info->ContextLocalCount() - 1);
} else {
private_entries_count++;
}
}
// Estimate number of static private methods/accessors for classes.
bool has_static_private_methods_or_accessors = false;
if (receiver->IsJSFunction()) {
i::Handle<i::JSFunction> func(i::JSFunction::cast(*receiver), isolate);
i::Handle<i::SharedFunctionInfo> shared(func->shared(), isolate);
if (shared->is_class_constructor() &&
shared->has_static_private_methods_or_accessors()) {
has_static_private_methods_or_accessors = true;
i::Handle<i::Context> func_context(func->context(), isolate);
i::Handle<i::ScopeInfo> scope_info(func_context->scope_info(), isolate);
int local_count = scope_info->ContextLocalCount();
for (int j = 0; j < local_count; ++j) {
i::VariableMode mode = scope_info->ContextLocalMode(j);
i::IsStaticFlag is_static_flag =
scope_info->ContextLocalIsStaticFlag(j);
if (i::IsPrivateMethodOrAccessorVariableMode(mode) &&
is_static_flag == i::IsStaticFlag::kStatic) {
private_entries_count += local_count;
break;
}
}
}
}
DCHECK(names_out->empty());
names_out->reserve(private_entries_count);
DCHECK(values_out->empty());
values_out->reserve(private_entries_count);
if (has_static_private_methods_or_accessors) {
i::Handle<i::Context> recevier_context(
i::JSFunction::cast(*receiver).context(), isolate);
CollectPrivateMethodsAndAccessorsFromContext(isolate, recevier_context,
i::IsStaticFlag::kStatic,
names_out, values_out);
}
for (int i = 0; i < keys->length(); ++i) {
i::Handle<i::Object> obj_key(keys->get(i), isolate);
i::Handle<i::Symbol> key(i::Symbol::cast(*obj_key), isolate);
CHECK(key->is_private_name());
i::Handle<i::Object> value;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, value, i::Object::GetProperty(isolate, receiver, key), false);
if (key->is_private_brand()) {
DCHECK(value->IsContext());
i::Handle<i::Context> value_context(i::Context::cast(*value), isolate);
CollectPrivateMethodsAndAccessorsFromContext(isolate, value_context,
i::IsStaticFlag::kNotStatic,
names_out, values_out);
} else { // Private fields
i::Handle<i::String> name(
i::String::cast(i::Symbol::cast(*key).description()), isolate);
names_out->push_back(Utils::ToLocal(name));
values_out->push_back(Utils::ToLocal(value));
}
}
DCHECK_EQ(names_out->size(), values_out->size());
DCHECK_LE(names_out->size(), private_entries_count);
return true;
}
MaybeLocal<Context> GetCreationContext(Local<Object> value) {
i::Handle<i::Object> val = Utils::OpenHandle(*value);
if (val->IsJSGlobalProxy()) {
return MaybeLocal<Context>();
}
return value->GetCreationContext();
}
void ChangeBreakOnException(Isolate* isolate, ExceptionBreakState type) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_isolate->debug()->ChangeBreakOnException(
i::BreakException, type == BreakOnAnyException);
internal_isolate->debug()->ChangeBreakOnException(i::BreakUncaughtException,
type != NoBreakOnException);
}
void SetBreakPointsActive(Isolate* v8_isolate, bool is_active) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
isolate->debug()->set_break_points_active(is_active);
}
void PrepareStep(Isolate* v8_isolate, StepAction action) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_DO_NOT_USE(isolate);
CHECK(isolate->debug()->CheckExecutionState());
// Clear all current stepping setup.
isolate->debug()->ClearStepping();
// Prepare step.
isolate->debug()->PrepareStep(static_cast<i::StepAction>(action));
}
void ClearStepping(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
// Clear all current stepping setup.
isolate->debug()->ClearStepping();
}
void BreakRightNow(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_DO_NOT_USE(isolate);
isolate->debug()->HandleDebugBreak(i::kIgnoreIfAllFramesBlackboxed);
}
void SetTerminateOnResume(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
isolate->debug()->SetTerminateOnResume();
}
bool CanBreakProgram(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_DO_NOT_USE(isolate);
return isolate->debug()->AllFramesOnStackAreBlackboxed();
}
Isolate* Script::GetIsolate() const {
return reinterpret_cast<Isolate*>(Utils::OpenHandle(this)->GetIsolate());
}
ScriptOriginOptions Script::OriginOptions() const {
return Utils::OpenHandle(this)->origin_options();
}
bool Script::WasCompiled() const {
return Utils::OpenHandle(this)->compilation_state() ==
i::Script::COMPILATION_STATE_COMPILED;
}
bool Script::IsEmbedded() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
return script->context_data() ==
script->GetReadOnlyRoots().uninitialized_symbol();
}
int Script::Id() const { return Utils::OpenHandle(this)->id(); }
int Script::LineOffset() const {
return Utils::OpenHandle(this)->line_offset();
}
int Script::ColumnOffset() const {
return Utils::OpenHandle(this)->column_offset();
}
std::vector<int> Script::LineEnds() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
#if V8_ENABLE_WEBASSEMBLY
if (script->type() == i::Script::TYPE_WASM) return {};
#endif // V8_ENABLE_WEBASSEMBLY
i::Isolate* isolate = script->GetIsolate();
i::HandleScope scope(isolate);
i::Script::InitLineEnds(isolate, script);
CHECK(script->line_ends().IsFixedArray());
i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()),
isolate);
std::vector<int> result(line_ends->length());
for (int i = 0; i < line_ends->length(); ++i) {
i::Smi line_end = i::Smi::cast(line_ends->get(i));
result[i] = line_end.value();
}
return result;
}
MaybeLocal<String> Script::Name() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
i::HandleScope handle_scope(isolate);
i::Handle<i::Object> value(script->name(), isolate);
if (!value->IsString()) return MaybeLocal<String>();
return Utils::ToLocal(
handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
}
MaybeLocal<String> Script::SourceURL() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
i::HandleScope handle_scope(isolate);
i::Handle<i::Object> value(script->source_url(), isolate);
if (!value->IsString()) return MaybeLocal<String>();
return Utils::ToLocal(
handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
}
MaybeLocal<String> Script::SourceMappingURL() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
i::HandleScope handle_scope(isolate);
i::Handle<i::Object> value(script->source_mapping_url(), isolate);
if (!value->IsString()) return MaybeLocal<String>();
return Utils::ToLocal(
handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
}
Maybe<int> Script::ContextId() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
i::HandleScope handle_scope(isolate);
i::Object value = script->context_data();
if (value.IsSmi()) return Just(i::Smi::ToInt(value));
return Nothing<int>();
}
MaybeLocal<String> Script::Source() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
i::HandleScope handle_scope(isolate);
i::Handle<i::Object> value(script->source(), isolate);
if (!value->IsString()) return MaybeLocal<String>();
return Utils::ToLocal(
handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value)));
}
#if V8_ENABLE_WEBASSEMBLY
bool Script::IsWasm() const {
return Utils::OpenHandle(this)->type() == i::Script::TYPE_WASM;
}
#endif // V8_ENABLE_WEBASSEMBLY
bool Script::IsModule() const {
return Utils::OpenHandle(this)->origin_options().IsModule();
}
namespace {
int GetSmiValue(i::Handle<i::FixedArray> array, int index) {
return i::Smi::ToInt(array->get(index));
}
bool CompareBreakLocation(const i::BreakLocation& loc1,
const i::BreakLocation& loc2) {
return loc1.position() < loc2.position();
}
} // namespace
bool Script::GetPossibleBreakpoints(
const Location& start, const Location& end, bool restrict_to_function,
std::vector<BreakLocation>* locations) const {
CHECK(!start.IsEmpty());
i::Handle<i::Script> script = Utils::OpenHandle(this);
#if V8_ENABLE_WEBASSEMBLY
if (script->type() == i::Script::TYPE_WASM) {
i::wasm::NativeModule* native_module = script->wasm_native_module();
return i::WasmScript::GetPossibleBreakpoints(native_module, start, end,
locations);
}
#endif // V8_ENABLE_WEBASSEMBLY
i::Isolate* isolate = script->GetIsolate();
i::Script::InitLineEnds(isolate, script);
CHECK(script->line_ends().IsFixedArray());
i::Handle<i::FixedArray> line_ends =
i::Handle<i::FixedArray>::cast(i::handle(script->line_ends(), isolate));
CHECK(line_ends->length());
int start_offset = GetSourceOffset(start);
int end_offset = end.IsEmpty()
? GetSmiValue(line_ends, line_ends->length() - 1) + 1
: GetSourceOffset(end);
if (start_offset >= end_offset) return true;
std::vector<i::BreakLocation> v8_locations;
if (!isolate->debug()->GetPossibleBreakpoints(
script, start_offset, end_offset, restrict_to_function,
&v8_locations)) {
return false;
}
std::sort(v8_locations.begin(), v8_locations.end(), CompareBreakLocation);
int current_line_end_index = 0;
for (const auto& v8_location : v8_locations) {
int offset = v8_location.position();
while (offset > GetSmiValue(line_ends, current_line_end_index)) {
++current_line_end_index;
CHECK(current_line_end_index < line_ends->length());
}
int line_offset = 0;
if (current_line_end_index > 0) {
line_offset = GetSmiValue(line_ends, current_line_end_index - 1) + 1;
}
locations->emplace_back(
current_line_end_index + script->line_offset(),
offset - line_offset +
(current_line_end_index == 0 ? script->column_offset() : 0),
v8_location.type());
}
return true;
}
int Script::GetSourceOffset(const Location& location) const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
#if V8_ENABLE_WEBASSEMBLY
if (script->type() == i::Script::TYPE_WASM) {
DCHECK_EQ(0, location.GetLineNumber());
return location.GetColumnNumber();
}
#endif // V8_ENABLE_WEBASSEMBLY
int line = std::max(location.GetLineNumber() - script->line_offset(), 0);
int column = location.GetColumnNumber();
if (line == 0) {
column = std::max(0, column - script->column_offset());
}
i::Script::InitLineEnds(script->GetIsolate(), script);
CHECK(script->line_ends().IsFixedArray());
i::Handle<i::FixedArray> line_ends = i::Handle<i::FixedArray>::cast(
i::handle(script->line_ends(), script->GetIsolate()));
CHECK(line_ends->length());
if (line >= line_ends->length())
return GetSmiValue(line_ends, line_ends->length() - 1);
int line_offset = GetSmiValue(line_ends, line);
if (line == 0) return std::min(column, line_offset);
int prev_line_offset = GetSmiValue(line_ends, line - 1);
return std::min(prev_line_offset + column + 1, line_offset);
}
Location Script::GetSourceLocation(int offset) const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Script::PositionInfo info;
i::Script::GetPositionInfo(script, offset, &info, i::Script::WITH_OFFSET);
return Location(info.line, info.column);
}
bool Script::SetScriptSource(Local<String> newSource, bool preview,
LiveEditResult* result) const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
return isolate->debug()->SetScriptSource(
script, Utils::OpenHandle(*newSource), preview, result);
}
bool Script::SetBreakpoint(Local<String> condition, Location* location,
BreakpointId* id) const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
int offset = GetSourceOffset(*location);
if (!isolate->debug()->SetBreakPointForScript(
script, Utils::OpenHandle(*condition), &offset, id)) {
return false;
}
*location = GetSourceLocation(offset);
return true;
}
bool Script::SetBreakpointOnScriptEntry(BreakpointId* id) const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
#if V8_ENABLE_WEBASSEMBLY
if (script->type() == i::Script::TYPE_WASM) {
isolate->debug()->SetOnEntryBreakpointForWasmScript(script, id);
return true;
}
#endif // V8_ENABLE_WEBASSEMBLY
i::SharedFunctionInfo::ScriptIterator it(isolate, *script);
for (i::SharedFunctionInfo sfi = it.Next(); !sfi.is_null(); sfi = it.Next()) {
if (sfi.is_toplevel()) {
return isolate->debug()->SetBreakpointForFunction(
handle(sfi, isolate), isolate->factory()->empty_string(), id);
}
}
return false;
}
#if V8_ENABLE_WEBASSEMBLY
void Script::RemoveWasmBreakpoint(BreakpointId id) {
i::Handle<i::Script> script = Utils::OpenHandle(this);
i::Isolate* isolate = script->GetIsolate();
isolate->debug()->RemoveBreakpointForWasmScript(script, id);
}
#endif // V8_ENABLE_WEBASSEMBLY
void RemoveBreakpoint(Isolate* v8_isolate, BreakpointId id) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::HandleScope handle_scope(isolate);
isolate->debug()->RemoveBreakpoint(id);
}
Platform* GetCurrentPlatform() { return i::V8::GetCurrentPlatform(); }
void ForceGarbageCollection(
Isolate* isolate,
EmbedderHeapTracer::EmbedderStackState embedder_stack_state) {
i::Heap* heap = reinterpret_cast<i::Isolate*>(isolate)->heap();
heap->SetEmbedderStackStateForNextFinalization(embedder_stack_state);
isolate->LowMemoryNotification();
}
#if V8_ENABLE_WEBASSEMBLY
WasmScript* WasmScript::Cast(Script* script) {
CHECK(script->IsWasm());
return static_cast<WasmScript*>(script);
}
WasmScript::DebugSymbolsType WasmScript::GetDebugSymbolType() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
switch (script->wasm_native_module()->module()->debug_symbols.type) {
case i::wasm::WasmDebugSymbols::Type::None:
return WasmScript::DebugSymbolsType::None;
case i::wasm::WasmDebugSymbols::Type::EmbeddedDWARF:
return WasmScript::DebugSymbolsType::EmbeddedDWARF;
case i::wasm::WasmDebugSymbols::Type::ExternalDWARF:
return WasmScript::DebugSymbolsType::ExternalDWARF;
case i::wasm::WasmDebugSymbols::Type::SourceMap:
return WasmScript::DebugSymbolsType::SourceMap;
}
}
MemorySpan<const char> WasmScript::ExternalSymbolsURL() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
const i::wasm::WasmDebugSymbols& symbols =
script->wasm_native_module()->module()->debug_symbols;
if (symbols.external_url.is_empty()) return {};
internal::wasm::ModuleWireBytes wire_bytes(
script->wasm_native_module()->wire_bytes());
i::wasm::WasmName external_url =
wire_bytes.GetNameOrNull(symbols.external_url);
return {external_url.data(), external_url.size()};
}
int WasmScript::NumFunctions() const {
i::DisallowGarbageCollection no_gc;
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
DCHECK_GE(i::kMaxInt, module->functions.size());
return static_cast<int>(module->functions.size());
}
int WasmScript::NumImportedFunctions() const {
i::DisallowGarbageCollection no_gc;
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
DCHECK_GE(i::kMaxInt, module->num_imported_functions);
return static_cast<int>(module->num_imported_functions);
}
MemorySpan<const uint8_t> WasmScript::Bytecode() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
base::Vector<const uint8_t> wire_bytes =
script->wasm_native_module()->wire_bytes();
return {wire_bytes.begin(), wire_bytes.size()};
}
std::pair<int, int> WasmScript::GetFunctionRange(int function_index) const {
i::DisallowGarbageCollection no_gc;
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
DCHECK_LE(0, function_index);
DCHECK_GT(module->functions.size(), function_index);
const i::wasm::WasmFunction& func = module->functions[function_index];
DCHECK_GE(i::kMaxInt, func.code.offset());
DCHECK_GE(i::kMaxInt, func.code.end_offset());
return std::make_pair(static_cast<int>(func.code.offset()),
static_cast<int>(func.code.end_offset()));
}
int WasmScript::GetContainingFunction(int byte_offset) const {
i::DisallowGarbageCollection no_gc;
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
DCHECK_LE(0, byte_offset);
return i::wasm::GetContainingWasmFunction(module, byte_offset);
}
uint32_t WasmScript::GetFunctionHash(int function_index) {
i::DisallowGarbageCollection no_gc;
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
DCHECK_LE(0, function_index);
DCHECK_GT(module->functions.size(), function_index);
const i::wasm::WasmFunction& func = module->functions[function_index];
i::wasm::ModuleWireBytes wire_bytes(native_module->wire_bytes());
base::Vector<const i::byte> function_bytes =
wire_bytes.GetFunctionBytes(&func);
// TODO(herhut): Maybe also take module, name and signature into account.
return i::StringHasher::HashSequentialString(function_bytes.begin(),
function_bytes.length(), 0);
}
int WasmScript::CodeOffset() const {
i::Handle<i::Script> script = Utils::OpenHandle(this);
DCHECK_EQ(i::Script::TYPE_WASM, script->type());
i::wasm::NativeModule* native_module = script->wasm_native_module();
const i::wasm::WasmModule* module = native_module->module();
// If the module contains at least one function, the code offset must have
// been initialized, and it cannot be zero.
DCHECK_IMPLIES(module->num_declared_functions > 0,
module->code.offset() != 0);
return module->code.offset();
}
#endif // V8_ENABLE_WEBASSEMBLY
Location::Location(int line_number, int column_number)
: line_number_(line_number),
column_number_(column_number),
is_empty_(false) {}
Location::Location()
: line_number_(Function::kLineOffsetNotFound),
column_number_(Function::kLineOffsetNotFound),
is_empty_(true) {}
int Location::GetLineNumber() const {
DCHECK(!IsEmpty());
return line_number_;
}
int Location::GetColumnNumber() const {
DCHECK(!IsEmpty());
return column_number_;
}
bool Location::IsEmpty() const { return is_empty_; }
void GetLoadedScripts(Isolate* v8_isolate,
PersistentValueVector<Script>& scripts) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
{
i::DisallowGarbageCollection no_gc;
i::Script::Iterator iterator(isolate);
for (i::Script script = iterator.Next(); !script.is_null();
script = iterator.Next()) {
#if V8_ENABLE_WEBASSEMBLY
if (script.type() != i::Script::TYPE_NORMAL &&
script.type() != i::Script::TYPE_WASM) {
continue;
}
#else
if (script.type() != i::Script::TYPE_NORMAL) continue;
#endif // V8_ENABLE_WEBASSEMBLY
if (!script.HasValidSource()) continue;
i::HandleScope handle_scope(isolate);
i::Handle<i::Script> script_handle(script, isolate);
scripts.Append(ToApiHandle<Script>(script_handle));
}
}
}
MaybeLocal<UnboundScript> CompileInspectorScript(Isolate* v8_isolate,
Local<String> source) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, UnboundScript);
i::Handle<i::String> str = Utils::OpenHandle(*source);
i::Handle<i::SharedFunctionInfo> result;
{
i::AlignedCachedData* cached_data = nullptr;
i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
i::Compiler::GetSharedFunctionInfoForScriptWithCachedData(
isolate, str, i::ScriptDetails(), cached_data,
ScriptCompiler::kNoCompileOptions,
ScriptCompiler::kNoCacheBecauseInspector,
i::FLAG_expose_inspector_scripts ? i::NOT_NATIVES_CODE
: i::INSPECTOR_CODE);
has_pending_exception = !maybe_function_info.ToHandle(&result);
RETURN_ON_FAILED_EXECUTION(UnboundScript);
}
RETURN_ESCAPED(ToApiHandle<UnboundScript>(result));
}
#if V8_ENABLE_WEBASSEMBLY
void TierDownAllModulesPerIsolate(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::wasm::GetWasmEngine()->TierDownAllModulesPerIsolate(isolate);
}
void TierUpAllModulesPerIsolate(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::wasm::GetWasmEngine()->TierUpAllModulesPerIsolate(isolate);
}
#endif // V8_ENABLE_WEBASSEMBLY
void SetDebugDelegate(Isolate* v8_isolate, DebugDelegate* delegate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
isolate->debug()->SetDebugDelegate(delegate);
}
void SetAsyncEventDelegate(Isolate* v8_isolate, AsyncEventDelegate* delegate) {
reinterpret_cast<i::Isolate*>(v8_isolate)->set_async_event_delegate(delegate);
}
void ResetBlackboxedStateCache(Isolate* v8_isolate, Local<Script> script) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::DisallowGarbageCollection no_gc;
i::SharedFunctionInfo::ScriptIterator iter(isolate,
*Utils::OpenHandle(*script));
for (i::SharedFunctionInfo info = iter.Next(); !info.is_null();
info = iter.Next()) {
if (info.HasDebugInfo()) {
info.GetDebugInfo().set_computed_debug_is_blackboxed(false);
}
}
}
int EstimatedValueSize(Isolate* v8_isolate, Local<Value> value) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::Handle<i::Object> object = Utils::OpenHandle(*value);
if (object->IsSmi()) return i::kTaggedSize;
CHECK(object->IsHeapObject());
return i::Handle<i::HeapObject>::cast(object)->Size();
}
void AccessorPair::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsAccessorPair(), "v8::debug::AccessorPair::Cast",
"Value is not a v8::debug::AccessorPair");
}
#if V8_ENABLE_WEBASSEMBLY
void WasmValueObject::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsWasmValueObject(), "v8::debug::WasmValueObject::Cast",
"Value is not a v8::debug::WasmValueObject");
}
bool WasmValueObject::IsWasmValueObject(Local<Value> that) {
i::Handle<i::Object> obj = Utils::OpenHandle(*that);
return obj->IsWasmValueObject();
}
Local<String> WasmValueObject::type() const {
i::Handle<i::WasmValueObject> object =
i::Handle<i::WasmValueObject>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = object->GetIsolate();
i::Handle<i::String> type(object->type(), isolate);
return Utils::ToLocal(type);
}
#endif // V8_ENABLE_WEBASSEMBLY
Local<Function> GetBuiltin(Isolate* v8_isolate, Builtin requested_builtin) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::HandleScope handle_scope(isolate);
CHECK_EQ(requested_builtin, kStringToLowerCase);
i::Builtin builtin = i::Builtin::kStringPrototypeToLocaleLowerCase;
i::Factory* factory = isolate->factory();
i::Handle<i::String> name = isolate->factory()->empty_string();
i::Handle<i::NativeContext> context(isolate->native_context());
i::Handle<i::SharedFunctionInfo> info =
factory->NewSharedFunctionInfoForBuiltin(name, builtin);
info->set_language_mode(i::LanguageMode::kStrict);
i::Handle<i::JSFunction> fun =
i::Factory::JSFunctionBuilder{isolate, info, context}
.set_map(isolate->strict_function_without_prototype_map())
.Build();
fun->shared().set_internal_formal_parameter_count(i::JSParameterCount(0));
fun->shared().set_length(0);
return Utils::ToLocal(handle_scope.CloseAndEscape(fun));
}
void SetConsoleDelegate(Isolate* v8_isolate, ConsoleDelegate* delegate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
isolate->set_console_delegate(delegate);
}
ConsoleCallArguments::ConsoleCallArguments(
const v8::FunctionCallbackInfo<v8::Value>& info)
: v8::FunctionCallbackInfo<v8::Value>(nullptr, info.values_, info.length_) {
}
ConsoleCallArguments::ConsoleCallArguments(
const internal::BuiltinArguments& args)
: v8::FunctionCallbackInfo<v8::Value>(
nullptr,
// Drop the first argument (receiver, i.e. the "console" object).
args.length() > 1 ? args.address_of_first_argument() : nullptr,
args.length() - 1) {}
v8::Local<v8::StackTrace> GetDetailedStackTrace(
Isolate* v8_isolate, v8::Local<v8::Object> v8_error) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::Handle<i::JSReceiver> error = Utils::OpenHandle(*v8_error);
if (!error->IsJSObject()) {
return v8::Local<v8::StackTrace>();
}
i::Handle<i::FixedArray> stack_trace =
isolate->GetDetailedStackTrace(i::Handle<i::JSObject>::cast(error));
return Utils::StackTraceToLocal(stack_trace);
}
MaybeLocal<Script> GeneratorObject::Script() {
i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
i::Object maybe_script = obj->function().shared().script();
if (!maybe_script.IsScript()) return {};
i::Handle<i::Script> script(i::Script::cast(maybe_script), obj->GetIsolate());
return ToApiHandle<v8::debug::Script>(script);
}
Local<Function> GeneratorObject::Function() {
i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
return Utils::ToLocal(handle(obj->function(), obj->GetIsolate()));
}
Location GeneratorObject::SuspendedLocation() {
i::Handle<i::JSGeneratorObject> obj = Utils::OpenHandle(this);
CHECK(obj->is_suspended());
i::Object maybe_script = obj->function().shared().script();
if (!maybe_script.IsScript()) return Location();
i::Isolate* isolate = obj->GetIsolate();
i::Handle<i::Script> script(i::Script::cast(maybe_script), isolate);
i::Script::PositionInfo info;
i::SharedFunctionInfo::EnsureSourcePositionsAvailable(
isolate, i::handle(obj->function().shared(), isolate));
i::Script::GetPositionInfo(script, obj->source_position(), &info,
i::Script::WITH_OFFSET);
return Location(info.line, info.column);
}
bool GeneratorObject::IsSuspended() {
return Utils::OpenHandle(this)->is_suspended();
}
v8::Local<GeneratorObject> GeneratorObject::Cast(v8::Local<v8::Value> value) {
CHECK(value->IsGeneratorObject());
return ToApiHandle<GeneratorObject>(Utils::OpenHandle(*value));
}
MaybeLocal<Value> CallFunctionOn(Local<Context> context,
Local<Function> function, Local<Value> recv,
int argc, Local<Value> argv[],
bool throw_on_side_effect) {
auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(isolate, Value);
auto self = Utils::OpenHandle(*function);
auto recv_obj = Utils::OpenHandle(*recv);
STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Handle<i::Object>));
auto args = reinterpret_cast<i::Handle<i::Object>*>(argv);
// Disable breaks in side-effect free mode.
i::DisableBreak disable_break_scope(isolate->debug(), throw_on_side_effect);
if (throw_on_side_effect) {
isolate->debug()->StartSideEffectCheckMode();
}
Local<Value> result;
has_pending_exception = !ToLocal<Value>(
i::Execution::Call(isolate, self, recv_obj, argc, args), &result);
if (throw_on_side_effect) {
isolate->debug()->StopSideEffectCheckMode();
}
RETURN_ON_FAILED_EXECUTION(Value);
RETURN_ESCAPED(result);
}
MaybeLocal<v8::Value> EvaluateGlobal(v8::Isolate* isolate,
v8::Local<v8::String> source,
EvaluateGlobalMode mode, bool repl) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(internal_isolate, Value);
i::REPLMode repl_mode = repl ? i::REPLMode::kYes : i::REPLMode::kNo;
Local<Value> result;
has_pending_exception = !ToLocal<Value>(
i::DebugEvaluate::Global(internal_isolate, Utils::OpenHandle(*source),
mode, repl_mode),
&result);
RETURN_ON_FAILED_EXECUTION(Value);
RETURN_ESCAPED(result);
}
v8::MaybeLocal<v8::Value> EvaluateGlobalForTesting(
v8::Isolate* isolate, v8::Local<v8::Script> function,
v8::debug::EvaluateGlobalMode mode, bool repl) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
PREPARE_FOR_DEBUG_INTERFACE_EXECUTION_WITH_ISOLATE(internal_isolate, Value);
i::REPLMode repl_mode = repl ? i::REPLMode::kYes : i::REPLMode::kNo;
Local<Value> result;
has_pending_exception = !ToLocal<Value>(
i::DebugEvaluate::Global(internal_isolate, Utils::OpenHandle(*function),
mode, repl_mode),
&result);
RETURN_ON_FAILED_EXECUTION(Value);
RETURN_ESCAPED(result);
}
void QueryObjects(v8::Local<v8::Context> v8_context,
QueryObjectPredicate* predicate,
PersistentValueVector<v8::Object>* objects) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_context->GetIsolate());
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
isolate->heap_profiler()->QueryObjects(Utils::OpenHandle(*v8_context),
predicate, objects);
}
void GlobalLexicalScopeNames(v8::Local<v8::Context> v8_context,
v8::PersistentValueVector<v8::String>* names) {
i::Handle<i::Context> context = Utils::OpenHandle(*v8_context);
i::Isolate* isolate = context->GetIsolate();
i::Handle<i::ScriptContextTable> table(
context->global_object().native_context().script_context_table(),
isolate);
for (int i = 0; i < table->used(kAcquireLoad); i++) {
i::Handle<i::Context> script_context =
i::ScriptContextTable::GetContext(isolate, table, i);
DCHECK(script_context->IsScriptContext());
i::Handle<i::ScopeInfo> scope_info(script_context->scope_info(), isolate);
int local_count = scope_info->ContextLocalCount();
for (int j = 0; j < local_count; ++j) {
i::String name = scope_info->ContextLocalName(j);
if (i::ScopeInfo::VariableIsSynthetic(name)) continue;
names->Append(Utils::ToLocal(handle(name, isolate)));
}
}
}
void SetReturnValue(v8::Isolate* v8_isolate, v8::Local<v8::Value> value) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
isolate->debug()->set_return_value(*Utils::OpenHandle(*value));
}
int64_t GetNextRandomInt64(v8::Isolate* v8_isolate) {
return reinterpret_cast<i::Isolate*>(v8_isolate)
->random_number_generator()
->NextInt64();
}
int GetDebuggingId(v8::Local<v8::Function> function) {
i::Handle<i::JSReceiver> callable = v8::Utils::OpenHandle(*function);
if (!callable->IsJSFunction()) return i::DebugInfo::kNoDebuggingId;
i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(callable);
int id = func->GetIsolate()->debug()->GetFunctionDebuggingId(func);
DCHECK_NE(i::DebugInfo::kNoDebuggingId, id);
return id;
}
bool SetFunctionBreakpoint(v8::Local<v8::Function> function,
v8::Local<v8::String> condition, BreakpointId* id) {
i::Handle<i::JSReceiver> callable = Utils::OpenHandle(*function);
if (!callable->IsJSFunction()) return false;
i::Handle<i::JSFunction> jsfunction =
i::Handle<i::JSFunction>::cast(callable);
i::Isolate* isolate = jsfunction->GetIsolate();
i::Handle<i::String> condition_string =
condition.IsEmpty() ? isolate->factory()->empty_string()
: Utils::OpenHandle(*condition);
return isolate->debug()->SetBreakpointForFunction(
handle(jsfunction->shared(), isolate), condition_string, id);
}
PostponeInterruptsScope::PostponeInterruptsScope(v8::Isolate* isolate)
: scope_(
new i::PostponeInterruptsScope(reinterpret_cast<i::Isolate*>(isolate),
i::StackGuard::API_INTERRUPT)) {}
PostponeInterruptsScope::~PostponeInterruptsScope() = default;
DisableBreakScope::DisableBreakScope(v8::Isolate* isolate)
: scope_(std::make_unique<i::DisableBreak>(
reinterpret_cast<i::Isolate*>(isolate)->debug())) {}
DisableBreakScope::~DisableBreakScope() = default;
int Coverage::BlockData::StartOffset() const { return block_->start; }
int Coverage::BlockData::EndOffset() const { return block_->end; }
uint32_t Coverage::BlockData::Count() const { return block_->count; }
int Coverage::FunctionData::StartOffset() const { return function_->start; }
int Coverage::FunctionData::EndOffset() const { return function_->end; }
uint32_t Coverage::FunctionData::Count() const { return function_->count; }
MaybeLocal<String> Coverage::FunctionData::Name() const {
return ToApiHandle<String>(function_->name);
}
size_t Coverage::FunctionData::BlockCount() const {
return function_->blocks.size();
}
bool Coverage::FunctionData::HasBlockCoverage() const {
return function_->has_block_coverage;
}
Coverage::BlockData Coverage::FunctionData::GetBlockData(size_t i) const {
return BlockData(&function_->blocks.at(i), coverage_);
}
Local<Script> Coverage::ScriptData::GetScript() const {
return ToApiHandle<Script>(script_->script);
}
size_t Coverage::ScriptData::FunctionCount() const {
return script_->functions.size();
}
Coverage::FunctionData Coverage::ScriptData::GetFunctionData(size_t i) const {
return FunctionData(&script_->functions.at(i), coverage_);
}
Coverage::ScriptData::ScriptData(size_t index,
std::shared_ptr<i::Coverage> coverage)
: script_(&coverage->at(index)), coverage_(std::move(coverage)) {}
size_t Coverage::ScriptCount() const { return coverage_->size(); }
Coverage::ScriptData Coverage::GetScriptData(size_t i) const {
return ScriptData(i, coverage_);
}
Coverage Coverage::CollectPrecise(Isolate* isolate) {
return Coverage(
i::Coverage::CollectPrecise(reinterpret_cast<i::Isolate*>(isolate)));
}
Coverage Coverage::CollectBestEffort(Isolate* isolate) {
return Coverage(
i::Coverage::CollectBestEffort(reinterpret_cast<i::Isolate*>(isolate)));
}
void Coverage::SelectMode(Isolate* isolate, CoverageMode mode) {
i::Coverage::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
}
int TypeProfile::Entry::SourcePosition() const { return entry_->position; }
std::vector<MaybeLocal<String>> TypeProfile::Entry::Types() const {
std::vector<MaybeLocal<String>> result;
for (const internal::Handle<internal::String>& type : entry_->types) {
result.emplace_back(ToApiHandle<String>(type));
}
return result;
}
TypeProfile::ScriptData::ScriptData(
size_t index, std::shared_ptr<i::TypeProfile> type_profile)
: script_(&type_profile->at(index)),
type_profile_(std::move(type_profile)) {}
Local<Script> TypeProfile::ScriptData::GetScript() const {
return ToApiHandle<Script>(script_->script);
}
std::vector<TypeProfile::Entry> TypeProfile::ScriptData::Entries() const {
std::vector<TypeProfile::Entry> result;
for (const internal::TypeProfileEntry& entry : script_->entries) {
result.push_back(TypeProfile::Entry(&entry, type_profile_));
}
return result;
}
TypeProfile TypeProfile::Collect(Isolate* isolate) {
return TypeProfile(
i::TypeProfile::Collect(reinterpret_cast<i::Isolate*>(isolate)));
}
void TypeProfile::SelectMode(Isolate* isolate, TypeProfileMode mode) {
i::TypeProfile::SelectMode(reinterpret_cast<i::Isolate*>(isolate), mode);
}
size_t TypeProfile::ScriptCount() const { return type_profile_->size(); }
TypeProfile::ScriptData TypeProfile::GetScriptData(size_t i) const {
return ScriptData(i, type_profile_);
}
MaybeLocal<v8::Value> EphemeronTable::Get(v8::Isolate* isolate,
v8::Local<v8::Value> key) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
auto self = i::Handle<i::EphemeronHashTable>::cast(Utils::OpenHandle(this));
i::Handle<i::Object> internal_key = Utils::OpenHandle(*key);
DCHECK(internal_key->IsJSReceiver());
i::Handle<i::Object> value(self->Lookup(internal_key), internal_isolate);
if (value->IsTheHole()) return {};
return Utils::ToLocal(value);
}
Local<EphemeronTable> EphemeronTable::Set(v8::Isolate* isolate,
v8::Local<v8::Value> key,
v8::Local<v8::Value> value) {
auto self = i::Handle<i::EphemeronHashTable>::cast(Utils::OpenHandle(this));
i::Handle<i::Object> internal_key = Utils::OpenHandle(*key);
i::Handle<i::Object> internal_value = Utils::OpenHandle(*value);
DCHECK(internal_key->IsJSReceiver());
i::Handle<i::EphemeronHashTable> result(
i::EphemeronHashTable::Put(self, internal_key, internal_value));
return ToApiHandle<EphemeronTable>(result);
}
Local<EphemeronTable> EphemeronTable::New(v8::Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate);
i::Handle<i::EphemeronHashTable> table =
i::EphemeronHashTable::New(i_isolate, 0);
return ToApiHandle<EphemeronTable>(table);
}
EphemeronTable* EphemeronTable::Cast(v8::Value* value) {
return static_cast<EphemeronTable*>(value);
}
Local<Value> AccessorPair::getter() {
i::Handle<i::AccessorPair> accessors = Utils::OpenHandle(this);
i::Isolate* isolate = accessors->GetIsolate();
i::Handle<i::Object> getter(accessors->getter(), isolate);
return Utils::ToLocal(getter);
}
Local<Value> AccessorPair::setter() {
i::Handle<i::AccessorPair> accessors = Utils::OpenHandle(this);
i::Isolate* isolate = accessors->GetIsolate();
i::Handle<i::Object> setter(accessors->setter(), isolate);
return Utils::ToLocal(setter);
}
bool AccessorPair::IsAccessorPair(Local<Value> that) {
i::Handle<i::Object> obj = Utils::OpenHandle(*that);
return obj->IsAccessorPair();
}
MaybeLocal<Message> GetMessageFromPromise(Local<Promise> p) {
i::Handle<i::JSPromise> promise = Utils::OpenHandle(*p);
i::Isolate* isolate = promise->GetIsolate();
i::Handle<i::Symbol> key = isolate->factory()->promise_debug_message_symbol();
i::Handle<i::Object> maybeMessage =
i::JSReceiver::GetDataProperty(promise, key);
if (!maybeMessage->IsJSMessageObject(isolate)) return MaybeLocal<Message>();
return ToApiHandle<Message>(
i::Handle<i::JSMessageObject>::cast(maybeMessage));
}
bool isExperimentalAsyncStackTaggingApiEnabled() {
return v8::internal::FLAG_experimental_async_stack_tagging_api;
}
std::unique_ptr<PropertyIterator> PropertyIterator::Create(
Local<Context> context, Local<Object> object, bool skip_indices) {
internal::Isolate* isolate =
reinterpret_cast<i::Isolate*>(object->GetIsolate());
if (IsExecutionTerminatingCheck(isolate)) {
return nullptr;
}
CallDepthScope<false> call_depth_scope(isolate, context);
auto result = i::DebugPropertyIterator::Create(
isolate, Utils::OpenHandle(*object), skip_indices);
if (!result) {
DCHECK(isolate->has_pending_exception());
call_depth_scope.Escape();
}
return result;
}
} // namespace debug
namespace internal {
Maybe<bool> DebugPropertyIterator::Advance() {
if (IsExecutionTerminatingCheck(isolate_)) {
return Nothing<bool>();
}
Local<v8::Context> context =
Utils::ToLocal(handle(isolate_->context(), isolate_));
CallDepthScope<false> call_depth_scope(isolate_, context);
if (!AdvanceInternal()) {
DCHECK(isolate_->has_pending_exception());
call_depth_scope.Escape();
return Nothing<bool>();
}
return Just(true);
}
} // namespace internal
} // namespace v8
#include "src/api/api-macros-undef.h"
| 38.193972 | 80 | 0.697246 | [
"object",
"vector"
] |
f58a96d6de87a9dc18ce6d24815538c5f1493a71 | 19,138 | cc | C++ | base/profiler/stack_sampler_impl_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | base/profiler/stack_sampler_impl_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | base/profiler/stack_sampler_impl_unittest.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 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 <algorithm>
#include <cstring>
#include <iterator>
#include <memory>
#include <numeric>
#include <utility>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/profiler/module_cache.h"
#include "base/profiler/profile_builder.h"
#include "base/profiler/stack_buffer.h"
#include "base/profiler/stack_copier.h"
#include "base/profiler/stack_sampler_impl.h"
#include "base/profiler/suspendable_thread_delegate.h"
#include "base/profiler/unwinder.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
using ::testing::ElementsAre;
class TestProfileBuilder : public ProfileBuilder {
public:
TestProfileBuilder(ModuleCache* module_cache) : module_cache_(module_cache) {}
TestProfileBuilder(const TestProfileBuilder&) = delete;
TestProfileBuilder& operator=(const TestProfileBuilder&) = delete;
// ProfileBuilder
ModuleCache* GetModuleCache() override { return module_cache_; }
void RecordMetadata(
const MetadataRecorder::MetadataProvider& metadata_provider) override {}
void OnSampleCompleted(std::vector<Frame> frames,
TimeTicks sample_timestamp) override {
last_timestamp_ = sample_timestamp;
}
void OnProfileCompleted(TimeDelta profile_duration,
TimeDelta sampling_period) override {}
TimeTicks last_timestamp() { return last_timestamp_; }
private:
raw_ptr<ModuleCache> module_cache_;
TimeTicks last_timestamp_;
};
// A stack copier for use in tests that provides the expected behavior when
// operating on the supplied fake stack.
class TestStackCopier : public StackCopier {
public:
TestStackCopier(const std::vector<uintptr_t>& fake_stack,
TimeTicks timestamp = TimeTicks())
: fake_stack_(fake_stack), timestamp_(timestamp) {}
bool CopyStack(StackBuffer* stack_buffer,
uintptr_t* stack_top,
TimeTicks* timestamp,
RegisterContext* thread_context,
Delegate* delegate) override {
std::memcpy(stack_buffer->buffer(), &fake_stack_[0], fake_stack_.size());
*stack_top =
reinterpret_cast<uintptr_t>(&fake_stack_[0] + fake_stack_.size());
// Set the stack pointer to be consistent with the provided fake stack.
*thread_context = {};
RegisterContextStackPointer(thread_context) =
reinterpret_cast<uintptr_t>(&fake_stack_[0]);
*timestamp = timestamp_;
return true;
}
private:
// Must be a reference to retain the underlying allocation from the vector
// passed to the constructor.
const std::vector<uintptr_t>& fake_stack_;
const TimeTicks timestamp_;
};
// A StackCopier that just invokes the expected functions on the delegate.
class DelegateInvokingStackCopier : public StackCopier {
public:
bool CopyStack(StackBuffer* stack_buffer,
uintptr_t* stack_top,
TimeTicks* timestamp,
RegisterContext* thread_context,
Delegate* delegate) override {
delegate->OnStackCopy();
return true;
}
};
// Trivial unwinder implementation for testing.
class TestUnwinder : public Unwinder {
public:
TestUnwinder(size_t stack_size = 0,
std::vector<uintptr_t>* stack_copy = nullptr,
// Variable to fill in with the bottom address of the
// copied stack. This will be different than
// &(*stack_copy)[0] because |stack_copy| is a copy of the
// copy so does not share memory with the actual copy.
uintptr_t* stack_copy_bottom = nullptr)
: stack_size_(stack_size),
stack_copy_(stack_copy),
stack_copy_bottom_(stack_copy_bottom) {}
bool CanUnwindFrom(const Frame& current_frame) const override { return true; }
UnwindResult TryUnwind(RegisterContext* thread_context,
uintptr_t stack_top,
std::vector<Frame>* stack) const override {
if (stack_copy_) {
auto* bottom = reinterpret_cast<uintptr_t*>(
RegisterContextStackPointer(thread_context));
auto* top = bottom + stack_size_;
*stack_copy_ = std::vector<uintptr_t>(bottom, top);
}
if (stack_copy_bottom_)
*stack_copy_bottom_ = RegisterContextStackPointer(thread_context);
return UnwindResult::kCompleted;
}
private:
size_t stack_size_;
raw_ptr<std::vector<uintptr_t>> stack_copy_;
raw_ptr<uintptr_t> stack_copy_bottom_;
};
// Records invocations of calls to OnStackCapture()/UpdateModules().
class CallRecordingUnwinder : public Unwinder {
public:
void OnStackCapture() override { on_stack_capture_was_invoked_ = true; }
void UpdateModules() override { update_modules_was_invoked_ = true; }
bool CanUnwindFrom(const Frame& current_frame) const override { return true; }
UnwindResult TryUnwind(RegisterContext* thread_context,
uintptr_t stack_top,
std::vector<Frame>* stack) const override {
return UnwindResult::kUnrecognizedFrame;
}
bool on_stack_capture_was_invoked() const {
return on_stack_capture_was_invoked_;
}
bool update_modules_was_invoked() const {
return update_modules_was_invoked_;
}
private:
bool on_stack_capture_was_invoked_ = false;
bool update_modules_was_invoked_ = false;
};
class TestModule : public ModuleCache::Module {
public:
TestModule(uintptr_t base_address, size_t size, bool is_native = true)
: base_address_(base_address), size_(size), is_native_(is_native) {}
uintptr_t GetBaseAddress() const override { return base_address_; }
std::string GetId() const override { return ""; }
FilePath GetDebugBasename() const override { return FilePath(); }
size_t GetSize() const override { return size_; }
bool IsNative() const override { return is_native_; }
private:
const uintptr_t base_address_;
const size_t size_;
const bool is_native_;
};
// Utility function to form a vector from a single module.
std::vector<std::unique_ptr<const ModuleCache::Module>> ToModuleVector(
std::unique_ptr<const ModuleCache::Module> module) {
return std::vector<std::unique_ptr<const ModuleCache::Module>>(
std::make_move_iterator(&module), std::make_move_iterator(&module + 1));
}
// Injects a fake module covering the initial instruction pointer value, to
// avoid asking the OS to look it up. Windows doesn't return a consistent error
// code when doing so, and we DCHECK_EQ the expected error code.
void InjectModuleForContextInstructionPointer(
const std::vector<uintptr_t>& stack,
ModuleCache* module_cache) {
module_cache->AddCustomNativeModule(
std::make_unique<TestModule>(stack[0], sizeof(uintptr_t)));
}
// Returns a plausible instruction pointer value for use in tests that don't
// care about the instruction pointer value in the context, and hence don't need
// InjectModuleForContextInstructionPointer().
uintptr_t GetTestInstructionPointer() {
return reinterpret_cast<uintptr_t>(&GetTestInstructionPointer);
}
// An unwinder fake that replays the provided outputs.
class FakeTestUnwinder : public Unwinder {
public:
struct Result {
Result(bool can_unwind)
: can_unwind(can_unwind), result(UnwindResult::kUnrecognizedFrame) {}
Result(UnwindResult result, std::vector<uintptr_t> instruction_pointers)
: can_unwind(true),
result(result),
instruction_pointers(instruction_pointers) {}
bool can_unwind;
UnwindResult result;
std::vector<uintptr_t> instruction_pointers;
};
// Construct the unwinder with the outputs. The relevant unwinder functions
// are expected to be invoked at least as many times as the number of values
// specified in the arrays (except for CanUnwindFrom() which will always
// return true if provided an empty array.
explicit FakeTestUnwinder(std::vector<Result> results)
: results_(std::move(results)) {}
FakeTestUnwinder(const FakeTestUnwinder&) = delete;
FakeTestUnwinder& operator=(const FakeTestUnwinder&) = delete;
bool CanUnwindFrom(const Frame& current_frame) const override {
bool can_unwind = results_[current_unwind_].can_unwind;
// NB: If CanUnwindFrom() returns false then TryUnwind() will not be
// invoked, so current_unwind_ is guarantee to be incremented only once for
// each result.
if (!can_unwind)
++current_unwind_;
return can_unwind;
}
UnwindResult TryUnwind(RegisterContext* thread_context,
uintptr_t stack_top,
std::vector<Frame>* stack) const override {
CHECK_LT(current_unwind_, results_.size());
const Result& current_result = results_[current_unwind_];
++current_unwind_;
CHECK(current_result.can_unwind);
for (const auto instruction_pointer : current_result.instruction_pointers)
stack->emplace_back(
instruction_pointer,
module_cache()->GetModuleForAddress(instruction_pointer));
return current_result.result;
}
private:
mutable size_t current_unwind_ = 0;
std::vector<Result> results_;
};
StackSampler::UnwindersFactory MakeUnwindersFactory(
std::unique_ptr<Unwinder> unwinder) {
return BindOnce(
[](std::unique_ptr<Unwinder> unwinder) {
std::vector<std::unique_ptr<Unwinder>> unwinders;
unwinders.push_back(std::move(unwinder));
return unwinders;
},
std::move(unwinder));
}
base::circular_deque<std::unique_ptr<Unwinder>> MakeUnwinderCircularDeque(
std::unique_ptr<Unwinder> native_unwinder,
std::unique_ptr<Unwinder> aux_unwinder) {
base::circular_deque<std::unique_ptr<Unwinder>> unwinders;
if (native_unwinder)
unwinders.push_front(std::move(native_unwinder));
if (aux_unwinder)
unwinders.push_front(std::move(aux_unwinder));
return unwinders;
}
} // namespace
// TODO(crbug.com/1001923): Fails on Linux MSan.
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
#define MAYBE_CopyStack DISABLED_MAYBE_CopyStack
#else
#define MAYBE_CopyStack CopyStack
#endif
TEST(StackSamplerImplTest, MAYBE_CopyStack) {
ModuleCache module_cache;
const std::vector<uintptr_t> stack = {0, 1, 2, 3, 4};
InjectModuleForContextInstructionPointer(stack, &module_cache);
std::vector<uintptr_t> stack_copy;
StackSamplerImpl stack_sampler_impl(
std::make_unique<TestStackCopier>(stack),
MakeUnwindersFactory(
std::make_unique<TestUnwinder>(stack.size(), &stack_copy)),
&module_cache);
stack_sampler_impl.Initialize();
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
TestProfileBuilder profile_builder(&module_cache);
stack_sampler_impl.RecordStackFrames(stack_buffer.get(), &profile_builder);
EXPECT_EQ(stack, stack_copy);
}
TEST(StackSamplerImplTest, CopyStackTimestamp) {
ModuleCache module_cache;
const std::vector<uintptr_t> stack = {0};
InjectModuleForContextInstructionPointer(stack, &module_cache);
std::vector<uintptr_t> stack_copy;
TimeTicks timestamp = TimeTicks::UnixEpoch();
StackSamplerImpl stack_sampler_impl(
std::make_unique<TestStackCopier>(stack, timestamp),
MakeUnwindersFactory(
std::make_unique<TestUnwinder>(stack.size(), &stack_copy)),
&module_cache);
stack_sampler_impl.Initialize();
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
TestProfileBuilder profile_builder(&module_cache);
stack_sampler_impl.RecordStackFrames(stack_buffer.get(), &profile_builder);
EXPECT_EQ(timestamp, profile_builder.last_timestamp());
}
TEST(StackSamplerImplTest, UnwinderInvokedWhileRecordingStackFrames) {
std::unique_ptr<StackBuffer> stack_buffer = std::make_unique<StackBuffer>(10);
auto owned_unwinder = std::make_unique<CallRecordingUnwinder>();
CallRecordingUnwinder* unwinder = owned_unwinder.get();
ModuleCache module_cache;
TestProfileBuilder profile_builder(&module_cache);
StackSamplerImpl stack_sampler_impl(
std::make_unique<DelegateInvokingStackCopier>(),
MakeUnwindersFactory(std::move(owned_unwinder)), &module_cache);
stack_sampler_impl.Initialize();
stack_sampler_impl.RecordStackFrames(stack_buffer.get(), &profile_builder);
EXPECT_TRUE(unwinder->on_stack_capture_was_invoked());
EXPECT_TRUE(unwinder->update_modules_was_invoked());
}
TEST(StackSamplerImplTest, AuxUnwinderInvokedWhileRecordingStackFrames) {
std::unique_ptr<StackBuffer> stack_buffer = std::make_unique<StackBuffer>(10);
ModuleCache module_cache;
TestProfileBuilder profile_builder(&module_cache);
StackSamplerImpl stack_sampler_impl(
std::make_unique<DelegateInvokingStackCopier>(),
MakeUnwindersFactory(std::make_unique<CallRecordingUnwinder>()),
&module_cache);
stack_sampler_impl.Initialize();
auto owned_aux_unwinder = std::make_unique<CallRecordingUnwinder>();
CallRecordingUnwinder* aux_unwinder = owned_aux_unwinder.get();
stack_sampler_impl.AddAuxUnwinder(std::move(owned_aux_unwinder));
stack_sampler_impl.RecordStackFrames(stack_buffer.get(), &profile_builder);
EXPECT_TRUE(aux_unwinder->on_stack_capture_was_invoked());
EXPECT_TRUE(aux_unwinder->update_modules_was_invoked());
}
TEST(StackSamplerImplTest, WalkStack_Completed) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) =
GetTestInstructionPointer();
module_cache.AddCustomNativeModule(std::make_unique<TestModule>(1u, 1u));
auto native_unwinder =
WrapUnique(new FakeTestUnwinder({{UnwindResult::kCompleted, {1u}}}));
native_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(std::move(native_unwinder), nullptr));
ASSERT_EQ(2u, stack.size());
EXPECT_EQ(1u, stack[1].instruction_pointer);
}
TEST(StackSamplerImplTest, WalkStack_Aborted) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) =
GetTestInstructionPointer();
module_cache.AddCustomNativeModule(std::make_unique<TestModule>(1u, 1u));
auto native_unwinder =
WrapUnique(new FakeTestUnwinder({{UnwindResult::kAborted, {1u}}}));
native_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(std::move(native_unwinder), nullptr));
ASSERT_EQ(2u, stack.size());
EXPECT_EQ(1u, stack[1].instruction_pointer);
}
TEST(StackSamplerImplTest, WalkStack_NotUnwound) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) =
GetTestInstructionPointer();
auto native_unwinder = WrapUnique(
new FakeTestUnwinder({{UnwindResult::kUnrecognizedFrame, {}}}));
native_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(std::move(native_unwinder), nullptr));
ASSERT_EQ(1u, stack.size());
}
TEST(StackSamplerImplTest, WalkStack_AuxUnwind) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) =
GetTestInstructionPointer();
// Treat the context instruction pointer as being in the aux unwinder's
// non-native module.
module_cache.UpdateNonNativeModules(
{}, ToModuleVector(std::make_unique<TestModule>(
GetTestInstructionPointer(), 1u, false)));
auto aux_unwinder =
WrapUnique(new FakeTestUnwinder({{UnwindResult::kAborted, {1u}}}));
aux_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(nullptr, std::move(aux_unwinder)));
ASSERT_EQ(2u, stack.size());
EXPECT_EQ(GetTestInstructionPointer(), stack[0].instruction_pointer);
EXPECT_EQ(1u, stack[1].instruction_pointer);
}
TEST(StackSamplerImplTest, WalkStack_AuxThenNative) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) = 0u;
// Treat the context instruction pointer as being in the aux unwinder's
// non-native module.
module_cache.UpdateNonNativeModules(
{}, ToModuleVector(std::make_unique<TestModule>(0u, 1u, false)));
// Inject a fake native module for the second frame.
module_cache.AddCustomNativeModule(std::make_unique<TestModule>(1u, 1u));
auto aux_unwinder = WrapUnique(
new FakeTestUnwinder({{UnwindResult::kUnrecognizedFrame, {1u}}, false}));
aux_unwinder->Initialize(&module_cache);
auto native_unwinder =
WrapUnique(new FakeTestUnwinder({{UnwindResult::kCompleted, {2u}}}));
native_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(std::move(native_unwinder),
std::move(aux_unwinder)));
ASSERT_EQ(3u, stack.size());
EXPECT_EQ(0u, stack[0].instruction_pointer);
EXPECT_EQ(1u, stack[1].instruction_pointer);
EXPECT_EQ(2u, stack[2].instruction_pointer);
}
TEST(StackSamplerImplTest, WalkStack_NativeThenAux) {
ModuleCache module_cache;
RegisterContext thread_context;
RegisterContextInstructionPointer(&thread_context) = 0u;
// Inject fake native modules for the instruction pointer from the context and
// the third frame.
module_cache.AddCustomNativeModule(std::make_unique<TestModule>(0u, 1u));
module_cache.AddCustomNativeModule(std::make_unique<TestModule>(2u, 1u));
// Treat the second frame's pointer as being in the aux unwinder's non-native
// module.
module_cache.UpdateNonNativeModules(
{}, ToModuleVector(std::make_unique<TestModule>(1u, 1u, false)));
auto aux_unwinder = WrapUnique(new FakeTestUnwinder(
{{false}, {UnwindResult::kUnrecognizedFrame, {2u}}, {false}}));
aux_unwinder->Initialize(&module_cache);
auto native_unwinder =
WrapUnique(new FakeTestUnwinder({{UnwindResult::kUnrecognizedFrame, {1u}},
{UnwindResult::kCompleted, {3u}}}));
native_unwinder->Initialize(&module_cache);
std::vector<Frame> stack = StackSamplerImpl::WalkStackForTesting(
&module_cache, &thread_context, 0u,
MakeUnwinderCircularDeque(std::move(native_unwinder),
std::move(aux_unwinder)));
ASSERT_EQ(4u, stack.size());
EXPECT_EQ(0u, stack[0].instruction_pointer);
EXPECT_EQ(1u, stack[1].instruction_pointer);
EXPECT_EQ(2u, stack[2].instruction_pointer);
EXPECT_EQ(3u, stack[3].instruction_pointer);
}
} // namespace base
| 36.803846 | 80 | 0.736441 | [
"vector"
] |
f58ce05028944eaf02d7ba8d2df2cc728bc4f5ec | 4,726 | hpp | C++ | src/dsl/word/emit/Delay.hpp | KipHamiltons/NUClear | 1c6147b3fda26c3796f133881f0bf626261db574 | [
"MIT"
] | 6 | 2015-04-09T04:23:58.000Z | 2020-12-10T04:35:13.000Z | src/dsl/word/emit/Delay.hpp | KipHamiltons/NUClear | 1c6147b3fda26c3796f133881f0bf626261db574 | [
"MIT"
] | 12 | 2015-01-21T16:42:43.000Z | 2021-09-29T10:06:45.000Z | src/dsl/word/emit/Delay.hpp | KipHamiltons/NUClear | 1c6147b3fda26c3796f133881f0bf626261db574 | [
"MIT"
] | 15 | 2015-04-10T00:33:38.000Z | 2021-09-24T23:42:55.000Z | /*
* Copyright (C) 2013 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com>
* 2014-2017 Trent Houliston <trent@houliston.me>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef NUCLEAR_DSL_WORD_EMIT_DELAY_HPP
#define NUCLEAR_DSL_WORD_EMIT_DELAY_HPP
#include "../../operation/ChronoTask.hpp"
#include "Direct.hpp"
namespace NUClear {
namespace dsl {
namespace word {
namespace emit {
/**
* @brief
* This will emit data, after the provided delay.
*
* @details
* @code emit<Scope::DELAY>(data, delay(ticks), dataType); @endcode
* Emissions under this scope will wait for the provided time delay, and then emit the object utilising a
* local emit (that is, normal threadpool distribution).
*
* @param data
* the data to emit
* @param delay(ticks)
* the time to wait before emitting this object. Use delay to specify the unit in which to measure the
* ticks, this will default to clock duration, but can accept any of the defined std::chrono durations
* (nanoseconds, microseconds, milliseconds, seconds, minutes, hours). Note that you can also define your
* own unit: See http://en.cppreference.com/w/cpp/chrono/duration. Use an int to specify the number of
* ticks to wait.
* @tparam DataType
* the datatype of the object to emit
*/
template <typename DataType>
struct Delay {
static void emit(PowerPlant& powerplant,
std::shared_ptr<DataType> data,
NUClear::clock::duration delay) {
// Our chrono task is just to do a normal emit in the amount of time
auto msg = std::make_shared<operation::ChronoTask>(
[&powerplant, data](NUClear::clock::time_point&) {
// Do the emit
emit::Local<DataType>::emit(powerplant, data);
// We don't renew, remove us
return false;
},
NUClear::clock::now() + delay,
-1); // Our ID is -1 as we will remove ourselves
// Send this straight to the chrono controller
emit::Direct<operation::ChronoTask>::emit(powerplant, msg);
}
static void emit(PowerPlant& powerplant,
std::shared_ptr<DataType> data,
NUClear::clock::time_point at_time) {
// Our chrono task is just to do a normal emit in the amount of time
auto msg = std::make_shared<operation::ChronoTask>(
[&powerplant, data](NUClear::clock::time_point&) {
// Do the emit
emit::Local<DataType>::emit(powerplant, data);
// We don't renew, remove us
return false;
},
at_time,
-1); // Our ID is -1 as we will remove ourselves
// Send this straight to the chrono controller
emit::Direct<operation::ChronoTask>::emit(powerplant, msg);
}
};
} // namespace emit
} // namespace word
} // namespace dsl
} // namespace NUClear
#endif // NUCLEAR_DSL_WORD_EMIT_DELAY_HPP
| 47.26 | 120 | 0.570461 | [
"object"
] |
f58f97534806914db3e667e1b45504fa2a3da381 | 19,477 | cpp | C++ | APEX_1.4/framework/src/MirrorSceneImpl.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | APEX_1.4/framework/src/MirrorSceneImpl.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | APEX_1.4/framework/src/MirrorSceneImpl.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2018-2019 NVIDIA Corporation. All rights reserved.
#include "MirrorSceneImpl.h"
#if PX_PHYSICS_VERSION_MAJOR == 3
#include "PxScene.h"
#include "PxRigidDynamic.h"
#include "PxMaterial.h"
#include "PxSphereGeometry.h"
#include "PxRigidDynamic.h"
#include "PxRigidStatic.h"
#include "PxShape.h"
#include "ApexSDKIntl.h"
#include "PsInlineArray.h"
#include "PxPhysics.h"
#pragma warning(disable:4100)
namespace nvidia
{
namespace apex
{
using namespace physx;
bool copyStaticProperties(PxRigidActor& to, const PxRigidActor& from,MirrorScene::MirrorFilter &mirrorFilter)
{
shdfnd::InlineArray<PxShape*, 64> shapes;
shapes.resize(from.getNbShapes());
uint32_t shapeCount = from.getNbShapes();
from.getShapes(shapes.begin(), shapeCount);
shdfnd::InlineArray<PxMaterial*, 64> materials;
for(uint32_t i = 0; i < shapeCount; i++)
{
PxShape* s = shapes[i];
if ( mirrorFilter.shouldMirror(*s) )
{
uint32_t materialCount = s->getNbMaterials();
materials.resize(materialCount);
s->getMaterials(materials.begin(), materialCount);
PxShape* shape = to.createShape(s->getGeometry().any(), materials.begin(), static_cast<uint16_t>(materialCount));
shape->setLocalPose( s->getLocalPose());
shape->setContactOffset(s->getContactOffset());
shape->setRestOffset(s->getRestOffset());
shape->setFlags(s->getFlags());
shape->setSimulationFilterData(s->getSimulationFilterData());
shape->setQueryFilterData(s->getQueryFilterData());
mirrorFilter.reviseMirrorShape(*shape);
}
}
to.setActorFlags(from.getActorFlags());
to.setOwnerClient(from.getOwnerClient());
to.setDominanceGroup(from.getDominanceGroup());
if ( to.getNbShapes() )
{
mirrorFilter.reviseMirrorActor(to);
}
return to.getNbShapes() != 0;
}
PxRigidStatic* CloneStatic(PxPhysics& physicsSDK,
const PxTransform& transform,
const PxRigidActor& from,
MirrorScene::MirrorFilter &mirrorFilter)
{
PxRigidStatic* to = physicsSDK.createRigidStatic(transform);
if(!to)
return NULL;
if ( !copyStaticProperties(*to, from,mirrorFilter) )
{
to->release();
to = NULL;
}
return to;
}
PxRigidDynamic* CloneDynamic(PxPhysics& physicsSDK,
const PxTransform& transform,
const PxRigidDynamic& from,
MirrorScene::MirrorFilter &mirrorFilter)
{
PxRigidDynamic* to = physicsSDK.createRigidDynamic(transform);
if(!to)
return NULL;
if ( !copyStaticProperties(*to, from, mirrorFilter) )
{
to->release();
to = NULL;
return NULL;
}
to->setRigidBodyFlags(from.getRigidBodyFlags());
to->setMass(from.getMass());
to->setMassSpaceInertiaTensor(from.getMassSpaceInertiaTensor());
to->setCMassLocalPose(from.getCMassLocalPose());
if ( !(to->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC) )
{
to->setLinearVelocity(from.getLinearVelocity());
to->setAngularVelocity(from.getAngularVelocity());
}
to->setLinearDamping(from.getAngularDamping());
to->setAngularDamping(from.getAngularDamping());
to->setMaxAngularVelocity(from.getMaxAngularVelocity());
uint32_t posIters, velIters;
from.getSolverIterationCounts(posIters, velIters);
to->setSolverIterationCounts(posIters, velIters);
to->setSleepThreshold(from.getSleepThreshold());
to->setContactReportThreshold(from.getContactReportThreshold());
return to;
}
MirrorSceneImpl::MirrorSceneImpl(physx::PxScene &primaryScene,
physx::PxScene &mirrorScene,
MirrorScene::MirrorFilter &mirrorFilter,
float mirrorStaticDistance,
float mirrorDynamicDistance,
float mirrorDistanceThreshold)
: mPrimaryScene(primaryScene)
, mMirrorScene(mirrorScene)
, mMirrorFilter(mirrorFilter)
, mMirrorStaticDistance(mirrorStaticDistance)
, mMirrorDynamicDistance(mirrorDynamicDistance)
, mMirrorDistanceThreshold(mirrorDistanceThreshold*mirrorDistanceThreshold)
, mTriggerActor(NULL)
, mTriggerMaterial(NULL)
, mTriggerShapeStatic(NULL)
, mTriggerShapeDynamic(NULL)
, mSimulationEventCallback(NULL)
{
mLastCameraLocation = PxVec3(1e9,1e9,1e9);
primaryScene.getPhysics().registerDeletionListener(*this,physx::PxDeletionEventFlag::eMEMORY_RELEASE | physx::PxDeletionEventFlag::eUSER_RELEASE);
}
MirrorSceneImpl::~MirrorSceneImpl(void)
{
if ( mTriggerActor )
{
mPrimaryScene.lockWrite(__FILE__,__LINE__);
mTriggerActor->release();
mPrimaryScene.unlockWrite();
}
if ( mTriggerMaterial )
{
mTriggerMaterial->release();
}
mPrimaryScene.getPhysics().unregisterDeletionListener(*this);
}
void MirrorSceneImpl::createTriggerActor(const PxVec3 &cameraPosition)
{
PX_ASSERT( mTriggerActor == NULL );
mTriggerActor = mPrimaryScene.getPhysics().createRigidDynamic( PxTransform(cameraPosition) );
PX_ASSERT(mTriggerActor);
if ( mTriggerActor )
{
mTriggerActor->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC,true);
physx::PxSphereGeometry staticSphere;
physx::PxSphereGeometry dynamicSphere;
staticSphere.radius = mMirrorStaticDistance;
dynamicSphere.radius = mMirrorDynamicDistance;
mTriggerMaterial = mPrimaryScene.getPhysics().createMaterial(1,1,1);
PX_ASSERT(mTriggerMaterial);
if ( mTriggerMaterial )
{
mTriggerShapeStatic = mTriggerActor->createShape(staticSphere,*mTriggerMaterial);
mTriggerShapeDynamic = mTriggerActor->createShape(dynamicSphere,*mTriggerMaterial);
PX_ASSERT(mTriggerShapeStatic);
PX_ASSERT(mTriggerShapeDynamic);
if ( mTriggerShapeStatic && mTriggerShapeDynamic )
{
mPrimaryScene.lockWrite(__FILE__,__LINE__);
mTriggerActor->setOwnerClient(0);
mTriggerShapeStatic->setFlag(physx::PxShapeFlag::eSCENE_QUERY_SHAPE,false);
mTriggerShapeStatic->setFlag(physx::PxShapeFlag::eSIMULATION_SHAPE,false);
mTriggerShapeStatic->setFlag(physx::PxShapeFlag::eTRIGGER_SHAPE,true);
mTriggerShapeDynamic->setFlag(physx::PxShapeFlag::eSCENE_QUERY_SHAPE,false);
mTriggerShapeDynamic->setFlag(physx::PxShapeFlag::eSIMULATION_SHAPE,false);
mTriggerShapeDynamic->setFlag(physx::PxShapeFlag::eTRIGGER_SHAPE,true);
mSimulationEventCallback = mPrimaryScene.getSimulationEventCallback(); // get a copy of the original callback
mPrimaryScene.setSimulationEventCallback(this,0);
mPrimaryScene.addActor(*mTriggerActor);
mPrimaryScene.unlockWrite();
}
}
}
}
// Each frame, we do a shape query for static and dynamic objects
// If this is the first time the synchronize has been called, then we create
// a trigger actor with two spheres in the primary scene. This trigger
// actor is used to detect when objects move in and outside of the static and dynamic
// mirror range specified.
void MirrorSceneImpl::synchronizePrimaryScene(const PxVec3 &cameraPos)
{
PxVec3 diff = cameraPos - mLastCameraLocation;
float dist = diff.magnitudeSquared();
if ( dist > mMirrorDistanceThreshold )
{
mLastCameraLocation = cameraPos;
if ( mTriggerActor == NULL )
{
createTriggerActor(cameraPos); // Create the scene mirroring trigger actor
}
if ( mTriggerActor )
{
mPrimaryScene.lockWrite(__FILE__,__LINE__);
mTriggerActor->setKinematicTarget( PxTransform(cameraPos) ); // Update the position of the trigger actor to be the current camera location
mPrimaryScene.unlockWrite();
}
}
// Now, iterate on all of the current actors which are being mirrored
// Only the primary scene after modifies this hash, so it is safe to do this
// without any concerns of thread locking.
// The mirrored scene thread does access the contents of this hash (MirrorActor)
{
mPrimaryScene.lockRead(__FILE__,__LINE__);
for (ActorHash::Iterator i=mActors.getIterator(); !i.done(); ++i)
{
MirrorActor *ma = i->second;
ma->synchronizePose(); // check to see if the position of this object in the primary
// scene has changed. If it has, then we create a command for the mirror scene to update
// it's mirror actor to that new position.
}
mPrimaryScene.unlockRead();
}
}
// When the mirrored scene is synchronized, we grab the mirror command buffer
// And then despool all of the create/release/update commands that got posted previously by the
// primary scene thread. A mutex is used to safe brief access to the command buffer.
// A copy of the command buffer is made so that we only grab the mutex for the shorted period
// of time possible.
void MirrorSceneImpl::synchronizeMirrorScene(void)
{
MirrorCommandArray temp;
mMirrorCommandMutex.lock();
temp = mMirrorCommands;
mMirrorCommands.clear();
mMirrorCommandMutex.unlock();
if ( !temp.empty() )
{
mMirrorScene.lockWrite(__FILE__,__LINE__);
for (uint32_t i=0; i<temp.size(); i++)
{
MirrorCommand &mc = temp[i];
switch ( mc.mType )
{
case MCT_CREATE_ACTOR:
{
mc.mMirrorActor->createActor(mMirrorScene);
}
break;
case MCT_RELEASE_ACTOR:
{
delete mc.mMirrorActor;
}
break;
case MCT_UPDATE_POSE:
{
mc.mMirrorActor->updatePose(mc.mPose);
}
break;
default:
break;
}
}
mMirrorScene.unlockWrite();
}
}
void MirrorSceneImpl::release(void)
{
delete this;
}
/**
\brief This is called when a breakable constraint breaks.
\note The user should not release the constraint shader inside this call!
\param[in] constraints - The constraints which have been broken.
\param[in] count - The number of constraints
@see PxConstraint PxConstraintDesc.linearBreakForce PxConstraintDesc.angularBreakForce
*/
void MirrorSceneImpl::onConstraintBreak(PxConstraintInfo* constraints, uint32_t count)
{
if ( mSimulationEventCallback )
{
mSimulationEventCallback->onConstraintBreak(constraints,count);
}
}
/**
\brief This is called during PxScene::fetchResults with the actors which have just been woken up.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\param[in] actors - The actors which just woke up.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
void MirrorSceneImpl::onWake(PxActor** actors, uint32_t count)
{
if ( mSimulationEventCallback )
{
mSimulationEventCallback->onWake(actors,count);
}
}
/**
\brief This is called during PxScene::fetchResults with the actors which have just been put to sleep.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\param[in] actors - The actors which have just been put to sleep.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
void MirrorSceneImpl::onSleep(PxActor** actors, uint32_t count)
{
if ( mSimulationEventCallback )
{
mSimulationEventCallback->onSleep(actors,count);
}
}
/**
\brief The user needs to implement this interface class in order to be notified when
certain contact events occur.
The method will be called for a pair of actors if one of the colliding shape pairs requested contact notification.
You request which events are reported using the filter shader/callback mechanism (see #PxSimulationFilterShader,
#PxSimulationFilterCallback, #PxPairFlag).
Do not keep references to the passed objects, as they will be
invalid after this function returns.
\param[in] pairHeader Information on the two actors whose shapes triggered a contact report.
\param[in] pairs The contact pairs of two actors for which contact reports have been requested. See #PxContactPair.
\param[in] nbPairs The number of provided contact pairs.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxContactPair PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
void MirrorSceneImpl::onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, uint32_t nbPairs)
{
if ( mSimulationEventCallback )
{
mSimulationEventCallback->onContact(pairHeader,pairs,nbPairs);
}
}
/*
\brief This is called during PxScene::fetchResults with the current trigger pair events.
Shapes which have been marked as triggers using PxShapeFlag::eTRIGGER_SHAPE will send events
according to the pair flag specification in the filter shader (see #PxPairFlag, #PxSimulationFilterShader).
\param[in] pairs - The trigger pairs which caused events.
\param[in] count - The number of trigger pairs.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxPairFlag PxSimulationFilterShader PxShapeFlag PxShape.setFlag()
*/
void MirrorSceneImpl::onTrigger(PxTriggerPair* pairs, uint32_t count)
{
mTriggerPairs.clear();
for (uint32_t i=0; i<count; i++)
{
PxTriggerPair &tp = pairs[i];
if ( ( tp.triggerShape == mTriggerShapeStatic ) || ( tp.triggerShape == mTriggerShapeDynamic ) )
{
if ( tp.flags & PxTriggerPairFlag::eREMOVED_SHAPE_OTHER ) // actor was deleted!
{
// handle shape release..
mirrorShape(tp);
}
else
{
PxActor *actor = tp.otherActor;
if( mMirrorFilter.shouldMirror(*actor) ) // let the application telll us whether this is an actor we want to mirror or not
{
if ( tp.triggerShape == mTriggerShapeStatic )
{
if ( actor->getType() == PxActorType::eRIGID_STATIC )
{
mirrorShape(tp);
}
}
else if ( tp.triggerShape == mTriggerShapeDynamic )
{
if ( actor->getType() == PxActorType::eRIGID_DYNAMIC )
{
mirrorShape(tp);
}
}
}
}
}
else
{
mTriggerPairs.pushBack(tp);
}
}
if ( !mTriggerPairs.empty() ) // If some of the triggers were for the application; then we pass them on
{
mSimulationEventCallback->onTrigger(&mTriggerPairs[0],mTriggerPairs.size());
}
}
void MirrorSceneImpl::onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count)
{
PX_UNUSED(bodyBuffer);
PX_UNUSED(poseBuffer);
PX_UNUSED(count);
}
void MirrorSceneImpl::mirrorShape(const PxTriggerPair &tp)
{
size_t hash = (size_t)tp.otherShape;
const ShapeHash::Entry *found = mShapes.find(hash);
MirrorActor *ma = found ? found->second : NULL;
if ( tp.flags & PxTriggerPairFlag::eREMOVED_SHAPE_OTHER )
{
if ( found )
{
bool kill = ma->removeShape();
mShapes.erase(hash);
if ( kill )
{
ma->release();
mActors.erase( ma->mActorHash );
}
}
}
else if ( tp.status == PxPairFlag::eNOTIFY_TOUCH_FOUND )
{
PX_ASSERT( found == NULL );
size_t actorHash = (size_t) &tp.otherActor;
const ActorHash::Entry *foundActor = mActors.find(actorHash);
if ( foundActor == NULL )
{
ma = PX_NEW(MirrorActor)(actorHash,*tp.otherActor,*this);
mActors[actorHash] = ma;
}
else
{
ma = foundActor->second;
}
ma->addShape();
mShapes[hash] = ma;
}
else if ( tp.status == PxPairFlag::eNOTIFY_TOUCH_LOST )
{
PX_ASSERT( found );
if ( ma )
{
bool kill = ma->removeShape();
mShapes.erase(hash);
if ( kill )
{
mActors.erase( ma->mActorHash );
ma->release();
}
}
}
}
void MirrorSceneImpl::postCommand(const MirrorCommand &mc)
{
mMirrorCommandMutex.lock();
mMirrorCommands.pushBack(mc);
mMirrorCommandMutex.unlock();
}
MirrorActor::MirrorActor(size_t actorHash,
physx::PxRigidActor &actor,
MirrorSceneImpl &mirrorScene) : mMirrorScene(mirrorScene), mPrimaryActor(&actor), mActorHash(actorHash)
{
mReleasePosted = false;
mMirrorActor = NULL;
mShapeCount = 0;
PxScene *scene = actor.getScene();
PX_ASSERT(scene);
if ( scene )
{
scene->lockWrite(__FILE__,__LINE__);
mPrimaryGlobalPose = actor.getGlobalPose();
PxPhysics *sdk = &scene->getPhysics();
if ( actor.getType() == physx::PxActorType::eRIGID_STATIC )
{
mMirrorActor = CloneStatic(*sdk,actor.getGlobalPose(),actor, mirrorScene.getMirrorFilter());
}
else
{
physx::PxRigidDynamic *rd = static_cast< physx::PxRigidDynamic *>(&actor);
mMirrorActor = CloneDynamic(*sdk,actor.getGlobalPose(),*rd, mirrorScene.getMirrorFilter());
if ( mMirrorActor )
{
rd = static_cast< physx::PxRigidDynamic *>(mMirrorActor);
rd->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC,true);
}
}
scene->unlockWrite();
if ( mMirrorActor )
{
MirrorCommand mc(MCT_CREATE_ACTOR,this);
mMirrorScene.postCommand(mc);
}
}
}
MirrorActor::~MirrorActor(void)
{
if ( mMirrorActor )
{
mMirrorActor->release();
}
}
void MirrorActor::release(void)
{
PX_ASSERT( mReleasePosted == false );
if ( !mReleasePosted )
{
if ( mPrimaryActor )
{
}
MirrorCommand mc(MCT_RELEASE_ACTOR,this);
mMirrorScene.postCommand(mc);
mReleasePosted = true;
}
}
void MirrorActor::createActor(PxScene &scene)
{
if ( mMirrorActor )
{
scene.addActor(*mMirrorActor);
}
}
static bool sameTransform(const PxTransform &a,const PxTransform &b)
{
if ( a.p == b.p &&
a.q.x == b.q.x &&
a.q.y == b.q.y &&
a.q.z == b.q.z &&
a.q.w == b.q.w )
{
return true;
}
return false;
}
void MirrorActor::synchronizePose(void)
{
if ( mPrimaryActor )
{
PxTransform p = mPrimaryActor->getGlobalPose();
if ( !sameTransform(p,mPrimaryGlobalPose) )
{
mPrimaryGlobalPose = p;
MirrorCommand mc(MCT_UPDATE_POSE,this,p);
mMirrorScene.postCommand(mc);
}
}
}
void MirrorActor::updatePose(const PxTransform &pose)
{
if ( mMirrorActor )
{
if ( mMirrorActor->getType() == PxActorType::eRIGID_STATIC )
{
PxRigidStatic *p = static_cast< PxRigidStatic *>(mMirrorActor);
p->setGlobalPose(pose);
}
else
{
PxRigidDynamic *p = static_cast< PxRigidDynamic *>(mMirrorActor);
p->setKinematicTarget(pose);
}
}
}
void MirrorSceneImpl::onRelease(const PxBase* observed,
void* /*userData*/,
PxDeletionEventFlag::Enum /*deletionEvent*/)
{
const physx::PxRigidActor *a = observed->is<PxRigidActor>();
if ( a )
{
size_t actorHash = (size_t)a;
const ActorHash::Entry *foundActor = mActors.find(actorHash);
if ( foundActor != NULL )
{
MirrorActor *ma = foundActor->second;
ma->mPrimaryActor = NULL;
}
}
}
}; // end apex namespace
}; // end physx namespace
#endif
| 29.2009 | 154 | 0.735637 | [
"object",
"shape",
"transform"
] |
f59097d5064d9f86af38c687c9840772fb144b74 | 137 | cc | C++ | k/null_object.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 18 | 2016-04-09T09:05:43.000Z | 2021-03-31T20:52:44.000Z | k/null_object.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 1 | 2017-05-16T08:17:25.000Z | 2017-05-16T08:17:25.000Z | k/null_object.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 1 | 2021-11-23T15:17:15.000Z | 2021-11-23T15:17:15.000Z | #include "k/null_object.h"
#include "k/sender.h"
namespace k {
NullObject::NullObject(Generation g) : Object{g} {}
} // namespace k
| 13.7 | 51 | 0.678832 | [
"object"
] |
f590aff2f86a400290bcbfb2ca12d7bf0bc97f8b | 8,064 | cpp | C++ | OSS13 Server/Sources/World/Tile.cpp | Insineer/OSS-13 | 6ddceea4fdd4b869ad438190237bbbc2610ba4bc | [
"MIT"
] | null | null | null | OSS13 Server/Sources/World/Tile.cpp | Insineer/OSS-13 | 6ddceea4fdd4b869ad438190237bbbc2610ba4bc | [
"MIT"
] | null | null | null | OSS13 Server/Sources/World/Tile.cpp | Insineer/OSS-13 | 6ddceea4fdd4b869ad438190237bbbc2610ba4bc | [
"MIT"
] | null | null | null | #include "Tile.hpp"
#include <plog/Log.h>
#include <IServer.h>
#include <Resources/ResourceManager.hpp>
#include <World/World.hpp>
#include <World/Map.hpp>
#include <World/Objects.hpp>
#include <World/Atmos/Atmos.hpp>
#include <Shared/Network/Protocol/ServerToClient/WorldInfo.h>
Tile::Tile(Map *map, apos pos) :
map(map), pos(pos),
hasFloor(false), fullBlocked(false), directionsBlocked(4, false),
locale(nullptr), needToUpdateLocale(false), gases(int(Gas::Count), 0)
{
uint ux = uint(pos.x);
uint uy = uint(pos.y);
icon = IServer::RM()->GetIconInfo("space");
icon.id += ((ux + uy) ^ ~(ux * uy)) % 25;
totalPressure = 0;
}
void Tile::Update(std::chrono::microseconds timeElapsed) {
// Update locale, if wall/floor state was changed
if (needToUpdateLocale) {
// Atmos-available tile
if (hasFloor && !fullBlocked) {
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++) {
Tile *neighbour = map->GetTile(pos + rpos(dx, dy, 0));
if (!neighbour ||
dx == 0 && dy == 0 ||
dx * dy != 0) // diag tiles
continue;
if (neighbour->locale) {
if (locale) {
locale->Merge(neighbour->locale);
} else {
neighbour->locale->AddTile(this);
locale = neighbour->locale;
}
}
}
if (!locale) {
map->GetAtmos()->CreateLocale(this);
}
} else { // Space
if (!hasFloor && !fullBlocked) {
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++) {
Tile *neighbour = map->GetTile(pos + rpos(dx, dy, 0));
if (!neighbour ||
dx == 0 && dy == 0 ||
dx * dy != 0) // diag tiles
continue;
if (neighbour->locale) {
neighbour->locale->Open();
}
}
if (locale) locale->RemoveTile(this);
} else { // fullBlocked
// if here was locale then remove it
if (locale) {
map->GetAtmos()->RemoveLocale(locale);
}
// if here was a space then we need to update neighbors locals
// so we delete them, after that Atmos::Update recreate them
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++) {
Tile *neighbour = map->GetTile(pos + rpos(dx, dy, 0));
if (!neighbour ||
dx == 0 && dy == 0 ||
dx * dy != 0) // diag tiles
continue;
if (neighbour->locale) {
neighbour->locale->CheckCloseness();
}
}
}
}
needToUpdateLocale = false;
}
}
void Tile::CheckLocale() {
needToUpdateLocale = true;
}
bool Tile::RemoveObject(Object *obj) {
if (removeObject(obj)) {
auto diff = std::make_shared<network::protocol::RemoveDiff>();
diff->objId = obj->ID();
AddDiff(diff, obj);
return true;
}
return false;
}
bool Tile::MoveTo(Object *obj) {
if (!obj) return false;
if (!obj->IsMovable()) {
LOGW << "Warning! Try to move immovable object";
return false;
}
if (obj->GetDensity())
for (auto &object : content)
if (object)
if (object->GetDensity()) {
return false;
}
Tile *lastTile = obj->GetTile();
rpos delta = GetPos() - lastTile->GetPos();
if (abs(delta.x) > 1 || abs(delta.y) > 1)
LOGW << "Warning! Moving more than a one tile. (Tile::MoveTo)";
if (delta.z)
LOGW << "Warning! Moving between Z-levels. (Tile::MoveTo)";
const uf::Direction direction = uf::VectToDirection(delta);
auto relocateAwayDiff = std::make_shared<network::protocol::RelocateAwayDiff>(); // TODO: MoveAway???
relocateAwayDiff->objId = obj->ID();
relocateAwayDiff->newCoords = pos;
lastTile->AddDiff(std::move(relocateAwayDiff), obj);
addObject(obj);
auto moveDiff = std::make_shared<network::protocol::MoveDiff>();
moveDiff->objId = obj->ID();
moveDiff->direction = direction;
moveDiff->speed = obj->GetMoveSpeed();
AddDiff(moveDiff, obj);
return true;
}
void Tile::PlaceTo(Object *obj) {
if (!obj)
return;
Tile *lastTile = obj->GetTile();
// If obj is wall or floor - remove previous and change status
if (obj->IsFloor()) {
if (hasFloor) {
for (auto iter = content.begin(); iter != content.end(); iter++) {
if ((*iter)->IsFloor()) {
content.erase(iter);
break;
}
}
}
hasFloor = true;
CheckLocale();
} else if (obj->IsWall()) {
if (!hasFloor) {
LOGW << "Warning! Try to place wall without floor";
return;
}
if (fullBlocked) {
for (auto iter = content.begin(); iter != content.end(); iter++) {
if ((*iter)->IsWall()) {
content.erase(iter);
break;
}
}
}
fullBlocked = true;
CheckLocale();
}
auto objInfo = obj->GetObjectInfo();
if (lastTile) {
auto relocateAwayDiff = std::make_shared<network::protocol::RelocateAwayDiff>();
relocateAwayDiff->objId = obj->ID();
relocateAwayDiff->newCoords = pos;
lastTile->AddDiff(relocateAwayDiff, obj);
}
addObject(obj);
auto relocateDiff = std::make_shared<network::protocol::RelocateDiff>();
relocateDiff->objId = obj->ID();
relocateDiff->newCoords = pos;
AddDiff(relocateDiff, obj);
}
const std::list<Object *> &Tile::Content() const {
return content;
}
Object *Tile::GetDenseObject() const
{
for (auto &obj : content)
if (obj->GetDensity()) return obj;
return nullptr;
}
uf::vec3i Tile::GetPos() const {
return pos;
}
Map *Tile::GetMap() const { return map; }
bool Tile::IsDense() const {
for (auto &obj : content)
if (obj->GetDensity()) return true;
return false;
}
bool Tile::IsDense(const std::initializer_list<uf::Direction> &directions) const {
for (auto &obj : content)
if (obj->GetSolidity().IsExistsOne(directions)) return true;
return false;
}
bool Tile::IsSpace() const {
return !hasFloor && !fullBlocked;
}
Locale *Tile::GetLocale() const {
return locale;
}
network::protocol::TileInfo Tile::GetTileInfo(uint viewerId, uint visibility) const {
network::protocol::TileInfo tileInfo;
tileInfo.coords = pos;
tileInfo.sprite = icon.id;
for (auto &obj : this->content) {
if (obj->CheckVisibility(viewerId, visibility))
tileInfo.content.push_back(obj->GetObjectInfo());
}
return tileInfo;
}
void Tile::addObject(Object *obj) {
if (!obj)
return;
Object *holder = obj->GetHolder();
if (holder) {
EXPECT(holder->RemoveObject(obj));
}
Tile *lastTile = obj->GetTile();
if (lastTile) {
EXPECT(lastTile->removeObject(obj));
}
// Count position in tile content by layer
auto iter = content.begin();
while (iter != content.end() && (*iter)->GetLayer() <= obj->GetLayer())
iter++;
content.insert(iter, obj);
obj->setTile(this);
obj->SetSpriteState(Global::ItemSpriteState::DEFAULT);
}
bool Tile::removeObject(Object *obj) {
if (!obj)
return false;
for (auto iter = content.begin(); iter != content.end(); iter++) {
if (*iter == obj) {
if (obj->IsFloor()) {
hasFloor = false;
CheckLocale();
} else if (obj->IsWall()) {
fullBlocked = false;
CheckLocale();
}
obj->setTile(nullptr);
content.erase(iter);
return true;
}
}
return false;
}
void Tile::AddDiff(std::shared_ptr<network::protocol::Diff> diff, Object *obj) {
EXPECT(uf::CreateSerializableById(diff->Id())); // debug
differencesWithObject.push_back({diff, obj->GetOwnershipPointer()});
}
void Tile::ClearDiffs() {
differencesWithObject.clear();
}
| 27.151515 | 102 | 0.556548 | [
"object"
] |
f59586b4cd71f4a296291e7d35979acd0eed0d43 | 2,846 | cpp | C++ | 3rd-parties/jaeger-client-cpp-0.7.0/src/jaegertracing/utils/UDPSenderTest.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 193 | 2021-03-27T00:46:13.000Z | 2022-03-29T07:25:00.000Z | 3rd-parties/jaeger-client-cpp-0.7.0/src/jaegertracing/utils/UDPSenderTest.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 220 | 2018-04-05T15:25:20.000Z | 2022-01-21T02:38:57.000Z | 3rd-parties/jaeger-client-cpp-0.7.0/src/jaegertracing/utils/UDPSenderTest.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 122 | 2018-04-08T01:07:20.000Z | 2022-03-03T21:14:02.000Z | /*
* Copyright (c) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jaegertracing/net/IPAddress.h"
#include "jaegertracing/net/Socket.h"
#include "jaegertracing/thrift-gen/jaeger_types.h"
#include "jaegertracing/thrift-gen/zipkincore_types.h"
#include "jaegertracing/utils/UDPTransporter.h"
#include <future>
#include <gtest/gtest.h>
#include <stdexcept>
#include <thread>
#include <vector>
namespace jaegertracing {
namespace utils {
TEST(UDPSender, testZipkinMessage)
{
net::IPAddress serverAddr;
std::promise<void> started;
std::thread serverThread([&serverAddr, &started]() {
net::Socket socket;
socket.open(AF_INET, SOCK_DGRAM);
socket.bind(net::IPAddress::v4("127.0.0.1", 0));
::sockaddr_storage addrStorage;
::socklen_t addrLen = sizeof(addrStorage);
const auto returnCode =
::getsockname(socket.handle(),
reinterpret_cast<::sockaddr*>(&addrStorage),
&addrLen);
ASSERT_EQ(0, returnCode);
serverAddr = net::IPAddress(addrStorage, addrLen);
started.set_value();
});
started.get_future().wait();
UDPTransporter udpClient(serverAddr, 0);
using ZipkinBatch = std::vector<twitter::zipkin::thrift::Span>;
ASSERT_THROW(udpClient.emitZipkinBatch(ZipkinBatch()), std::logic_error);
serverThread.join();
}
TEST(UDPSender, testBigMessage)
{
net::IPAddress serverAddr;
std::promise<void> started;
std::thread serverThread([&serverAddr, &started]() {
net::Socket socket;
socket.open(AF_INET, SOCK_DGRAM);
socket.bind(net::IPAddress::v4("127.0.0.1", 0));
::sockaddr_storage addrStorage;
::socklen_t addrLen = sizeof(addrStorage);
const auto returnCode =
::getsockname(socket.handle(),
reinterpret_cast<::sockaddr*>(&addrStorage),
&addrLen);
ASSERT_EQ(0, returnCode);
serverAddr = net::IPAddress(addrStorage, addrLen);
started.set_value();
});
started.get_future().wait();
UDPTransporter udpClient(serverAddr, 1);
ASSERT_THROW(udpClient.emitBatch(thrift::Batch()), std::logic_error);
serverThread.join();
}
} // namespace utils
} // namespace jaegertracing
| 33.880952 | 77 | 0.666198 | [
"vector"
] |
f59598c920c09ddebc957ed98433c74395957489 | 11,790 | cpp | C++ | experiments/plane_engaging/plane_engaging.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | 16 | 2020-04-15T04:45:02.000Z | 2022-01-13T03:28:46.000Z | experiments/plane_engaging/plane_engaging.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | null | null | null | experiments/plane_engaging/plane_engaging.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | null | null | null | #include "plane_engaging.h"
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
#include <Eigen/SVD>
#include <solvehfvc.h>
#include <RobotUtilities/utilities.h>
#include <RobotUtilities/TimerLinux.h>
using namespace RUT;
PlaneEngaging::PlaneEngaging(ForceControlHardware *robot,
ForceControlController *controller) {
robot_ = robot;
controller_ = controller;
}
PlaneEngaging::~PlaneEngaging() {
}
bool PlaneEngaging::initialize(const std::string& file_name,
const int main_loop_rate, ros::NodeHandle& root_nh) {
main_loop_rate_ = main_loop_rate;
folder_path_ = file_name;
// parameters in file
// G, b_G
ifstream fp;
fp.open(file_name + "plane_engaging/para.txt");
if (!fp) {
cerr << "Unable to open parameter file.";
return false;
}
int nRowG, nColG;
fp >> nRowG >> nColG;
G_.resize(nRowG, nColG);
b_G_.resize(nRowG);
for (int i = 0; i < nRowG; ++i)
for (int j = 0; j < nColG; ++j)
fp >> G_(i,j);
for (int i = 0; i < nRowG; ++i) fp >> b_G_(i);
fp.close();
// double check
cout << "G_: " << G_.format(MatlabFmt) << endl;
cout << "b_G_: " << b_G_.format(MatlabFmt) << endl;
// parameters in ROS server
std::vector<double> scale_force_vector;
root_nh.getParam("/constraint_estimation/scale_force_vector", scale_force_vector);
if (!root_nh.hasParam("/constraint_estimation/scale_force_vector"))
ROS_WARN_STREAM("Parameter [/constraint_estimation/scale_force_vector] not found!");
force_scale_matrix_inv_ = Matrix6d::Zero();
for (int i = 0; i < 6; ++i) force_scale_matrix_inv_(i,i) = 1.0/scale_force_vector[i];
root_nh.param(string("/constraint_estimation/v_singular_value_threshold"),
v_singular_value_threshold_, 0.1);
root_nh.param(string("/constraint_estimation/f_singular_value_threshold"),
f_singular_value_threshold_, 0.1);
if (!root_nh.hasParam("/constraint_estimation/v_singular_value_threshold"))
ROS_WARN_STREAM("Parameter "
"[/constraint_estimation/v_singular_value_threshold] not found, "
" using default: " << v_singular_value_threshold_);
if (!root_nh.hasParam("/constraint_estimation/f_singular_value_threshold"))
ROS_WARN_STREAM("Parameter "
"[/constraint_estimation/f_singular_value_threshold] not found, "
"using default: " << f_singular_value_threshold_);
root_nh.param(string("/plane_engaging/Number_of_frames"),
N_TRJ_, 1);
if (!root_nh.hasParam("/plane_engaging/Number_of_frames"))
ROS_WARN_STREAM("Parameter "
"[/plane_engaging/Number_of_frames] not found, "
" using default: " << N_TRJ_);
return true;
}
bool PlaneEngaging::run() {
MatrixXd f_data, v_data;
controller_->reset();
if (controller_->_f_queue.size() < 50) {
cout << "Run update() for " << main_loop_rate_ << " frames:" << endl;
// first, run update for 1s to populate the data deques
ros::Rate pub_rate(main_loop_rate_);
ros::Duration period(EGM_PERIOD);
for (int i = 0; i < main_loop_rate_; ++i) {
ros::Time time_now = ros::Time::now();
bool b_is_safe = controller_->update(time_now, period);
if(!b_is_safe) break;
pub_rate.sleep();
}
cout << "Done." << endl;
}
Timer timer;
std::srand(std::time(0));
for (int fr = 0; fr < N_TRJ_; ++fr) {
timer.tic();
/* Estimate Natural Constraints from pool of data */
// get the weighted data
// debug
f_data = MatrixXd::Zero(6, controller_->_f_queue.size());
v_data = MatrixXd::Zero(6, controller_->_v_queue.size());
for (int i = 0; i < controller_->_f_queue.size(); ++i)
f_data.col(i) = controller_->_f_queue[i] * controller_->_f_weights[i];
for (int i = 0; i < controller_->_v_queue.size(); ++i)
v_data.col(i) = controller_->_v_queue[i] * controller_->_v_weights[i];
// SVD on velocity data
Eigen::JacobiSVD<MatrixXd> svd_v(v_data.transpose(), Eigen::ComputeThinV);
VectorXd sigma_v = svd_v.singularValues();
int DimV = 0;
for (int i = 0; i < 6; ++i)
if (sigma_v(i) > v_singular_value_threshold_) DimV ++;
// get a basis for row space of velocity data
MatrixXd rowspace_v = svd_v.matrixV().leftCols(DimV);
// filter out force data that:
// 1. has a small weight
std::vector<int> f_id;
for (int i = 0; i < f_data.cols(); ++i) {
double length = f_data.col(i).norm();
if (length > 1.5) { // weighted length in newton
f_id.push_back(i);
}
}
int f_data_length = f_id.size();
MatrixXd f_data_filtered = MatrixXd::Zero(6, f_data_length);
for (int i = 0; i < f_data_length; ++i)
f_data_filtered.col(i) = f_data.col(f_id[i]);
int DimF = 0;
MatrixXd Nf;
MatrixXd f_data_selected;
if (f_data_length > 5) {
// SVD to filtered force data
Eigen::JacobiSVD<MatrixXd> svd_f(f_data_filtered.transpose(), Eigen::ComputeThinV);
VectorXd sigma_f = svd_f.singularValues();
// check dimensions, estimate natural constraints
double threshold = max(f_singular_value_threshold_, 0.1*sigma_f(0));
for (int i = 0; i < 6; ++i)
if (sigma_f(i) > threshold) DimF ++;
if (DimF > 3) {
cout << "DimF: " << DimF << endl;
cout << "Press Enter to continue" << endl;
getchar();
}
// MatrixXd N = SVD_V_f.block<6, DimF>(0, 0).transpose();
// Sample DimF force directions
MatrixXd f_data_normalized = f_data_filtered;
for (int i = 0; i < f_data_length; ++i)
f_data_normalized.col(i).normalize();
int kNFSamples = (int)pow(double(f_data_length), 0.7);
f_data_selected = MatrixXd(6, DimF);
if (DimF == 1) {
f_data_selected = f_data_filtered.rowwise().mean();
f_data_selected.normalize();
} else {
MatrixXd f_data_selected_new(6, DimF);
double f_distance = 0;
assert(f_data_length < 32767);
for (int i = 0; i < kNFSamples; ++i) {
// 1. sample
for (int s = 0; s < DimF; s++) {
int r = (rand() % f_data_length);
f_data_selected_new.col(s) = f_data_normalized.col(r);
}
// 2. compute distance
double f_distance_new = 0;
for (int ii = 0; ii < DimF-1; ++ii)
for (int jj = ii+1; jj < DimF; ++jj)
f_distance_new += (f_data_selected_new.col(ii) -
f_data_selected_new.col(jj)).norm();
// 3. Update data
if (f_distance_new > f_distance) {
f_data_selected = f_data_selected_new;
f_distance = f_distance_new;
}
} // end sampling
}
// unscale
Nf = f_data_selected.transpose() * force_scale_matrix_inv_;
} else {
DimF = 0;
Nf = MatrixXd(0, 6);
f_data_selected = MatrixXd(6, 0);
}
/* Do Hybrid Servoing */
HFVC action;
int kDimActualized = 6;
int kDimUnActualized = 0;
int kDimSlidingFriction = 0;
int kNumSeeds = 3;
int kDimLambda = DimF;
int kPrintLevel = 1;
VectorXd F = VectorXd::Zero(6);
MatrixXd Aeq(0, DimF+6); // dummy
VectorXd beq(0); // dummy
MatrixXd A = MatrixXd::Zero(DimF, DimF + 6);
VectorXd b_A = VectorXd::Zero(DimF);
A.leftCols(DimF) = -MatrixXd::Identity(DimF,DimF);
double kLambdaMin = 10.0;
for (int i = 0; i < DimF; ++i) b_A(i) = -kLambdaMin;
solvehfvc(Nf, G_, b_G_, F, Aeq, beq, A, b_A,
kDimActualized, kDimUnActualized,
kDimSlidingFriction, kDimLambda,
kNumSeeds, kPrintLevel,
&action);
double computation_time_ms = timer.toc();
/* Execute the hybrid action */
Vector6d v_Tr = Vector6d::Zero();
for (int i = 0; i < action.n_av; ++i) v_Tr(i+action.n_af) = action.w_av(i);
double pose_fb[7];
robot_->getPose(pose_fb);
Matrix4d SE3_WT_fb = posemm2SE3(pose_fb);
Matrix6d Adj_WT = SE32Adj(SE3_WT_fb);
Matrix6d R_a = action.R_a;
Matrix6d R_a_inv = R_a.inverse();
Vector6d v_T = R_a_inv*v_Tr;
const double dt = 0.1; // s
const double kVMax = 0.002; // m/s, maximum speed limit
const double scale_rot_to_tran = 0.5; // 1m = 2rad
Vector6d v_T_scaled = v_T;
v_T_scaled.tail(3) *= scale_rot_to_tran;
if (v_T_scaled.norm() > kVMax) {
double scale_safe = kVMax/v_T_scaled.norm();
v_T *= scale_safe;
}
Vector6d v_W = Adj_WT*v_T;
Matrix4d SE3_WT_command;
SE3_WT_command = SE3_WT_fb + wedge6(v_W)*SE3_WT_fb*dt;
double pose_set[7];
SE32Posemm(SE3_WT_command, pose_set);
Vector6d force_Tr_set = Vector6d::Zero();
for (int i = 0; i < action.n_af; ++i) force_Tr_set[i] = action.eta_af(i);
Vector6d force_T = R_a_inv*force_Tr_set;
Matrix6d Adj_TW = SE32Adj(SE3Inv(SE3_WT_fb));
Vector6d force_W = Adj_TW.transpose() * force_T;
printf("V in world: %.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", v_W[0], v_W[1],
v_W[2],v_W[3],v_W[4],v_W[5]);
printf("F in world: %.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", force_W[0],
force_W[1], force_W[2],force_W[3],force_W[4],force_W[5]);
cout << "Computation Time: " << computation_time_ms << endl << endl;
if (fr == N_TRJ_-1) {
// print to file
ofstream fp;
// f_queue
fp.open(folder_path_ + "plane_engaging/f_queue.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
for (int i = 0; i < controller_->_f_queue.size(); ++i) {
stream_array_in(fp, controller_->_f_queue[i].data(), 6);
fp << endl;
}
fp.close();
// v_queue
fp.open(folder_path_ + "plane_engaging/v_queue.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
for (int i = 0; i < controller_->_v_queue.size(); ++i) {
stream_array_in(fp, controller_->_v_queue[i].data(), 6);
fp << endl;
}
fp.close();
// f_weights
fp.open(folder_path_ + "plane_engaging/f_weights.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
for (int i = 0; i < controller_->_f_weights.size(); ++i)
fp << controller_->_f_weights[i] << endl;
fp.close();
// v_weights
fp.open(folder_path_ + "plane_engaging/v_weights.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
for (int i = 0; i < controller_->_v_weights.size(); ++i)
fp << controller_->_v_weights[i] << endl;
fp.close();
// f_data_filtered
fp.open(folder_path_ + "plane_engaging/f_data_filtered.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
fp << f_data_filtered.transpose() << endl;
fp.close();
// f_data_selected
fp.open(folder_path_ + "plane_engaging/f_data_selected.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
fp << f_data_selected.transpose() << endl;
fp.close();
// others
fp.open(folder_path_ + "plane_engaging/process.txt");
if (!fp) {
cerr << "Unable to open file to write.";
return false;
}
fp << DimV << endl << DimF << endl;
stream_array_in(fp, v_T.data(), 6);
fp << endl;
stream_array_in(fp, force_T.data(), 6);
fp.close();
}
if (std::isnan(force_Tr_set[0])) {
cout << "================== NaN =====================" << endl;
cout << "Press Enter to continue.." << endl;
getchar();
}
cout << "motion begins:" << endl;
controller_->ExecuteHFVC(action.n_af, action.n_av,
action.R_a, pose_set, force_Tr_set.data(),
HS_CONTINUOUS, main_loop_rate_);
} // end for
}
| 33.305085 | 89 | 0.60475 | [
"vector"
] |
f5972b83d9089f52992b2687bcb2804ab927faa9 | 1,108 | hpp | C++ | third_party/boost/simd/function/is_nlez.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/function/is_nlez.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/is_nlez.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_IS_NLEZ_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_IS_NLEZ_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-predicates
This function object returns @ref True if x is not less or equal to @ref Zero else returns @ref False.
@par Header <boost/simd/function/is_nlez.hpp>
@par Note
Using `is_nlez(x)` is similar to: `!(x <= 0)`
@par Example:
@snippet is_nlez.cpp is_nlez
@par Possible output:
@snippet is_nlez.txt is_nlez
**/
as_logical_t<Value> is_nlez(Value const& x);
} }
#endif
#include <boost/simd/function/scalar/is_nlez.hpp>
#include <boost/simd/function/simd/is_nlez.hpp>
#endif
| 23.574468 | 106 | 0.583032 | [
"object"
] |
60d275a8ac534ede0df045597c0387e4b220a824 | 2,861 | cpp | C++ | cognitics/src/scenegraph/TransformVisitor.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/src/scenegraph/TransformVisitor.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/src/scenegraph/TransformVisitor.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2019 Cognitics, Inc.
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 "scenegraph/TransformVisitor.h"
#include "scenegraph/LOD.h"
namespace scenegraph
{
TransformVisitor::~TransformVisitor(void)
{
}
TransformVisitor::TransformVisitor(sfa::Matrix _transform) : mat(_transform)
{
}
void TransformVisitor::visiting(Scene *scene)
{
for(size_t i = 0, c = scene->faces.size(); i < c; ++i)
{
Face &face = scene->faces.at(i);
// update face coordinates based on transform
int numVerts = face.getNumVertices();
for(int i=0;i<numVerts;i++)
{
sfa::Point pt = face.getVertN(i);
pt = mat * pt;
face.setVertN(i,pt);
sfa::Point n = face.getNormalN(i);
n = mat * n;
face.setNormalN(i,n);
}
}
for(size_t i = 0, c = scene->externalReferences.size(); i < c; ++i)
{
ExternalReference &externalReference = scene->externalReferences.at(i);
// consolidate transform
sfa::Matrix m;
m.PushRotate(externalReference.attitude);
m.PushScale(externalReference.scale);
m.PushTranslate(externalReference.position);
sfa::Matrix extMatrix = mat * m;
externalReference.attitude = extMatrix.getRotation();
externalReference.position = extMatrix.getTranslation();
externalReference.scale = extMatrix.getScale();
}
traverse(scene);
}
Scene *TransformVisitor::transform(Scene *scene)
{
visit(scene);
return scene;
}
} | 36.679487 | 83 | 0.613422 | [
"transform"
] |
60d76d852f0b146f09c20caa6073a0ba3507bf67 | 1,931 | hpp | C++ | ExternalLibraries/NvGameworksFramework/externals/include/Cg/floatToIntBits.hpp | centauroWaRRIor/VulkanSamples | 5a7c58de820207cc0931a9db8c90f00453e31631 | [
"MIT"
] | 32 | 2016-12-13T05:49:12.000Z | 2022-02-04T06:15:47.000Z | ExternalLibraries/NvGameworksFramework/externals/include/Cg/floatToIntBits.hpp | centauroWaRRIor/VulkanSamples | 5a7c58de820207cc0931a9db8c90f00453e31631 | [
"MIT"
] | 2 | 2019-07-30T02:01:16.000Z | 2020-03-12T15:06:51.000Z | ExternalLibraries/NvGameworksFramework/externals/include/Cg/floatToIntBits.hpp | centauroWaRRIor/VulkanSamples | 5a7c58de820207cc0931a9db8c90f00453e31631 | [
"MIT"
] | 18 | 2017-11-16T13:37:06.000Z | 2022-03-11T08:13:46.000Z | /*
* Copyright 2007 by NVIDIA Corporation. All rights reserved. All
* information contained herein is proprietary and confidential to NVIDIA
* Corporation. Any use, reproduction, or disclosure without the written
* permission of NVIDIA Corporation is prohibited.
*/
#ifndef __Cg_floatToIntBits_hpp__
#define __Cg_floatToIntBits_hpp__
#ifdef __Cg_stdlib_hpp__
#pragma message("error: include this header file (" __FILE__ ") before <Cg/stdlib.hpp>")
#endif
#include <Cg/vector.hpp>
namespace Cg {
template <typename T, int N>
static inline __CGvector<int,N> floatToIntBits(const __CGvector<T,N> & iv)
{
__CGvector<float,N> v = __CGvector<float,N>(iv);
__CGvector<int,N> rv;
for (int i=0; i<N; i++) {
// By IEEE 754 rule, NaN is not equal to NaN
if (v[i] != v[i]) {
rv[i] = 0x7fc00000; // Canonical NaN value.
} else {
union { float f; int i; } combo;
combo.f = v[i];
rv[i] = combo.i;
}
}
return rv;
}
template <typename T, int N, typename Tstore>
static inline __CGvector<int,N> floatToIntBits(const __CGvector_usage<T,N,Tstore> & iv)
{
__CGvector<float,N> v = __CGvector<float,N>(iv);
__CGvector<int,N> rv;
for (int i=0; i<N; i++) {
// By IEEE 754 rule, NaN is not equal to NaN
if (v[i] != v[i]) {
rv[i] = 0x7fc00000; // Canonical NaN value.
} else {
union { float f; int i; } combo;
combo.f = v[i];
rv[i] = combo.i;
}
}
return rv;
}
static inline __CGvector<int,1> floatToIntBits(const float & v)
{
// By IEEE 754 rule, NaN is not equal to NaN
if (v != v) {
return 0x7fc00000; // Canonical NaN value.
} else {
union { float f; int i; } combo;
combo.f = v;
__CGvector<int,1> rv(combo.i);
return rv;
}
}
} // namespace Cg
#endif // __Cg_floatToIntBits_hpp__
| 27.985507 | 88 | 0.599689 | [
"vector"
] |
60ddddb35f5dee9b8a33eda1e65ec1c7ecee5efb | 7,697 | cpp | C++ | vpc/src/v20170312/model/ServiceTemplate.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | vpc/src/v20170312/model/ServiceTemplate.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | vpc/src/v20170312/model/ServiceTemplate.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/vpc/v20170312/model/ServiceTemplate.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Vpc::V20170312::Model;
using namespace std;
ServiceTemplate::ServiceTemplate() :
m_serviceTemplateIdHasBeenSet(false),
m_serviceTemplateNameHasBeenSet(false),
m_serviceSetHasBeenSet(false),
m_createdTimeHasBeenSet(false),
m_serviceExtraSetHasBeenSet(false)
{
}
CoreInternalOutcome ServiceTemplate::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ServiceTemplateId") && !value["ServiceTemplateId"].IsNull())
{
if (!value["ServiceTemplateId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServiceTemplate.ServiceTemplateId` IsString=false incorrectly").SetRequestId(requestId));
}
m_serviceTemplateId = string(value["ServiceTemplateId"].GetString());
m_serviceTemplateIdHasBeenSet = true;
}
if (value.HasMember("ServiceTemplateName") && !value["ServiceTemplateName"].IsNull())
{
if (!value["ServiceTemplateName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServiceTemplate.ServiceTemplateName` IsString=false incorrectly").SetRequestId(requestId));
}
m_serviceTemplateName = string(value["ServiceTemplateName"].GetString());
m_serviceTemplateNameHasBeenSet = true;
}
if (value.HasMember("ServiceSet") && !value["ServiceSet"].IsNull())
{
if (!value["ServiceSet"].IsArray())
return CoreInternalOutcome(Core::Error("response `ServiceTemplate.ServiceSet` is not array type"));
const rapidjson::Value &tmpValue = value["ServiceSet"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_serviceSet.push_back((*itr).GetString());
}
m_serviceSetHasBeenSet = true;
}
if (value.HasMember("CreatedTime") && !value["CreatedTime"].IsNull())
{
if (!value["CreatedTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServiceTemplate.CreatedTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_createdTime = string(value["CreatedTime"].GetString());
m_createdTimeHasBeenSet = true;
}
if (value.HasMember("ServiceExtraSet") && !value["ServiceExtraSet"].IsNull())
{
if (!value["ServiceExtraSet"].IsArray())
return CoreInternalOutcome(Core::Error("response `ServiceTemplate.ServiceExtraSet` is not array type"));
const rapidjson::Value &tmpValue = value["ServiceExtraSet"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
ServicesInfo item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_serviceExtraSet.push_back(item);
}
m_serviceExtraSetHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void ServiceTemplate::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_serviceTemplateIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServiceTemplateId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_serviceTemplateId.c_str(), allocator).Move(), allocator);
}
if (m_serviceTemplateNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServiceTemplateName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_serviceTemplateName.c_str(), allocator).Move(), allocator);
}
if (m_serviceSetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServiceSet";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_serviceSet.begin(); itr != m_serviceSet.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_createdTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreatedTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_createdTime.c_str(), allocator).Move(), allocator);
}
if (m_serviceExtraSetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServiceExtraSet";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_serviceExtraSet.begin(); itr != m_serviceExtraSet.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
string ServiceTemplate::GetServiceTemplateId() const
{
return m_serviceTemplateId;
}
void ServiceTemplate::SetServiceTemplateId(const string& _serviceTemplateId)
{
m_serviceTemplateId = _serviceTemplateId;
m_serviceTemplateIdHasBeenSet = true;
}
bool ServiceTemplate::ServiceTemplateIdHasBeenSet() const
{
return m_serviceTemplateIdHasBeenSet;
}
string ServiceTemplate::GetServiceTemplateName() const
{
return m_serviceTemplateName;
}
void ServiceTemplate::SetServiceTemplateName(const string& _serviceTemplateName)
{
m_serviceTemplateName = _serviceTemplateName;
m_serviceTemplateNameHasBeenSet = true;
}
bool ServiceTemplate::ServiceTemplateNameHasBeenSet() const
{
return m_serviceTemplateNameHasBeenSet;
}
vector<string> ServiceTemplate::GetServiceSet() const
{
return m_serviceSet;
}
void ServiceTemplate::SetServiceSet(const vector<string>& _serviceSet)
{
m_serviceSet = _serviceSet;
m_serviceSetHasBeenSet = true;
}
bool ServiceTemplate::ServiceSetHasBeenSet() const
{
return m_serviceSetHasBeenSet;
}
string ServiceTemplate::GetCreatedTime() const
{
return m_createdTime;
}
void ServiceTemplate::SetCreatedTime(const string& _createdTime)
{
m_createdTime = _createdTime;
m_createdTimeHasBeenSet = true;
}
bool ServiceTemplate::CreatedTimeHasBeenSet() const
{
return m_createdTimeHasBeenSet;
}
vector<ServicesInfo> ServiceTemplate::GetServiceExtraSet() const
{
return m_serviceExtraSet;
}
void ServiceTemplate::SetServiceExtraSet(const vector<ServicesInfo>& _serviceExtraSet)
{
m_serviceExtraSet = _serviceExtraSet;
m_serviceExtraSetHasBeenSet = true;
}
bool ServiceTemplate::ServiceExtraSetHasBeenSet() const
{
return m_serviceExtraSetHasBeenSet;
}
| 31.805785 | 153 | 0.692608 | [
"vector",
"model"
] |
60e15835932c689cd92b3c1cbc7d113191ccc9d1 | 8,667 | cpp | C++ | src/optionconverter.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | 1 | 2016-10-06T20:09:32.000Z | 2016-10-06T20:09:32.000Z | src/optionconverter.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | null | null | null | src/optionconverter.cpp | MacroGu/log4cxx_gcc_4_8 | c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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 <log4cxx/spi/loggerfactory.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/helpers/optionconverter.h>
#include <algorithm>
#include <ctype.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/exception.h>
#include <stdlib.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/object.h>
#include <log4cxx/helpers/class.h>
#include <log4cxx/helpers/loader.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/xml/domconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#ifdef HAVE_XML
using namespace log4cxx::xml;
#endif
String OptionConverter::DELIM_START = _T("${");
TCHAR OptionConverter::DELIM_STOP = _T('}');
int OptionConverter::DELIM_START_LEN = 2;
int OptionConverter::DELIM_STOP_LEN = 1;
namespace {
// Function object to turn a lower case character into an upper case one
class ToUpper {
public:
void operator()(TCHAR& c){c = toupper(c);}
};
}
String OptionConverter::convertSpecialChars(const String& s)
{
TCHAR c;
int len = s.length();
StringBuffer sbuf;
String::const_iterator i = s.begin();
while(i != s.end())
{
c = *i++;
if (c == _T('\\'))
{
c = *i++;
switch (c)
{
case _T('n'):
c = _T('\n');
break;
case _T('r'):
c = _T('\r');
break;
case _T('t'):
c = _T('\t');
break;
case _T('f'):
c = _T('\f');
break;
case _T('\b'):
c = _T('\b');
break;
case _T('\"'):
c = _T('\"');
break;
case _T('\''):
c = _T('\'');
break;
case _T('\\'):
c = _T('\\');
break;
}
}
sbuf.put(c);
}
return sbuf.str();
}
bool OptionConverter::toBoolean(const String& value, bool dEfault)
{
if (value.empty())
{
return dEfault;
}
String trimmedVal = StringHelper::toLowerCase(StringHelper::trim(value));
if (trimmedVal == _T("true"))
{
return true;
}
if (trimmedVal == _T("false"))
{
return false;
}
return dEfault;
}
int OptionConverter::toInt(const String& value, int dEfault)
{
if (value.empty())
{
return dEfault;
}
return (int)ttol(StringHelper::trim(value).c_str());
}
long OptionConverter::toFileSize(const String& value, long dEfault)
{
if(value.empty())
{
return dEfault;
}
String s = StringHelper::toLowerCase(StringHelper::trim(value));
long multiplier = 1;
int index;
if((index = s.find(_T("kb"))) != -1)
{
multiplier = 1024;
s = s.substr(0, index);
}
else if((index = s.find(_T("mb"))) != -1)
{
multiplier = 1024*1024;
s = s.substr(0, index);
}
else if((index = s.find(_T("gb"))) != -1)
{
multiplier = 1024*1024*1024;
s = s.substr(0, index);
}
if(!s.empty())
{
return ttol(s.c_str()) * multiplier;
}
return dEfault;
}
String OptionConverter::findAndSubst(const String& key, Properties& props)
{
String value = props.getProperty(key);
if(value.empty())
return value;
try
{
return substVars(value, props);
}
catch(IllegalArgumentException& e)
{
LogLog::error(_T("Bad option value [")+value+_T("]."), e);
return value;
}
}
String OptionConverter::substVars(const String& val, Properties& props)
{
StringBuffer sbuf;
int i = 0;
int j, k;
while(true)
{
j = val.find(DELIM_START, i);
if(j == -1)
{
// no more variables
if(i==0)
{ // this is a simple string
return val;
}
else
{ // add the tail string which contails no variables and return the result.
sbuf << val.substr(i, val.length() - i);
return sbuf.str();
}
}
else
{
sbuf << val.substr(i, j - i);
k = val.find(DELIM_STOP, j);
if(k == -1)
{
StringBuffer oss;
oss << _T("\"") << val
<< _T("\" has no closing brace. Opening brace at position ")
<< j << _T(".");
throw IllegalArgumentException(oss.str());
}
else
{
j += DELIM_START_LEN;
String key = val.substr(j, k - j);
// first try in System properties
String replacement = getSystemProperty(key, _T(""));
// then try props parameter
if(replacement.empty())
{
replacement = props.getProperty(key);
}
if(!replacement.empty())
{
// Do variable substitution on the replacement string
// such that we can solve "Hello ${x2}" as "Hello p1"
// the where the properties are
// x1=p1
// x2=${x1}
String recursiveReplacement = substVars(replacement, props);
sbuf << (recursiveReplacement);
}
i = k + DELIM_STOP_LEN;
}
}
}
}
String OptionConverter::getSystemProperty(const String& key, const String& def)
{
if (!key.empty())
{
String value = System::getProperty(key);
if (!value.empty())
{
return value;
}
else
{
return def;
}
}
else
{
return def;
}
}
const LevelPtr& OptionConverter::toLevel(const String& value,
const LevelPtr& defaultValue)
{
int hashIndex = value.find(_T("#"));
if (hashIndex == -1)
{
if (value.empty())
{
return defaultValue;
}
else
{
LogLog::debug(
_T("OptionConverter::toLevel: no class name specified, level=[")
+value+_T("]"));
// no class name specified : use standard Level class
return Level::toLevel(value, defaultValue);
}
}
const LevelPtr& result = defaultValue;
String clazz = value.substr(hashIndex + 1);
String levelName = value.substr(0, hashIndex);
LogLog::debug(_T("OptionConverter::toLevel: class=[") +clazz+_T("], level=[")+
levelName+_T("]"));
// This is degenerate case but you never know.
if (levelName.empty())
{
return Level::toLevel(value, defaultValue);
}
try
{
Level::LevelClass& levelClass =
(Level::LevelClass&)Loader::loadClass(clazz);
return levelClass.toLevel(levelName);
}
catch (ClassNotFoundException&)
{
LogLog::warn(_T("custom level class [") + clazz + _T("] not found."));
}
catch(Exception& oops)
{
LogLog::warn(
_T("class [") + clazz + _T("], level [") + levelName +
_T("] conversion) failed."), oops);
}
catch(...)
{
LogLog::warn(
_T("class [") + clazz + _T("], level [") + levelName +
_T("] conversion) failed."));
}
return defaultValue;
}
ObjectPtr OptionConverter::instantiateByKey(Properties& props, const String& key,
const Class& superClass, const ObjectPtr& defaultValue)
{
// Get the value of the property in string form
String className = findAndSubst(key, props);
if(className.empty())
{
LogLog::error(_T("Could not find value for key ") + key);
return defaultValue;
}
// Trim className to avoid trailing spaces that cause problems.
return OptionConverter::instantiateByClassName(
StringHelper::trim(className), superClass, defaultValue);
}
ObjectPtr OptionConverter::instantiateByClassName(const String& className,
const Class& superClass, const ObjectPtr& defaultValue)
{
if(!className.empty())
{
try
{
const Class& classObj = Loader::loadClass(className);
ObjectPtr newObject = classObj.newInstance();
if (!newObject->instanceof(superClass))
{
return defaultValue;
}
return newObject;
}
catch (Exception& e)
{
LogLog::error(_T("Could not instantiate class [") + className
+ _T("]."), e);
}
}
return defaultValue;
}
void OptionConverter::selectAndConfigure(const String& configFileName,
const String& _clazz, spi::LoggerRepositoryPtr& hierarchy)
{
ConfiguratorPtr configurator;
String clazz = _clazz;
#ifdef HAVE_XML
if(clazz.empty() && !configFileName.empty()
&& StringHelper::endsWith(configFileName, _T(".xml")))
{
clazz = DOMConfigurator::getStaticClass().toString();
}
#endif
if(!clazz.empty())
{
LogLog::debug(_T("Preferred configurator class: ") + clazz);
configurator = instantiateByClassName(clazz,
Configurator::getStaticClass(),
0);
if(configurator == 0)
{
LogLog::error(_T("Could not instantiate configurator [")+
clazz+_T("]."));
return;
}
}
else
{
configurator = new PropertyConfigurator();
}
configurator->doConfigure(configFileName, hierarchy);
}
| 20.934783 | 81 | 0.646937 | [
"object"
] |
60e258757820ae743ade7a927bc79015bb6c096a | 323 | hpp | C++ | include/robot/camera.hpp | jeguzzi/robomaster_sim | 714ec58340251dc318c0fa2508a3ad6afe12ea2c | [
"MIT"
] | 11 | 2021-10-13T08:11:51.000Z | 2022-03-15T16:20:31.000Z | include/robot/camera.hpp | jeguzzi/robomaster_sim | 714ec58340251dc318c0fa2508a3ad6afe12ea2c | [
"MIT"
] | 1 | 2021-12-02T13:47:49.000Z | 2021-12-02T14:03:00.000Z | include/robot/camera.hpp | jeguzzi/robomaster_sim | 714ec58340251dc318c0fa2508a3ad6afe12ea2c | [
"MIT"
] | null | null | null | #ifndef INCLUDE_ROBOT_CAMERA_HPP_
#define INCLUDE_ROBOT_CAMERA_HPP_
#include <vector>
#include "../utils.hpp"
using Image = std::vector<uint8_t>;
struct Camera {
int width;
int height;
float fps;
bool streaming;
Image image;
Camera()
: streaming(false) {}
};
#endif // INCLUDE_ROBOT_CAMERA_HPP_ */
| 15.380952 | 40 | 0.69969 | [
"vector"
] |
60e311cefe21ed27495e03a8489b2e6ec4068ba4 | 8,407 | cpp | C++ | scene/3d/visibility_notifier.cpp | Qwertie-/godot | cf04e1a827cadb597d8cbed534a4cc04a0ada4fc | [
"MIT"
] | 1 | 2019-07-17T03:59:30.000Z | 2019-07-17T03:59:30.000Z | scene/3d/visibility_notifier.cpp | mikica1986vee/godot_build_fix | 4da2ce6fe3336219ce1b251718ae6ec8e83bafb9 | [
"MIT"
] | null | null | null | scene/3d/visibility_notifier.cpp | mikica1986vee/godot_build_fix | 4da2ce6fe3336219ce1b251718ae6ec8e83bafb9 | [
"MIT"
] | null | null | null | /*************************************************************************/
/* visibility_notifier.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "visibility_notifier.h"
#include "scene/scene_string_names.h"
#include "scene/3d/physics_body.h"
#include "scene/animation/animation_player.h"
#include "scene/scene_string_names.h"
void VisibilityNotifier::_enter_camera(Camera* p_camera) {
ERR_FAIL_COND(cameras.has(p_camera));
cameras.insert(p_camera);
if (cameras.size()==1) {
emit_signal(SceneStringNames::get_singleton()->enter_screen);
_screen_enter();
}
emit_signal(SceneStringNames::get_singleton()->enter_camera,p_camera);
}
void VisibilityNotifier::_exit_camera(Camera* p_camera){
ERR_FAIL_COND(!cameras.has(p_camera));
cameras.erase(p_camera);
emit_signal(SceneStringNames::get_singleton()->exit_camera,p_camera);
if (cameras.size()==0) {
emit_signal(SceneStringNames::get_singleton()->exit_screen);
_screen_exit();
}
}
void VisibilityNotifier::set_aabb(const AABB& p_aabb){
if (aabb==p_aabb)
return;
aabb=p_aabb;
if (is_inside_world()) {
get_world()->_update_notifier(this,get_global_transform().xform(aabb));
}
_change_notify("aabb");
update_gizmo();
}
AABB VisibilityNotifier::get_aabb() const{
return aabb;
}
void VisibilityNotifier::_notification(int p_what) {
switch(p_what) {
case NOTIFICATION_ENTER_WORLD: {
get_world()->_register_notifier(this,get_global_transform().xform(aabb));
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
get_world()->_update_notifier(this,get_global_transform().xform(aabb));
} break;
case NOTIFICATION_EXIT_WORLD: {
get_world()->_remove_notifier(this);
} break;
}
}
bool VisibilityNotifier::is_on_screen() const {
return cameras.size()!=0;
}
void VisibilityNotifier::_bind_methods(){
ObjectTypeDB::bind_method(_MD("set_aabb","rect"),&VisibilityNotifier::set_aabb);
ObjectTypeDB::bind_method(_MD("get_aabb"),&VisibilityNotifier::get_aabb);
ObjectTypeDB::bind_method(_MD("is_on_screen"),&VisibilityNotifier::is_on_screen);
ADD_PROPERTY( PropertyInfo(Variant::_AABB,"aabb"),_SCS("set_aabb"),_SCS("get_aabb"));
ADD_SIGNAL( MethodInfo("enter_camera",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) );
ADD_SIGNAL( MethodInfo("exit_camera",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) );
ADD_SIGNAL( MethodInfo("enter_screen"));
ADD_SIGNAL( MethodInfo("exit_screen"));
}
VisibilityNotifier::VisibilityNotifier() {
aabb=AABB(Vector3(-1,-1,-1),Vector3(2,2,2));
}
//////////////////////////////////////
void VisibilityEnabler::_screen_enter() {
for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
_change_node_state(E->key(),true);
}
visible=true;
}
void VisibilityEnabler::_screen_exit() {
for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
_change_node_state(E->key(),false);
}
visible=false;
}
void VisibilityEnabler::_find_nodes(Node* p_node) {
bool add=false;
Variant meta;
if (enabler[ENABLER_FREEZE_BODIES]) {
RigidBody *rb = p_node->cast_to<RigidBody>();
if (rb && ((rb->get_mode()==RigidBody::MODE_CHARACTER || (rb->get_mode()==RigidBody::MODE_RIGID && !rb->is_able_to_sleep())))) {
add=true;
meta=rb->get_mode();
}
}
if (enabler[ENABLER_PAUSE_ANIMATIONS]) {
AnimationPlayer *ap = p_node->cast_to<AnimationPlayer>();
if (ap) {
add=true;
}
}
if (add) {
p_node->connect(SceneStringNames::get_singleton()->exit_scene,this,"_node_removed",varray(p_node),CONNECT_ONESHOT);
nodes[p_node]=meta;
_change_node_state(p_node,false);
}
for(int i=0;i<p_node->get_child_count();i++) {
Node *c = p_node->get_child(i);
if (c->get_filename()!=String())
continue; //skip, instance
_find_nodes(c);
}
}
void VisibilityEnabler::_notification(int p_what){
if (p_what==NOTIFICATION_ENTER_SCENE) {
if (get_scene()->is_editor_hint())
return;
Node *from = this;
//find where current scene starts
while(from->get_parent() && from->get_filename()==String())
from=from->get_parent();
_find_nodes(from);
}
if (p_what==NOTIFICATION_EXIT_SCENE) {
if (get_scene()->is_editor_hint())
return;
Node *from = this;
//find where current scene starts
for (Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
if (!visible)
_change_node_state(E->key(),true);
E->key()->disconnect(SceneStringNames::get_singleton()->exit_scene,this,"_node_removed");
}
nodes.clear();
}
}
void VisibilityEnabler::_change_node_state(Node* p_node,bool p_enabled) {
ERR_FAIL_COND(!nodes.has(p_node));
{
RigidBody *rb = p_node->cast_to<RigidBody>();
if (rb) {
if (p_enabled) {
RigidBody::Mode mode = RigidBody::Mode(nodes[p_node].operator int());
//rb->set_mode(mode);
rb->set_sleeping(false);
} else {
//rb->set_mode(RigidBody::MODE_STATIC);
rb->set_sleeping(true);
}
}
}
{
AnimationPlayer *ap=p_node->cast_to<AnimationPlayer>();
if (ap) {
ap->set_active(p_enabled);
}
}
}
void VisibilityEnabler::_node_removed(Node* p_node) {
if (!visible)
_change_node_state(p_node,true);
p_node->disconnect(SceneStringNames::get_singleton()->exit_scene,this,"_node_removed");
nodes.erase(p_node);
}
void VisibilityEnabler::_bind_methods(){
ObjectTypeDB::bind_method(_MD("set_enabler","enabler","enabled"),&VisibilityEnabler::set_enabler);
ObjectTypeDB::bind_method(_MD("is_enabler_enabled","enabler"),&VisibilityEnabler::is_enabler_enabled);
ObjectTypeDB::bind_method(_MD("_node_removed"),&VisibilityEnabler::_node_removed);
ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"enabler/pause_animations"),_SCS("set_enabler"),_SCS("is_enabler_enabled"), ENABLER_PAUSE_ANIMATIONS );
ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"enabler/freeze_bodies"),_SCS("set_enabler"),_SCS("is_enabler_enabled"), ENABLER_FREEZE_BODIES);
BIND_CONSTANT( ENABLER_FREEZE_BODIES );
BIND_CONSTANT( ENABLER_PAUSE_ANIMATIONS );
BIND_CONSTANT( ENABLER_MAX);
}
void VisibilityEnabler::set_enabler(Enabler p_enabler,bool p_enable){
ERR_FAIL_INDEX(p_enabler,ENABLER_MAX);
enabler[p_enabler]=p_enable;
}
bool VisibilityEnabler::is_enabler_enabled(Enabler p_enabler) const{
ERR_FAIL_INDEX_V(p_enabler,ENABLER_MAX,false);
return enabler[p_enabler];
}
VisibilityEnabler::VisibilityEnabler() {
for(int i=0;i<ENABLER_MAX;i++)
enabler[i]=true;
visible=false;
}
| 26.688889 | 146 | 0.650529 | [
"object",
"3d"
] |
60e7f16c90974e7ab363301f9a63de2d67f11a9b | 2,257 | cc | C++ | mindspore/lite/tools/converter/anf_transform.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/anf_transform.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/anf_transform.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/converter/anf_transform.h"
#include <memory>
#include <string>
#include "utils/log_adapter.h"
#include "tools/optimizer/fusion/conv_biasadd_fusion.h"
#include "tools/optimizer/fusion/conv_activation_fusion.h"
#include "tools/optimizer/fusion/conv_scale_fusion.h"
#include "tools/optimizer/fusion/conv_bn_fusion.h"
#include "tools/optimizer/fusion/constant_folding_fusion.h"
using std::string;
namespace mindspore {
namespace lite {
AnfTransform::AnfTransform() = default;
AnfTransform::~AnfTransform() = default;
void AnfTransform::SetGraphDef(schema::MetaGraphT *_dstDef) { graphDefT = _dstDef; }
FuncGraphPtr AnfTransform::Transform(const FuncGraphPtr &old_graph) {
// return old_graph;
auto optimizer = std::make_shared<opt::GraphOptimizer>();
auto pm = std::make_shared<opt::PassManager>("anf fusion pass manager", false);
pm->AddPass(std::make_shared<opt::ConvBiasaddFusion>());
pm->AddPass(std::make_shared<opt::ConvBatchNormFusion>());
pm->AddPass(std::make_shared<opt::ConvScaleFusion>());
pm->AddPass(std::make_shared<opt::ConvActivationFusion>(true, "conv_relu", schema::PrimitiveType_Activation,
schema::ActivationType_RELU));
pm->AddPass(std::make_shared<opt::ConvActivationFusion>(true, "conv_relu6", schema::PrimitiveType_Activation,
schema::ActivationType_RELU6));
pm->AddPass(std::make_shared<opt::ConstFoldPass>());
optimizer->AddPassManager(pm);
FuncGraphPtr new_graph = optimizer->Optimize(old_graph);
return new_graph;
}
} // namespace lite
} // namespace mindspore
| 41.036364 | 111 | 0.725742 | [
"transform"
] |
60e8d6bb0d5b1462ebfb16570e0b68f97b6dff98 | 3,197 | cpp | C++ | examples/serializer/serializer.cpp | breakin/sednl | 1003b55793b36dbf1d3e652e375d2990f31b3878 | [
"Zlib"
] | 9 | 2015-01-27T16:14:09.000Z | 2016-11-10T00:12:35.000Z | examples/serializer/serializer.cpp | breakin/sednl | 1003b55793b36dbf1d3e652e375d2990f31b3878 | [
"Zlib"
] | 2 | 2016-01-26T13:36:51.000Z | 2017-11-07T13:00:55.000Z | examples/serializer/serializer.cpp | breakin/sednl | 1003b55793b36dbf1d3e652e375d2990f31b3878 | [
"Zlib"
] | 4 | 2015-01-10T13:28:34.000Z | 2018-06-17T13:32:53.000Z | // SEDNL - Copyright (c) 2013 Jeremy S. Cochoy
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from
// the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
#include <SEDNL/Packet.hpp>
#include <SEDNL/Serializer.hpp>
#include <iostream>
using namespace SedNL;
class Foo
{
public:
Foo()
:m_int(0), m_char(0)
{
std::cout << "Foo constructed" << std::endl;
};
void set_things(char c, int n, std::string s)
{
m_char = c;
m_int = n;
m_string = s;
}
void show()
{
std::cout << "Foo instance : m_char = "
<< m_char
<< " m_int = "
<< m_int
<< " m_string = "
<< m_string
<< std::endl;
}
//
// None of these methods are needed.
//
// If they are available they will be called.
// Otherwise, your object will be serialised
// without trying to call this methods.
//
// You can use them, to release or re-create data
// that can't be transmited. For example, connection
// to a database. (You may need serialized data before
// connecting to database,
// or you may want to release a connection before
// unserialization. )
void before_serialization()
{
std::cout << "Before serialization" << std::endl;
};
void after_serialization()
{
std::cout << "After serialization" << std::endl;
};
void before_unserialization()
{
std::cout << "Before unserialization" << std::endl;
};
void after_unserialization()
{
std::cout << "After unserialization" << std::endl;
};
private:
int m_int;
char m_char;
std::string m_string;
public:
//
// Allow serialisation
//
SEDNL_SERIALIZABLE(m_int, m_char, m_string);
};
int main(int, char*[])
{
//Create and setup a Foo instance
Foo first;
first.set_things('*', 23, "Hello World");
first.show();
//Serialize the Foo instance
Packet p;
p << first; //same as first.serialize(p);
// Here, you would probably send the packet through the network
//Create an other Foo instance
Foo second;
//Unserialize into the new instance
PacketReader r(p);
r >> second; //same as second.unserialize(r);
//Display the content
second.show();
return EXIT_SUCCESS;
}
| 25.173228 | 78 | 0.607444 | [
"object"
] |
60f1eb7276518916ab0d4a4e80a708605f2a5e89 | 6,557 | hpp | C++ | src/gpu/jit/ngen/ngen_opencl.hpp | Srini511/oneDNN | b2cd3a8e50a715f9326a35f4c503bd11e60235a5 | [
"Apache-2.0"
] | 1 | 2022-01-26T10:23:30.000Z | 2022-01-26T10:23:30.000Z | src/gpu/jit/ngen/ngen_opencl.hpp | Srini511/oneDNN | b2cd3a8e50a715f9326a35f4c503bd11e60235a5 | [
"Apache-2.0"
] | null | null | null | src/gpu/jit/ngen/ngen_opencl.hpp | Srini511/oneDNN | b2cd3a8e50a715f9326a35f4c503bd11e60235a5 | [
"Apache-2.0"
] | 1 | 2022-01-27T10:08:30.000Z | 2022-01-27T10:08:30.000Z | /*******************************************************************************
* Copyright 2019-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef NGEN_OPENCL_HPP
#define NGEN_OPENCL_HPP
#include "ngen_config.hpp"
#include <CL/cl.h>
#include <sstream>
#include "ngen_elf.hpp"
#include "ngen_interface.hpp"
#include "npack/neo_packager.hpp"
namespace ngen {
// Exceptions.
class unsupported_opencl_runtime : public std::runtime_error {
public:
unsupported_opencl_runtime() : std::runtime_error("Unsupported OpenCL runtime.") {}
};
class opencl_error : public std::runtime_error {
public:
opencl_error(cl_int status_ = 0) : std::runtime_error("An OpenCL error occurred: " + std::to_string(status_)), status(status_) {}
protected:
cl_int status;
};
// OpenCL program generator class.
template <HW hw>
class OpenCLCodeGenerator : public ELFCodeGenerator<hw>
{
public:
explicit OpenCLCodeGenerator(int stepping_ = 0) : ELFCodeGenerator<hw>(stepping_) {}
inline std::vector<uint8_t> getBinary(cl_context context, cl_device_id device, const std::string &options = "-cl-std=CL2.0");
inline cl_kernel getKernel(cl_context context, cl_device_id device, const std::string &options = "-cl-std=CL2.0");
static inline HW detectHW(cl_context context, cl_device_id device);
static inline void detectHWInfo(cl_context context, cl_device_id device, HW &outHW, int &outStepping);
};
#define NGEN_FORWARD_OPENCL(hw) NGEN_FORWARD_ELF(hw)
namespace detail {
static inline void handleCL(cl_int result)
{
if (result != CL_SUCCESS)
throw opencl_error{result};
}
static inline std::vector<uint8_t> getOpenCLCProgramBinary(cl_context context, cl_device_id device, const char *src, const char *options)
{
cl_int status;
auto program = clCreateProgramWithSource(context, 1, &src, nullptr, &status);
detail::handleCL(status);
if (program == nullptr)
throw opencl_error();
detail::handleCL(clBuildProgram(program, 1, &device, options, nullptr, nullptr));
size_t nDevices = 0;
detail::handleCL(clGetProgramInfo(program, CL_PROGRAM_NUM_DEVICES, sizeof(size_t), &nDevices, nullptr));
std::vector<cl_device_id> devices(nDevices);
detail::handleCL(clGetProgramInfo(program, CL_PROGRAM_DEVICES, sizeof(cl_device_id) * nDevices, devices.data(), nullptr));
size_t deviceIdx = std::distance(devices.begin(), std::find(devices.begin(), devices.end(), device));
if (deviceIdx >= nDevices)
throw opencl_error();
std::vector<size_t> binarySize(nDevices);
std::vector<uint8_t *> binaryPointers(nDevices);
std::vector<std::vector<uint8_t>> binaries(nDevices);
detail::handleCL(clGetProgramInfo(program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t) * nDevices, binarySize.data(), nullptr));
for (size_t i = 0; i < nDevices; i++) {
binaries[i].resize(binarySize[i]);
binaryPointers[i] = binaries[i].data();
}
detail::handleCL(clGetProgramInfo(program, CL_PROGRAM_BINARIES, sizeof(uint8_t *) * nDevices, binaryPointers.data(), nullptr));
detail::handleCL(clReleaseProgram(program));
return binaries[deviceIdx];
}
inline bool tryZebin(cl_device_id device)
{
// Zebin is not yet supported by the OpenCL RT.
// Once it is, check driver version before attempting to pass in zebin.
return false;
}
}; /* namespace detail */
template <HW hw>
std::vector<uint8_t> OpenCLCodeGenerator<hw>::getBinary(cl_context context, cl_device_id device, const std::string &options)
{
using super = ELFCodeGenerator<hw>;
std::ostringstream dummyCL;
auto modOptions = options;
if ((hw >= HW::XeHP) && (super::interface_.needGRF > 128))
modOptions.append(" -cl-intel-256-GRF-per-thread");
super::interface_.generateDummyCL(dummyCL);
auto dummyCLString = dummyCL.str();
auto binary = detail::getOpenCLCProgramBinary(context, device, dummyCLString.c_str(), modOptions.c_str());
npack::replaceKernel(binary, this->getCode());
return binary;
}
template <HW hw>
cl_kernel OpenCLCodeGenerator<hw>::getKernel(cl_context context, cl_device_id device, const std::string &options)
{
using super = ELFCodeGenerator<hw>;
cl_int status = CL_SUCCESS;
cl_program program = nullptr;
bool good = false;
for (bool legacy : {false, true}) {
if (!legacy && !detail::tryZebin(device))
continue;
auto binary = legacy ? getBinary(context, device) : super::getBinary();
const auto *binaryPtr = binary.data();
size_t binarySize = binary.size();
status = CL_SUCCESS;
program = clCreateProgramWithBinary(context, 1, &device, &binarySize, &binaryPtr, nullptr, &status);
if ((program == nullptr) || (status != CL_SUCCESS))
continue;
status = clBuildProgram(program, 1, &device, options.c_str(), nullptr, nullptr);
good = (status == CL_SUCCESS);
if (good)
break;
else
detail::handleCL(clReleaseProgram(program));
}
if (!good)
throw opencl_error(status);
auto kernel = clCreateKernel(program, super::interface_.getExternalName().c_str(), &status);
detail::handleCL(status);
if (kernel == nullptr)
throw opencl_error();
detail::handleCL(clReleaseProgram(program));
return kernel;
}
template <HW hw>
HW OpenCLCodeGenerator<hw>::detectHW(cl_context context, cl_device_id device)
{
HW outHW;
int outStepping;
detectHWInfo(context, device, outHW, outStepping);
return outHW;
}
template <HW hw>
void OpenCLCodeGenerator<hw>::detectHWInfo(cl_context context, cl_device_id device, HW &outHW, int &outStepping)
{
const char *dummyCL = "kernel void _(){}";
const char *dummyOptions = "";
auto binary = detail::getOpenCLCProgramBinary(context, device, dummyCL, dummyOptions);
ELFCodeGenerator<hw>::getBinaryHWInfo(binary, outHW, outStepping);
}
} /* namespace ngen */
#endif
| 32.460396 | 137 | 0.688882 | [
"vector"
] |
60f43d45b2b6b9bf8eb73682cfbd6a944d810b57 | 45,143 | cpp | C++ | src/GameBoy/RendererVulkan.cpp | michaelxmroz/GameBoy | 517e95ded80d8d9b0f2570064064c8aaf3724f7d | [
"MIT"
] | 1 | 2022-02-04T00:14:19.000Z | 2022-02-04T00:14:19.000Z | src/GameBoy/RendererVulkan.cpp | michaelxmroz/GameBoy | 517e95ded80d8d9b0f2570064064c8aaf3724f7d | [
"MIT"
] | null | null | null | src/GameBoy/RendererVulkan.cpp | michaelxmroz/GameBoy | 517e95ded80d8d9b0f2570064064c8aaf3724f7d | [
"MIT"
] | null | null | null | #include "RendererVulkan.h"
#include "vulkan/vulkan.h"
#include "Logging.h"
#include <vector>
#include <set>
#include <algorithm>
#include <array>
#include "FileParser.h"
#include "ShaderCompiler.h"
#if _DEBUG
#define VK_CHECK(x) \
do \
{ \
VkResult err = x; \
if (err) \
{ \
LOG_ERROR(string_format("Detected Vulkan error: %s\n", std::to_string(static_cast<int32_t>(err)).c_str()).c_str()); \
abort(); \
} \
} while (0)
#else
#define VK_CHECK(x) { x; }
#endif
namespace RendererVulkanInternal
{
struct SwapChainSupportDetails
{
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct QueueFamilyIndices
{
enum class QueueTypes
{
Graphics = 0,
Present = 1,
COUNT = 2
};
QueueFamilyIndices() :
m_isPresent{ false }
{
}
bool IsComplete()
{
bool complete = true;
for (uint32_t i = 0; i < static_cast<uint32_t>(QueueTypes::COUNT); ++i)
{
complete &= m_isPresent[i];
}
return complete;
}
bool IsFamilyPresent(QueueTypes type)
{
return m_isPresent[static_cast<uint32_t>(type)];
}
uint32_t GetFamilyIndex(QueueTypes type)
{
return m_index[static_cast<uint32_t>(type)];
}
bool m_isPresent[static_cast<uint32_t>(QueueTypes::COUNT)];
uint32_t m_index[static_cast<uint32_t>(QueueTypes::COUNT)];
};
#if VALIDATION_LAYERS
VKAPI_ATTR VkBool32 VKAPI_CALL ValidationLogCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) {
if(messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
{
LOG_ERROR(pCallbackData->pMessage);
}
else if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
{
LOG_WARNING(pCallbackData->pMessage);
}
return VK_FALSE;
}
void InitValidationCallback(VkInstance instance, VkDebugUtilsMessengerEXT& messenger)
{
VkDebugUtilsMessengerCreateInfoEXT createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = ValidationLogCallback;
createInfo.pUserData = nullptr; // Optional
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
VK_CHECK(func(instance, &createInfo, nullptr, &messenger));
}
#endif
bool ValidateExtensions(const std::vector<const char*>& required,
const std::vector<VkExtensionProperties>& available)
{
for (auto extension : required)
{
bool found = false;
for (auto& available_extension : available)
{
if (strcmp(available_extension.extensionName, extension) == 0)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
bool ValidateLayers(const std::vector<const char*>& required,
const std::vector<VkLayerProperties>& available)
{
for (auto extension : required)
{
bool found = false;
for (auto& available_extension : available)
{
if (strcmp(available_extension.layerName, extension) == 0)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface)
{
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0) {
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0) {
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
void FindQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface, QueueFamilyIndices& indices)
{
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.m_isPresent[static_cast<uint32_t>(QueueFamilyIndices::QueueTypes::Graphics)] = true;
indices.m_index[static_cast<uint32_t>(QueueFamilyIndices::QueueTypes::Graphics)] = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport)
{
indices.m_isPresent[static_cast<uint32_t>(QueueFamilyIndices::QueueTypes::Present)] = true;
indices.m_index[static_cast<uint32_t>(QueueFamilyIndices::QueueTypes::Present)] = i;
}
if (indices.IsComplete())
{
break;
}
i++;
}
}
bool CheckDeviceExtensionSupport(VkPhysicalDevice device)
{
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
bool IsDeviceSupported(VkPhysicalDevice device, VkSurfaceKHR surface)
{
QueueFamilyIndices indices;
FindQueueFamilies(device, surface, indices);
bool extensionsSupported = CheckDeviceExtensionSupport(device);
bool swapChainAdequate = false;
if (extensionsSupported) {
SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport(device, surface);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
return indices.IsComplete() && swapChainAdequate;
}
VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, uint32_t width, uint32_t height)
{
if (capabilities.currentExtent.width != UINT32_MAX) {
return capabilities.currentExtent;
}
else {
VkExtent2D actualExtent = {
static_cast<uint32_t>(width),
static_cast<uint32_t>(height)
};
return actualExtent;
}
}
VkPresentModeKHR ChooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes)
{
return VK_PRESENT_MODE_FIFO_KHR;
}
VkSurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats)
{
for (const auto& availableFormat : availableFormats)
{
if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT)
{
return availableFormat;
}
}
return availableFormats[0];
}
VkShaderModule CreateShaderModule(VkDevice logicalDevice, const std::vector<uint32_t>& code)
{
VkShaderModuleCreateInfo createInfo { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
createInfo.codeSize = code.size() * 4;
createInfo.pCode = code.data();
VkShaderModule shaderModule;
VK_CHECK(vkCreateShaderModule(logicalDevice, &createInfo, nullptr, &shaderModule));
return shaderModule;
}
VkVertexInputBindingDescription GetVertexBindingDescription()
{
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
std::array<VkVertexInputAttributeDescription, 2> GetVertexAttributeDescriptions()
{
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, m_pos);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, m_uv);
return attributeDescriptions;
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
return 0;
}
void CreateBuffer(VkDevice logicalDevice, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(vkCreateBuffer(logicalDevice, &bufferInfo, nullptr, &buffer));
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(logicalDevice, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
VK_CHECK(vkAllocateMemory(logicalDevice, &allocInfo, nullptr, &bufferMemory));
vkBindBufferMemory(logicalDevice, buffer, bufferMemory, 0);
}
void TransitionImageLayout(VkCommandBuffer buffer, VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout)
{
VkImageMemoryBarrier barrier{ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
vkCmdPipelineBarrier(
buffer,
sourceStage,
destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
}
void CopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer buffer, VkImage image, uint32_t width, uint32_t height)
{
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
}
}
RendererVulkan::RendererVulkan(uint32_t sourceWidth, uint32_t sourceHeight, uint32_t scale)
: m_instance(VK_NULL_HANDLE)
, m_physicalDevice(VK_NULL_HANDLE)
, m_logicalDevice(VK_NULL_HANDLE)
, m_graphicsQueue(VK_NULL_HANDLE)
, m_surface(VK_NULL_HANDLE)
#if VALIDATION_LAYERS
, m_debugMessenger(VK_NULL_HANDLE)
#endif
, m_sourceWidth(sourceWidth)
, m_sourceHeight(sourceHeight)
, m_scaledWidth(sourceWidth * scale)
, m_scaledHeight(sourceHeight * scale)
, m_mainShaderName("main.glsl")
, m_fullscreenQuadVertices {{{-1,-1,0},{0,0}}, {{1,1,0},{1,1}}, {{-1,1,0},{0,1}}, {{1,-1,0},{1,0}} }
, m_fullscreenQuadIndices {0, 1, 2, 0, 3, 1}
{
Init();
}
RendererVulkan::~RendererVulkan()
{
vkDestroySemaphore(m_logicalDevice, m_renderFinishedSemaphore, nullptr);
vkDestroySemaphore(m_logicalDevice, m_imageAvailableSemaphore, nullptr);
vkDestroyBuffer(m_logicalDevice, m_vertexBuffer, nullptr);
vkFreeMemory(m_logicalDevice, m_vertexBufferMemory, nullptr);
vkDestroyBuffer(m_logicalDevice, m_indexBuffer, nullptr);
vkFreeMemory(m_logicalDevice, m_indexBufferMemory, nullptr);
vkDestroyBuffer(m_logicalDevice, m_imageUploadBuffer, nullptr);
vkFreeMemory(m_logicalDevice, m_imageUploadBufferMemory, nullptr);
vkDestroySampler(m_logicalDevice, m_textureSampler, nullptr);
vkDestroyImageView(m_logicalDevice, m_textureImageView, nullptr);
vkDestroyImage(m_logicalDevice, m_textureImage, nullptr);
vkFreeMemory(m_logicalDevice, m_textureImageMemory, nullptr);
vkDestroyCommandPool(m_logicalDevice, m_commandPool, nullptr);
for (auto framebuffer : m_swapChainFramebuffers)
{
vkDestroyFramebuffer(m_logicalDevice, framebuffer, nullptr);
}
vkDestroyPipeline(m_logicalDevice, m_graphicsPipeline, nullptr);
vkDestroyPipelineLayout(m_logicalDevice, m_pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(m_logicalDevice, m_descriptorSetLayout, nullptr);
vkDestroyDescriptorPool(m_logicalDevice, m_descriptorPool, nullptr);
vkDestroyRenderPass(m_logicalDevice, m_renderPass, nullptr);
for (auto imageView : m_swapChainImageViews)
{
vkDestroyImageView(m_logicalDevice, imageView, nullptr);
}
vkDestroySwapchainKHR(m_logicalDevice, m_swapChain, nullptr);
vkDestroyDevice(m_logicalDevice, nullptr);
#if VALIDATION_LAYERS
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(m_instance, "vkDestroyDebugUtilsMessengerEXT");
func(m_instance, m_debugMessenger, nullptr);
#endif
vkDestroySurfaceKHR(m_instance, m_surface, nullptr);
vkDestroyInstance(m_instance, nullptr);
m_backend.CleanupWindow();
}
void RendererVulkan::CreateInstance()
{
uint32_t instance_extension_count;
VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr));
std::vector<VkExtensionProperties> instance_extensions(instance_extension_count);
VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.data()));
std::vector<const char*> active_instance_extensions;
active_instance_extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
active_instance_extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#if VALIDATION_LAYERS
active_instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
if (!RendererVulkanInternal::ValidateExtensions(active_instance_extensions, instance_extensions))
{
throw std::runtime_error("Required instance extensions are missing.");
}
uint32_t instance_layer_count;
VK_CHECK(vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr));
std::vector<VkLayerProperties> supported_validation_layers(instance_layer_count);
VK_CHECK(vkEnumerateInstanceLayerProperties(&instance_layer_count, supported_validation_layers.data()));
VkApplicationInfo appInfo
{
VkStructureType::VK_STRUCTURE_TYPE_APPLICATION_INFO,
NULL,
"GameBoy",
VK_MAKE_VERSION(1,0,0),
"GameBoyEngine",
VK_MAKE_VERSION(1,0,0),
VK_API_VERSION_1_2
};
VkInstanceCreateInfo instanceInfo
{
VkStructureType::VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO
};
std::vector<const char*> validationLayers;
#if VALIDATION_LAYERS
validationLayers.push_back("VK_LAYER_KHRONOS_validation");
if (RendererVulkanInternal::ValidateLayers(validationLayers, supported_validation_layers))
{
LOG_INFO("Enabled Validation Layers:")
for (const auto& layer : validationLayers)
{
LOG_INFO(layer);
}
}
else
{
throw std::runtime_error("Required validation layers are missing.");
}
#endif
instanceInfo.pApplicationInfo = &appInfo;
instanceInfo.enabledExtensionCount = static_cast<uint32_t>(active_instance_extensions.size());
instanceInfo.ppEnabledExtensionNames = active_instance_extensions.data();
instanceInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
instanceInfo.ppEnabledLayerNames = validationLayers.data();
VK_CHECK(vkCreateInstance(&instanceInfo, nullptr, &m_instance));
}
void RendererVulkan::SelectPhysicalDevice()
{
uint32_t deviceCount = 0;
VK_CHECK(vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr));
if (deviceCount == 0) {
throw std::runtime_error("failed to find GPUs with Vulkan support!");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
VK_CHECK(vkEnumeratePhysicalDevices(m_instance, &deviceCount, devices.data()));
for (const auto& device : devices) {
if (RendererVulkanInternal::IsDeviceSupported(device, m_surface)) {
m_physicalDevice = device;
break;
}
}
if (m_physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU!");
}
}
void RendererVulkan::CreateLogicalDevice()
{
RendererVulkanInternal::QueueFamilyIndices indices;
RendererVulkanInternal::FindQueueFamilies(m_physicalDevice, m_surface, indices);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = { indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Graphics), indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Present) };
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies) {
VkDeviceQueueCreateInfo queueCreateInfo{ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures{};
VkDeviceCreateInfo createInfo{ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
VK_CHECK(vkCreateDevice(m_physicalDevice, &createInfo, nullptr, &m_logicalDevice));
vkGetDeviceQueue(m_logicalDevice, indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Graphics), 0, &m_graphicsQueue);
vkGetDeviceQueue(m_logicalDevice, indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Present), 0, &m_presentQueue);
}
void RendererVulkan::CreateSwapChain()
{
RendererVulkanInternal::SwapChainSupportDetails swapChainSupport = RendererVulkanInternal::QuerySwapChainSupport(m_physicalDevice, m_surface);
VkSurfaceFormatKHR surfaceFormat = RendererVulkanInternal::ChooseSwapSurfaceFormat(swapChainSupport.formats);
VkPresentModeKHR presentMode = RendererVulkanInternal::ChooseSwapPresentMode(swapChainSupport.presentModes);
VkExtent2D extent = RendererVulkanInternal::ChooseSwapExtent(swapChainSupport.capabilities, m_scaledWidth, m_scaledHeight);
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR createInfo{ VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
createInfo.surface = m_surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
RendererVulkanInternal::QueueFamilyIndices indices;
RendererVulkanInternal::FindQueueFamilies(m_physicalDevice, m_surface, indices);
uint32_t queueFamilyIndices[] = { indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Graphics), indices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Present) };
if (queueFamilyIndices[0] != queueFamilyIndices[1]) {
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0; // Optional
createInfo.pQueueFamilyIndices = nullptr; // Optional
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = VK_NULL_HANDLE;
VK_CHECK(vkCreateSwapchainKHR(m_logicalDevice, &createInfo, nullptr, &m_swapChain));
vkGetSwapchainImagesKHR(m_logicalDevice, m_swapChain, &imageCount, nullptr);
m_swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(m_logicalDevice, m_swapChain, &imageCount, m_swapChainImages.data());
m_swapChainImageFormat = surfaceFormat.format;
}
void RendererVulkan::CreateImageViews()
{
m_swapChainImageViews.resize(m_swapChainImages.size());
for (size_t i = 0; i < m_swapChainImages.size(); i++)
{
VkImageViewCreateInfo createInfo { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
createInfo.image = m_swapChainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = m_swapChainImageFormat;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
VK_CHECK(vkCreateImageView(m_logicalDevice, &createInfo, nullptr, &m_swapChainImageViews[i]));
}
}
void RendererVulkan::CreateRenderPass()
{
VkAttachmentDescription colorAttachment{};
colorAttachment.format = m_swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo renderPassInfo { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
VK_CHECK(vkCreateRenderPass(m_logicalDevice, &renderPassInfo, nullptr, &m_renderPass));
}
void RendererVulkan::CreateGraphicsPipeline()
{
ShaderCompiler::CombinedShaderBinary shaders = ShaderCompiler::GetCompiledShaders(m_mainShaderName);
VkShaderModule vertShaderModule = RendererVulkanInternal::CreateShaderModule(m_logicalDevice, shaders.m_vs);
VkShaderModule fragShaderModule = RendererVulkanInternal::CreateShaderModule(m_logicalDevice, shaders.m_fs);
VkPipelineShaderStageCreateInfo vertShaderStageInfo { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragShaderStageInfo { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
VkPipelineVertexInputStateCreateInfo vertexInputInfo { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
VkVertexInputBindingDescription bindingDescription = RendererVulkanInternal::GetVertexBindingDescription();
auto attributeDescriptions = RendererVulkanInternal::GetVertexAttributeDescriptions();
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)m_scaledWidth;
viewport.height = (float)m_scaledHeight;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = VkExtent2D{ m_scaledWidth, m_scaledHeight };
VkPipelineViewportStateCreateInfo viewportState { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo colorBlending { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
VkPipelineLayoutCreateInfo pipelineLayoutInfo { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &m_descriptorSetLayout;
VK_CHECK(vkCreatePipelineLayout(m_logicalDevice, &pipelineLayoutInfo, nullptr, &m_pipelineLayout));
VkGraphicsPipelineCreateInfo pipelineInfo{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = nullptr;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = nullptr;
pipelineInfo.layout = m_pipelineLayout;
pipelineInfo.renderPass = m_renderPass;
pipelineInfo.subpass = 0;
VK_CHECK(vkCreateGraphicsPipelines(m_logicalDevice, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &m_graphicsPipeline));
vkDestroyShaderModule(m_logicalDevice, fragShaderModule, nullptr);
vkDestroyShaderModule(m_logicalDevice, vertShaderModule, nullptr);
}
void RendererVulkan::CreateFramebuffers()
{
m_swapChainFramebuffers.resize(m_swapChainImageViews.size());
for (size_t i = 0; i < m_swapChainImageViews.size(); i++)
{
VkImageView attachments[] =
{
m_swapChainImageViews[i]
};
VkFramebufferCreateInfo framebufferInfo { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
framebufferInfo.renderPass = m_renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachments;
framebufferInfo.width = m_scaledWidth;
framebufferInfo.height = m_scaledHeight;
framebufferInfo.layers = 1;
VK_CHECK(vkCreateFramebuffer(m_logicalDevice, &framebufferInfo, nullptr, &m_swapChainFramebuffers[i]));
}
}
void RendererVulkan::CreateCommandPool()
{
RendererVulkanInternal::QueueFamilyIndices queueFamilyIndices;
RendererVulkanInternal::FindQueueFamilies(m_physicalDevice, m_surface, queueFamilyIndices);
VkCommandPoolCreateInfo poolInfo{ VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
poolInfo.queueFamilyIndex = queueFamilyIndices.GetFamilyIndex(RendererVulkanInternal::QueueFamilyIndices::QueueTypes::Graphics);
VK_CHECK(vkCreateCommandPool(m_logicalDevice, &poolInfo, nullptr, &m_commandPool));
}
void RendererVulkan::CreateCommandBuffers()
{
m_commandBuffers.resize(m_swapChainFramebuffers.size());
VkCommandBufferAllocateInfo allocInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
allocInfo.commandPool = m_commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = (uint32_t)m_commandBuffers.size();
VK_CHECK(vkAllocateCommandBuffers(m_logicalDevice, &allocInfo, m_commandBuffers.data()));
for (size_t i = 0; i < m_commandBuffers.size(); i++)
{
VkCommandBufferBeginInfo beginInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
VK_CHECK(vkBeginCommandBuffer(m_commandBuffers[i], &beginInfo));
RendererVulkanInternal::TransitionImageLayout(m_commandBuffers[i], m_textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
RendererVulkanInternal::CopyBufferToImage(m_commandBuffers[i], m_imageUploadBuffer, m_textureImage, m_sourceWidth, m_sourceHeight);
RendererVulkanInternal::TransitionImageLayout(m_commandBuffers[i], m_textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
VkRenderPassBeginInfo renderPassInfo{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
renderPassInfo.renderPass = m_renderPass;
renderPassInfo.framebuffer = m_swapChainFramebuffers[i];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = VkExtent2D{ m_scaledWidth, m_scaledHeight };
VkClearValue clearColor = { {{0.0f, 0.0f, 0.0f, 1.0f}} };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(m_commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_graphicsPipeline);
VkBuffer vertexBuffers[] = { m_vertexBuffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(m_commandBuffers[i], m_indexBuffer, 0, VK_INDEX_TYPE_UINT16);
vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1, &m_descriptorSets[i], 0, nullptr);
vkCmdDrawIndexed(m_commandBuffers[i], static_cast<uint32_t>(6), 1, 0, 0, 0);
vkCmdEndRenderPass(m_commandBuffers[i]);
VK_CHECK(vkEndCommandBuffer(m_commandBuffers[i]));
}
}
void RendererVulkan::CreateSemaphores()
{
VkSemaphoreCreateInfo semaphoreInfo { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
VK_CHECK(vkCreateSemaphore(m_logicalDevice, &semaphoreInfo, nullptr, &m_imageAvailableSemaphore));
VK_CHECK(vkCreateSemaphore(m_logicalDevice, &semaphoreInfo, nullptr, &m_renderFinishedSemaphore));
}
void RendererVulkan::CreateDescriptorPool()
{
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSize.descriptorCount = static_cast<uint32_t>(m_swapChainImages.size());
VkDescriptorPoolCreateInfo poolInfo { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = static_cast<uint32_t>(m_swapChainImages.size());
VK_CHECK(vkCreateDescriptorPool(m_logicalDevice, &poolInfo, nullptr, &m_descriptorPool));
}
void RendererVulkan::CreateDescriptorSets()
{
std::vector<VkDescriptorSetLayout> layouts(m_swapChainImages.size(), m_descriptorSetLayout);
VkDescriptorSetAllocateInfo allocInfo { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = m_descriptorPool;
allocInfo.descriptorSetCount = static_cast<uint32_t>(m_swapChainImages.size());
allocInfo.pSetLayouts = layouts.data();
m_descriptorSets.resize(m_swapChainImages.size());
VK_CHECK(vkAllocateDescriptorSets(m_logicalDevice, &allocInfo, m_descriptorSets.data()));
for (size_t i = 0; i < m_swapChainImages.size(); i++)
{
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = m_textureImageView;
imageInfo.sampler = m_textureSampler;
VkWriteDescriptorSet descriptorWrite { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
descriptorWrite.dstSet = m_descriptorSets[i];
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(m_logicalDevice, 1, &descriptorWrite, 0, nullptr);
}
}
void RendererVulkan::CreateVertexBuffer()
{
uint32_t size = sizeof(Vertex) * 4;
RendererVulkanInternal::CreateBuffer(m_logicalDevice, m_physicalDevice, size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, m_vertexBuffer, m_vertexBufferMemory);
void* data;
vkMapMemory(m_logicalDevice, m_vertexBufferMemory, 0, size, 0, &data);
memcpy(data, m_fullscreenQuadVertices, (size_t)size);
vkUnmapMemory(m_logicalDevice, m_vertexBufferMemory);
}
void RendererVulkan::CreateTextureImage()
{
VkDeviceSize imageSize = m_sourceWidth * m_sourceHeight * 4;
RendererVulkanInternal::CreateBuffer(m_logicalDevice, m_physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, m_imageUploadBuffer, m_imageUploadBufferMemory);
void* data;
vkMapMemory(m_logicalDevice, m_imageUploadBufferMemory, 0, imageSize, 0, &data);
memset(data, 1, static_cast<size_t>(imageSize));
vkUnmapMemory(m_logicalDevice, m_imageUploadBufferMemory);
VkImageCreateInfo imageInfo { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = static_cast<uint32_t>(m_sourceWidth);
imageInfo.extent.height = static_cast<uint32_t>(m_sourceHeight);
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
VK_CHECK(vkCreateImage(m_logicalDevice, &imageInfo, nullptr, &m_textureImage));
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(m_logicalDevice, m_textureImage, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = RendererVulkanInternal::FindMemoryType(m_physicalDevice, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
vkAllocateMemory(m_logicalDevice, &allocInfo, nullptr, &m_textureImageMemory);
vkBindImageMemory(m_logicalDevice, m_textureImage, m_textureImageMemory, 0);
VkCommandBuffer cb1 = BeginRecording();
RendererVulkanInternal::TransitionImageLayout(cb1, m_textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
EndRecording(cb1);
VkCommandBuffer cb2 = BeginRecording();
RendererVulkanInternal::CopyBufferToImage(cb2, m_imageUploadBuffer, m_textureImage, m_sourceWidth, m_sourceHeight);
EndRecording(cb2);
VkCommandBuffer cb3 = BeginRecording();
RendererVulkanInternal::TransitionImageLayout(cb3, m_textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
EndRecording(cb3);
}
void RendererVulkan::CreateTextureSampler()
{
VkSamplerCreateInfo samplerInfo { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0f;
VK_CHECK(vkCreateSampler(m_logicalDevice, &samplerInfo, nullptr, &m_textureSampler));
}
void RendererVulkan::CreateDescriptorSetLayout()
{
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.pImmutableSamplers = nullptr;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutCreateInfo layoutInfo { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VK_CHECK(vkCreateDescriptorSetLayout(m_logicalDevice, &layoutInfo, nullptr, &m_descriptorSetLayout));
}
void RendererVulkan::CreateTextureImageView()
{
VkImageViewCreateInfo viewInfo { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
viewInfo.image = m_textureImage;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = 1;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VK_CHECK(vkCreateImageView(m_logicalDevice, &viewInfo, nullptr, &m_textureImageView));
}
VkCommandBuffer RendererVulkan::BeginRecording()
{
VkCommandBufferAllocateInfo allocInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = m_commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(m_logicalDevice, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void RendererVulkan::EndRecording(VkCommandBuffer buffer)
{
vkEndCommandBuffer(buffer);
VkSubmitInfo submitInfo { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &buffer;
vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(m_graphicsQueue);
vkFreeCommandBuffers(m_logicalDevice, m_commandPool, 1, &buffer);
}
void RendererVulkan::CreateIndexBuffer()
{
uint32_t size = sizeof(uint16_t) * 6;
RendererVulkanInternal::CreateBuffer(m_logicalDevice, m_physicalDevice, size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, m_indexBuffer, m_indexBufferMemory);
void* data;
vkMapMemory(m_logicalDevice, m_indexBufferMemory, 0, size, 0, &data);
memcpy(data, m_fullscreenQuadIndices, (size_t) size);
vkUnmapMemory(m_logicalDevice, m_indexBufferMemory);
}
void RendererVulkan::Init()
{
m_backend.InitWindow(m_scaledWidth, m_scaledHeight);
CreateInstance();
#if VALIDATION_LAYERS
RendererVulkanInternal::InitValidationCallback(m_instance, m_debugMessenger);
#endif
m_backend.CreateSurface(m_instance, m_surface);
SelectPhysicalDevice();
CreateLogicalDevice();
CreateSwapChain();
CreateImageViews();
CreateRenderPass();
CreateDescriptorSetLayout();
CreateGraphicsPipeline();
CreateFramebuffers();
CreateCommandPool();
CreateVertexBuffer();
CreateIndexBuffer();
CreateTextureImage();
CreateTextureImageView();
CreateTextureSampler();
CreateDescriptorPool();
CreateDescriptorSets();
CreateCommandBuffers();
CreateSemaphores();
}
void RendererVulkan::Draw(const void* renderedImage)
{
uint32_t imageIndex;
vkAcquireNextImageKHR(m_logicalDevice, m_swapChain, UINT64_MAX, m_imageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
uint32_t imageSize = m_sourceWidth * m_sourceHeight * 4;
void* data;
vkMapMemory(m_logicalDevice, m_imageUploadBufferMemory, 0, imageSize, 0, &data);
memcpy(data, renderedImage, imageSize);
vkUnmapMemory(m_logicalDevice, m_imageUploadBufferMemory);
VkSubmitInfo submitInfo{ VK_STRUCTURE_TYPE_SUBMIT_INFO };
VkSemaphore waitSemaphores[] = { m_imageAvailableSemaphore };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_commandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { m_renderFinishedSemaphore };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
VK_CHECK(vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE));
VkPresentInfoKHR presentInfo{ VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { m_swapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(m_presentQueue, &presentInfo);
vkQueueWaitIdle(m_presentQueue);
}
void RendererVulkan::WaitForIdle()
{
vkDeviceWaitIdle(m_logicalDevice);
}
bool RendererVulkan::RequestExit()
{
return m_backend.RequestQuit();
}
| 36.612328 | 242 | 0.805263 | [
"vector"
] |
60f44998f1caa79941a6ce59cfd710abce340540 | 5,529 | cpp | C++ | interfaces/light/1.0/default/Light.cpp | LineageOS/android_device_shift_axolotl | 245360fcc132914ea987389f6df7f5c78c7aff6c | [
"Apache-2.0"
] | 2 | 2021-09-14T07:19:45.000Z | 2021-12-27T13:34:03.000Z | interfaces/light/1.0/default/Light.cpp | LineageOS/android_device_shift_axolotl | 245360fcc132914ea987389f6df7f5c78c7aff6c | [
"Apache-2.0"
] | null | null | null | interfaces/light/1.0/default/Light.cpp | LineageOS/android_device_shift_axolotl | 245360fcc132914ea987389f6df7f5c78c7aff6c | [
"Apache-2.0"
] | 1 | 2022-03-10T11:20:11.000Z | 2022-03-10T11:20:11.000Z | /*
* Copyright (C) 2020 SHIFT GmbH
*
* 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.
*/
#define LOG_TAG "SHIFT-Light"
#include "Light.h"
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <fstream>
namespace android {
namespace hardware {
namespace light {
namespace V2_0 {
namespace implementation {
/*
* Write value to path and close file.
*/
template <typename T>
static void set(const std::string& path, const T& value) {
std::ofstream file(path);
file << value;
}
template <typename T>
static T get(const std::string& path, const T& def) {
std::ifstream file(path);
T result;
file >> result;
return file.fail() ? def : result;
}
Light::Light() {
mLights.emplace(Type::ATTENTION, std::bind(&Light::handleRgb, this, std::placeholders::_1, 0));
mLights.emplace(Type::BATTERY, std::bind(&Light::handleRgb, this, std::placeholders::_1, 2));
mLights.emplace(Type::NOTIFICATIONS, std::bind(&Light::handleRgb, this, std::placeholders::_1, 1));
}
void Light::handleRgb(const LightState& state, size_t index) {
mLightStates.at(index) = state;
LightState stateToUse = mLightStates.front();
for (const auto& lightState : mLightStates) {
if (lightState.color & 0xffffff) {
stateToUse = lightState;
break;
}
}
std::map<std::string, int> colorValues;
colorValues["red"] = (stateToUse.color >> 16) & 0xff;
// lower green and blue brightness to adjust for the (lower) brightness of red
colorValues["green"] = ((stateToUse.color >> 8) & 0xff) / 2;
colorValues["blue"] = (stateToUse.color & 0xff) / 2;
int onMs = stateToUse.flashMode == Flash::TIMED ? stateToUse.flashOnMs : 0;
int offMs = stateToUse.flashMode == Flash::TIMED ? stateToUse.flashOffMs : 0;
// LUT has 63 entries, we could theoretically use them as 3 (colors) * 21 (steps).
// However, the last LUT entries don't seem to behave correctly for unknown
// reasons, so we use 17 steps for a total of 51 LUT entries only.
static constexpr int kRampSteps = 16;
static constexpr int kRampMaxStepDurationMs = 15;
auto makeLedPath = [](const std::string& led, const std::string& op) -> std::string {
return "/sys/class/leds/" + led + "/" + op;
};
auto getScaledDutyPercent = [](int brightness) -> std::string {
std::string output;
for (int i = 0; i <= kRampSteps; i++) {
if (i != 0) {
output += ",";
}
output += std::to_string(i * 512 * brightness / (255 * kRampSteps));
}
return output;
};
// Disable all blinking before starting
for (const auto& entry : colorValues) {
set(makeLedPath(entry.first, "blink"), 0);
}
if (onMs > 0 && offMs > 0) {
int pauseLo, pauseHi, stepDuration, index = 0;
if (kRampMaxStepDurationMs * kRampSteps > onMs) {
stepDuration = onMs / kRampSteps;
pauseHi = 0;
pauseLo = offMs;
} else {
stepDuration = kRampMaxStepDurationMs;
pauseHi = onMs - kRampSteps * stepDuration;
pauseLo = offMs - kRampSteps * stepDuration;
}
for (const auto& entry : colorValues) {
set(makeLedPath(entry.first, "lut_flags"), 95);
set(makeLedPath(entry.first, "start_idx"), index);
set(makeLedPath(entry.first, "duty_pcts"), getScaledDutyPercent(entry.second));
set(makeLedPath(entry.first, "pause_lo"), pauseLo);
set(makeLedPath(entry.first, "pause_hi"), pauseHi);
set(makeLedPath(entry.first, "ramp_step_ms"), stepDuration);
index += kRampSteps + 1;
}
// Start blinking
for (const auto& entry : colorValues) {
set(makeLedPath(entry.first, "blink"), entry.second);
}
} else {
for (const auto& entry : colorValues) {
set(makeLedPath(entry.first, "brightness"), entry.second);
}
}
LOG(DEBUG) << base::StringPrintf(
"handleRgb: mode=%d, color=%08X, onMs=%d, offMs=%d",
static_cast<std::underlying_type<Flash>::type>(stateToUse.flashMode), stateToUse.color,
onMs, offMs);
}
// Methods from ::android::hardware::light::V2_0::ILight follow.
Return<Status> Light::setLight(Type type, const LightState& state) {
auto it = mLights.find(type);
if (it == mLights.end()) {
return Status::LIGHT_NOT_SUPPORTED;
}
/*
* Lock global mutex until light state is updated.
*/
std::lock_guard<std::mutex> lock(mLock);
it->second(state);
return Status::SUCCESS;
}
Return<void> Light::getSupportedTypes(getSupportedTypes_cb _hidl_cb) {
std::vector<Type> types;
for (auto const& light : mLights) {
types.push_back(light.first);
}
_hidl_cb(types);
return Void();
}
} // namespace implementation
} // namespace V2_0
} // namespace light
} // namespace hardware
} // namespace android
| 32.145349 | 103 | 0.629047 | [
"vector"
] |
60f895c0a2a53bf924cea69db0cc9b4337e83914 | 6,838 | cpp | C++ | Source/TrackViz/Private/TrackVizBPLibrary.cpp | BrainsGarden/TrackViz | c63c1f041fc4ee124d1e7113772dc3a2e52d7ea6 | [
"MIT"
] | 13 | 2018-12-04T10:40:56.000Z | 2020-07-05T15:48:12.000Z | Source/TrackViz/Private/TrackVizBPLibrary.cpp | BrainsGarden/TrackViz | c63c1f041fc4ee124d1e7113772dc3a2e52d7ea6 | [
"MIT"
] | null | null | null | Source/TrackViz/Private/TrackVizBPLibrary.cpp | BrainsGarden/TrackViz | c63c1f041fc4ee124d1e7113772dc3a2e52d7ea6 | [
"MIT"
] | 3 | 2020-03-07T12:53:49.000Z | 2020-07-05T15:48:32.000Z | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "TrackVizBPLibrary.h"
#include "TrackViz.h"
#include "Core.h"
#include "Engine/GameEngine.h"
#include "Engine/World.h"
#include "DrawDebugHelpers.h"
#include "Core/Public/HAL/FileManagerGeneric.h"
void UTrackVizBPLibrary::DrawLine(UObject* WorldContextObject, FVector from, FVector to, FColor color, bool removable, float thickness)
{
DrawDebugLine(GEngine->GetWorldFromContextObjectChecked(WorldContextObject), from, to, color, removable, 999999, 0, thickness);
}
void UTrackVizBPLibrary::DrawArrow(UObject* WorldContextObject, FVector position, FRotator rotator, FColor color, bool removable, float thickness)
{
DrawDebugDirectionalArrow(
GEngine->GetWorldFromContextObjectChecked(WorldContextObject),
position,
position + rotator.Vector() * 10,
0,
color,
removable,
999999,
0,
thickness
);
}
FTrackRecord UTrackVizBPLibrary::ReadTrackRecordFromFile(const FString& path)
{
const TCHAR* delim = TEXT(",");
TArray<FString> lines;
FFileHelper::LoadFileToStringArray(lines, *path);
FString headerLine = lines[0];
lines.RemoveAt(0, 1, false);
struct {
int PosXIndex = -1;
int PosYIndex = -1;
int PosZIndex = -1;
int QuatXIndex = -1;
int QuatYIndex = -1;
int QuatZIndex = -1;
int QuatWIndex = -1;
} csvInfo;
TArray<FString> headers = ParseLineIntoArray(headerLine);
for (uint16 i = 0; i < headers.Num(); ++i) {
FString header = headers[i];
if (header.Equals(TEXT("POS_X"))) {
csvInfo.PosXIndex = i;
}
if (header.Equals(TEXT("POS_Y"))) {
csvInfo.PosYIndex = i;
}
if (header.Equals(TEXT("POS_Z"))) {
csvInfo.PosZIndex = i;
}
if (header.Equals(TEXT("Q_X"))) {
csvInfo.QuatXIndex = i;
}
if (header.Equals(TEXT("Q_Y"))) {
csvInfo.QuatYIndex = i;
}
if (header.Equals(TEXT("Q_Z"))) {
csvInfo.QuatZIndex = i;
}
if (header.Equals(TEXT("Q_W"))) {
csvInfo.QuatWIndex = i;
}
}
if (csvInfo.PosXIndex == -1 || csvInfo.PosYIndex == -1 || csvInfo.PosZIndex == -1) {
GEngine->AddOnScreenDebugMessage(-1, 999999, FColor::Red, TEXT("Parsing CSV file failed -- headers not found"));
return {TArray<FVector>(), TArray<FRotator>(), false, TEXT("")};
}
bool RotatorsKnown = csvInfo.QuatXIndex != -1 && csvInfo.QuatYIndex != -1 && csvInfo.QuatZIndex != -1 && csvInfo.QuatWIndex != -1;
TArray<FVector> positions;
TArray<FRotator> rotators;
positions.Reserve(lines.Num());
if (RotatorsKnown) {
rotators.Reserve(lines.Num());
}
for (FString line : lines) {
TArray<FString> fields = ParseLineIntoArray(line);
FVector position(
FCString::Atof(*fields[csvInfo.PosXIndex]) * 100,
FCString::Atof(*fields[csvInfo.PosYIndex]) * 100,
FCString::Atof(*fields[csvInfo.PosZIndex]) * 100
);
positions.Add(position);
if (RotatorsKnown) {
FQuat Quat(
FCString::Atof(*fields[csvInfo.QuatXIndex]),
FCString::Atof(*fields[csvInfo.QuatYIndex]),
FCString::Atof(*fields[csvInfo.QuatZIndex]),
FCString::Atof(*fields[csvInfo.QuatWIndex])
);
rotators.Add(Quat.Rotator());
}
}
return {positions, rotators, RotatorsKnown, FPaths::GetBaseFilename(path)};
}
void UTrackVizBPLibrary::DrawTrackRecord(
UObject* WorldContextObject,
const FTrackRecord& trackRecord,
FVector startPosition,
FColor color,
float thickness
) {
FVector currentPosition(startPosition + trackRecord.Positions[0]);
for (int i = 1; i < trackRecord.Positions.Num(); ++i) {
auto position = trackRecord.Positions[i];
FVector newPosition = startPosition + position;
DrawLine(WorldContextObject, currentPosition, newPosition, color, false, thickness);
currentPosition = newPosition;
}
}
TArray<FTrackRecord> UTrackVizBPLibrary::ReadTrackRecordsFromDir(const FString& path)
{
IFileManager& fileManager = IFileManager::Get();
TArray<FString> fileNames;
fileManager.FindFiles(fileNames, *path, TEXT("txt"));
TArray<FTrackRecord> trackRecords;
trackRecords.Reserve(fileNames.Num());
for (const FString& fileName : fileNames) {
FString fullFileName = FPaths::ConvertRelativePathToFull(path, fileName);
trackRecords.Add(ReadTrackRecordFromFile(fullFileName));
}
return trackRecords;
}
TArray<FColor> UTrackVizBPLibrary::GetColorsForTrackRecords(const TArray<FTrackRecord>& trackRecords)
{
static const TMap<FString, FColor> colorMap({
{"black", FColor::Black},
{"blue", FColor::Blue},
{"cyan", FColor::Cyan},
{"emerald", FColor::Emerald},
{"green", FColor::Green},
{"magenta", FColor::Magenta},
{"orange", FColor::Orange},
{"purple", FColor::Purple},
{"red", FColor::Red},
{"silver", FColor::Silver},
{"turquoise", FColor::Turquoise},
{"white", FColor::White},
{"yellow", FColor::Yellow},
});
TArray<TPair<FString, bool>> colorUsed({
TPair<FString, bool>("red", false),
TPair<FString, bool>("green", false),
TPair<FString, bool>("blue", false),
TPair<FString, bool>("cyan", false),
TPair<FString, bool>("magenta", false),
TPair<FString, bool>("yellow", false),
TPair<FString, bool>("black", false),
TPair<FString, bool>("white", false),
TPair<FString, bool>("emerald", false),
TPair<FString, bool>("orange", false),
TPair<FString, bool>("purple", false),
TPair<FString, bool>("turquoise", false),
});
FColor defaultColor = FColor::Silver;
TArray<FColor> colors;
colors.Reserve(trackRecords.Num());
for (int32 i = 0; i < trackRecords.Num(); ++i) {
colors.Add(defaultColor);
}
uint8 usedColorCount = 0;
for (int32 i = 0; i < trackRecords.Num(); ++i) {
const FTrackRecord& trackRecord = trackRecords[i];
for (TPair<FString, bool>& entry : colorUsed) {
const FString& colorStr = entry.Key;
const FString& fileName = trackRecord.FileName.ToLower();
if (fileName.StartsWith(colorStr) || fileName.EndsWith(colorStr))
{
entry.Value = true;
colors[i] = *colorMap.Find(colorStr);
usedColorCount += 1;
break;
}
}
}
int8 colorIndex = 0;
for (int32 i = 0; i < trackRecords.Num(); ++i) {
if (colors[i] != defaultColor || usedColorCount == colorUsed.Num()) {
continue;
}
while (colorUsed[colorIndex].Value) {
++colorIndex;
if (colorIndex >= colorUsed.Num()) {
colorIndex = 0;
}
}
colors[i] = *colorMap.Find(colorUsed[colorIndex].Key);
++colorIndex;
if (colorIndex >= colorUsed.Num()) {
colorIndex = 0;
}
}
return colors;
}
TArray<FString> UTrackVizBPLibrary::ParseLineIntoArray(const FString& Line)
{
static const FRegexPattern DELIM_REGEX(TEXT("(,\t)|(,)|(\t)"));
FRegexMatcher Matcher(DELIM_REGEX, Line);
TArray<FString> result;
int32 prev = 0;
while (Matcher.FindNext()) {
result.Add(Line.Mid(prev, Matcher.GetMatchBeginning() - prev));
prev = Matcher.GetMatchEnding();
}
result.Add(Line.Mid(prev, Line.Len() - prev));
for (const auto& s : result) {
UE_LOG(LogTemp, Log, TEXT("%s"), *s);
}
return result;
}
| 28.256198 | 146 | 0.690845 | [
"vector"
] |
60fa065dd71759b2793196e996c8a7b01e02fde0 | 3,214 | hpp | C++ | thirdparty/LAStools/LASlib/inc/lasreaderbuffered.hpp | Wkkkkk/protype | 3b0d77d545c177b86b8812be1a6e5392a6f7e367 | [
"BSL-1.0"
] | 184 | 2015-01-12T10:40:50.000Z | 2022-03-23T20:27:15.000Z | thirdparty/LAStools/LASlib/inc/lasreaderbuffered.hpp | Wkkkkk/protype | 3b0d77d545c177b86b8812be1a6e5392a6f7e367 | [
"BSL-1.0"
] | 154 | 2015-01-14T13:16:39.000Z | 2022-01-11T16:53:42.000Z | thirdparty/LAStools/LASlib/inc/lasreaderbuffered.hpp | Wkkkkk/protype | 3b0d77d545c177b86b8812be1a6e5392a6f7e367 | [
"BSL-1.0"
] | 87 | 2015-01-12T04:36:55.000Z | 2022-03-16T06:54:28.000Z | /*
===============================================================================
FILE: lasreaderbuffered.hpp
CONTENTS:
Reads LIDAR points from the LAS format and add those points from provided
neighboring files that fall within the bounding box of this file extended
by the user-specified buffer.
First the buffer points are read from all the neighboring files so that
the header can be properly populated. By default they are stored in main
memory so they do not have to be read twice from disk.
PROGRAMMERS:
martin.isenburg@rapidlasso.com - http://rapidlasso.com
COPYRIGHT:
(c) 2007-2012, martin isenburg, rapidlasso - fast tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the LICENSE.txt file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
17 July 2012 -- created after converting the LASzip paper from LaTeX to Word
===============================================================================
*/
#ifndef LAS_READER_BUFFERED_HPP
#define LAS_READER_BUFFERED_HPP
#include "lasreader.hpp"
class LASreaderBuffered : public LASreader
{
public:
void set_scale_factor(const F64* scale_factor);
void set_offset(const F64* offset);
void set_translate_intensity(F32 translate_intensity);
void set_scale_intensity(F32 scale_intensity);
void set_translate_scan_angle(F32 translate_scan_angle);
void set_scale_scan_angle(F32 scale_scan_angle);
void set_parse_string(const CHAR* parse_string);
void set_skip_lines(I32 skip_lines);
void set_populate_header(BOOL populate_header);
BOOL set_file_name(const CHAR* file_name);
BOOL add_neighbor_file_name(const CHAR* file_name);
void set_buffer_size(const F32 buffer_size);
BOOL remove_buffer();
BOOL open();
BOOL reopen();
void set_filter(LASfilter* filter);
void set_transform(LAStransform* transform);
BOOL inside_tile(const F32 ll_x, const F32 ll_y, const F32 size);
BOOL inside_circle(const F64 center_x, const F64 center_y, const F64 radius);
BOOL inside_rectangle(const F64 min_x, const F64 min_y, const F64 max_x, const F64 max_y);
I32 get_format() const;
BOOL seek(const I64 p_index){ return FALSE; };
ByteStreamIn* get_stream() const { return 0; };
void close(BOOL close_stream=TRUE);
LASreaderBuffered();
~LASreaderBuffered();
protected:
BOOL read_point_default();
private:
void clean();
void clean_buffer();
BOOL copy_point_to_buffer();
BOOL copy_point_from_buffer();
U32 get_number_buffered_points() const;
const U32 points_per_buffer;
U8** buffers;
U8* current_buffer;
U32 size_of_buffers_array;
U32 number_of_buffers;
U32 buffered_points;
U32 point_count;
LASreadOpener lasreadopener;
LASreadOpener lasreadopener_neighbors;
LASreader* lasreader;
F32 buffer_size;
BOOL point_type_change;
BOOL point_size_change;
BOOL rescale;
BOOL reoffset;
F64* scale_factor;
F64* offset;
};
#endif
| 28.192982 | 92 | 0.722464 | [
"transform"
] |
8800fdb25dec8ce68febef1545f598100c478efc | 8,236 | cpp | C++ | vkconfig_core/parameter.cpp | val-verde/lunarg-vulkan-tools | 25a5b6544449281e90e39a6368730f809eef747a | [
"Apache-2.0"
] | null | null | null | vkconfig_core/parameter.cpp | val-verde/lunarg-vulkan-tools | 25a5b6544449281e90e39a6368730f809eef747a | [
"Apache-2.0"
] | null | null | null | vkconfig_core/parameter.cpp | val-verde/lunarg-vulkan-tools | 25a5b6544449281e90e39a6368730f809eef747a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020-2021 Valve Corporation
* Copyright (c) 2020-2021 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "setting_filesystem.h"
#include "parameter.h"
#include "platform.h"
#include "version.h"
#include "util.h"
#include "path.h"
#include <QJsonArray>
#include <cassert>
#include <algorithm>
static const char* VK_LAYER_KHRONOS_PROFILES_NAME = "VK_LAYER_KHRONOS_profiles";
static const char* VK_LAYER_KHRONOS_VALIDATION_NAME = "VK_LAYER_KHRONOS_validation";
bool Parameter::ApplyPresetSettings(const LayerPreset& preset) {
for (std::size_t preset_index = 0, preset_count = preset.settings.size(); preset_index < preset_count; ++preset_index) {
const SettingData* preset_setting = preset.settings[preset_index];
for (std::size_t i = 0, n = this->settings.size(); i < n; ++i) {
SettingData* current_setting = this->settings[i];
if (current_setting->key != preset_setting->key) continue;
if (current_setting->type != preset_setting->type) continue;
this->settings[i]->Copy(preset_setting);
}
}
return true;
}
ParameterRank GetParameterOrdering(const std::vector<Layer>& available_layers, const Parameter& parameter) {
assert(!parameter.key.empty());
const Layer* layer = FindByKey(available_layers, parameter.key.c_str());
if (layer == nullptr) {
return PARAMETER_RANK_MISSING;
} else if (parameter.state == LAYER_STATE_EXCLUDED) {
return PARAMETER_RANK_EXCLUDED;
} else if (parameter.state == LAYER_STATE_APPLICATION_CONTROLLED && layer->type == LAYER_TYPE_IMPLICIT) {
return PARAMETER_RANK_IMPLICIT_AVAILABLE;
} else if (parameter.state == LAYER_STATE_OVERRIDDEN && layer->type == LAYER_TYPE_IMPLICIT) {
return PARAMETER_RANK_IMPLICIT_OVERRIDDEN;
} else if (parameter.state == LAYER_STATE_OVERRIDDEN && layer->type != LAYER_TYPE_IMPLICIT) {
return PARAMETER_RANK_EXPLICIT_OVERRIDDEN;
} else if (parameter.state == LAYER_STATE_APPLICATION_CONTROLLED && layer->type != LAYER_TYPE_IMPLICIT) {
return PARAMETER_RANK_EXPLICIT_AVAILABLE;
} else {
assert(0); // Unknown ordering
return PARAMETER_RANK_MISSING;
}
}
Version ComputeMinApiVersion(const Version api_version, const std::vector<Parameter>& parameters,
const std::vector<Layer>& layers) {
if (parameters.empty()) return Version::VERSION_NULL;
Version min_version = api_version;
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
const Layer* layer = FindByKey(layers, parameters[i].key.c_str());
if (layer == nullptr) continue;
if (parameters[i].state && PARAMETER_RANK_EXCLUDED) continue;
if (parameters[i].state && PARAMETER_RANK_MISSING) continue;
min_version = min_version < layer->api_version ? min_version : layer->api_version;
}
return min_version;
}
void OrderParameter(std::vector<Parameter>& parameters, const std::vector<Layer>& layers) {
struct ParameterCompare {
ParameterCompare(const std::vector<Layer>& layers) : layers(layers) {}
bool operator()(const Parameter& a, const Parameter& b) const {
const ParameterRank rankA = GetParameterOrdering(layers, a);
const ParameterRank rankB = GetParameterOrdering(layers, b);
if (rankA == rankB && a.state == LAYER_STATE_OVERRIDDEN) {
if (a.overridden_rank != Parameter::NO_RANK && b.overridden_rank != Parameter::NO_RANK)
return a.overridden_rank < b.overridden_rank;
else if (a.key == VK_LAYER_KHRONOS_PROFILES_NAME)
return false;
else if (b.key == VK_LAYER_KHRONOS_PROFILES_NAME)
return true;
else if (a.key == VK_LAYER_KHRONOS_VALIDATION_NAME && b.key == VK_LAYER_KHRONOS_PROFILES_NAME)
return true;
else if (a.key == VK_LAYER_KHRONOS_VALIDATION_NAME)
return false;
else
return a.key < b.key;
} else if (rankA == rankB && a.state != LAYER_STATE_OVERRIDDEN)
return a.key < b.key;
else
return rankA < rankB;
}
const std::vector<Layer>& layers;
};
std::sort(parameters.begin(), parameters.end(), ParameterCompare(layers));
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
if (parameters[i].state == LAYER_STATE_OVERRIDDEN)
parameters[i].overridden_rank = static_cast<int>(i);
else
parameters[i].overridden_rank = Parameter::NO_RANK;
}
}
void FilterParameters(std::vector<Parameter>& parameters, const LayerState state) {
std::vector<Parameter> filtered_parameters;
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
if (parameters[i].state == state) continue;
filtered_parameters.push_back(parameters[i]);
}
parameters = filtered_parameters;
}
bool HasMissingLayer(const std::vector<Parameter>& parameters, const std::vector<Layer>& layers) {
for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it) {
if (it->state == LAYER_STATE_EXCLUDED) {
continue; // If excluded are missing, it doesn't matter
}
if (!(it->platform_flags & (1 << VKC_PLATFORM))) {
continue; // If unsupported are missing, it doesn't matter
}
if (!IsFound(layers, it->key.c_str())) {
return true;
}
}
return false;
}
std::size_t CountOverriddenLayers(const std::vector<Parameter>& parameters) {
std::size_t count = 0;
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
const Parameter& parameter = parameters[i];
if (!IsPlatformSupported(parameter.platform_flags)) continue;
if (parameter.state != LAYER_STATE_OVERRIDDEN) continue;
++count;
}
return count;
}
std::size_t CountExcludedLayers(const std::vector<Parameter>& parameters, const std::vector<Layer>& layers) {
std::size_t count = 0;
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
const Parameter& parameter = parameters[i];
if (!IsPlatformSupported(parameter.platform_flags)) continue;
if (parameter.state != LAYER_STATE_EXCLUDED) continue;
const Layer* layer = FindByKey(layers, parameter.key.c_str());
if (layer == nullptr) continue; // Do not display missing excluded layers
++count;
}
return count;
}
std::vector<Parameter> GatherParameters(const std::vector<Parameter>& parameters, const std::vector<Layer>& available_layers) {
std::vector<Parameter> gathered_parameters;
// Loop through the layers. They are expected to be in order
for (std::size_t i = 0, n = parameters.size(); i < n; ++i) {
const Parameter& parameter = parameters[i];
assert(!parameter.key.empty());
gathered_parameters.push_back(parameter);
}
for (std::size_t i = 0, n = available_layers.size(); i < n; ++i) {
const Layer& layer = available_layers[i];
// The layer is already in the layer tree
if (IsFound(parameters, layer.key.c_str())) continue;
Parameter parameter;
parameter.key = layer.key;
parameter.state = LAYER_STATE_APPLICATION_CONTROLLED;
CollectDefaultSettingData(layer.settings, parameter.settings);
gathered_parameters.push_back(parameter);
}
OrderParameter(gathered_parameters, available_layers);
return gathered_parameters;
}
| 36.767857 | 127 | 0.653715 | [
"vector"
] |
8802c87b65abfcf45c51611741f28e3cb2498eeb | 7,579 | cpp | C++ | src/Introspection/Introspection.cpp | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | src/Introspection/Introspection.cpp | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | src/Introspection/Introspection.cpp | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2021 The Orbit 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 "Introspection/Introspection.h"
#include <absl/base/attributes.h>
#include <absl/base/const_init.h>
#include <absl/synchronization/mutex.h>
#include <absl/time/time.h>
#include <string.h>
#include <memory>
#include <utility>
#include <vector>
#include "OrbitBase/Logging.h"
#include "OrbitBase/Profiling.h"
#include "OrbitBase/ThreadPool.h"
#include "OrbitBase/ThreadUtils.h"
using orbit_introspection::TracingListener;
using orbit_introspection::TracingScope;
using orbit_introspection::TracingTimerCallback;
ABSL_CONST_INIT static absl::Mutex global_tracing_mutex(absl::kConstInit);
ABSL_CONST_INIT static TracingListener* global_tracing_listener = nullptr;
// Tracing uses the same function table used by the Orbit API, but specifies its own functions.
orbit_api_v0 g_orbit_api_v0;
namespace orbit_introspection {
void InitializeTracing();
TracingScope::TracingScope(orbit_api::EventType type, const char* name, uint64_t data,
orbit_api_color color)
: encoded_event(type, name, data, color) {}
TracingListener::TracingListener(TracingTimerCallback callback) {
constexpr size_t kMinNumThreads = 1;
constexpr size_t kMaxNumThreads = 1;
thread_pool_ =
orbit_base::ThreadPool::Create(kMinNumThreads, kMaxNumThreads, absl::Milliseconds(500));
user_callback_ = std::move(callback);
// Activate listener (only one listener instance is supported).
absl::MutexLock lock(&global_tracing_mutex);
CHECK(!IsActive());
InitializeTracing();
global_tracing_listener = this;
active_ = true;
shutdown_initiated_ = false;
}
TracingListener::~TracingListener() {
// Communicate that the thread pool will be shut down before shutting down
// the thread pool itself.
// Note that this is required, as otherwise, we might allow scheduling
// new events on the already shut down thread pool.
{
absl::MutexLock lock(&global_tracing_mutex);
CHECK(IsActive());
shutdown_initiated_ = true;
}
// Purge deferred scopes.
thread_pool_->Shutdown();
thread_pool_->Wait();
// Deactivate and destroy the listener.
absl::MutexLock lock(&global_tracing_mutex);
active_ = false;
global_tracing_listener = nullptr;
}
} // namespace orbit_introspection
namespace {
struct ScopeToggle {
ScopeToggle() = delete;
ScopeToggle(bool* value, bool initial_value) : toggle(value) { *toggle = initial_value; }
~ScopeToggle() { *toggle = !*toggle; }
bool* toggle = nullptr;
};
} // namespace
void TracingListener::DeferScopeProcessing(const TracingScope& scope) {
// Prevent reentry to avoid feedback loop.
thread_local bool is_internal_update = false;
if (is_internal_update) return;
// User callback is called from a worker thread to minimize contention on instrumented threads.
absl::MutexLock lock(&global_tracing_mutex);
if (IsShutdownInitiated()) return;
global_tracing_listener->thread_pool_->Schedule([scope]() {
ScopeToggle scope_toggle(&is_internal_update, true);
absl::MutexLock lock(&global_tracing_mutex);
if (!IsActive()) return;
global_tracing_listener->user_callback_(scope);
});
}
static std::vector<TracingScope>& GetThreadLocalScopes() {
thread_local std::vector<TracingScope> thread_local_scopes;
return thread_local_scopes;
}
void orbit_api_start(const char* name, orbit_api_color color) {
GetThreadLocalScopes().emplace_back(
TracingScope(orbit_api::kScopeStart, name, /*data*/ 0, color));
auto& scope = GetThreadLocalScopes().back();
scope.begin = orbit_base::CaptureTimestampNs();
}
void orbit_api_stop() {
std::vector<TracingScope>& thread_local_scopes = GetThreadLocalScopes();
if (thread_local_scopes.size() == 0) return;
auto& scope = thread_local_scopes.back();
scope.end = orbit_base::CaptureTimestampNs();
scope.depth = GetThreadLocalScopes().size() - 1;
scope.tid = static_cast<uint32_t>(orbit_base::GetCurrentThreadId());
TracingListener::DeferScopeProcessing(scope);
GetThreadLocalScopes().pop_back();
}
void orbit_api_start_async(const char* name, uint64_t id, orbit_api_color color) {
TracingScope scope(orbit_api::kScopeStartAsync, name, id, color);
scope.begin = orbit_base::CaptureTimestampNs();
scope.end = scope.begin;
scope.tid = static_cast<uint32_t>(orbit_base::GetCurrentThreadId());
TracingListener::DeferScopeProcessing(scope);
}
void orbit_api_stop_async(uint64_t id) {
TracingScope scope(orbit_api::kScopeStopAsync, /*name*/ nullptr, id);
scope.begin = orbit_base::CaptureTimestampNs();
scope.end = scope.begin;
scope.tid = static_cast<uint32_t>(orbit_base::GetCurrentThreadId());
TracingListener::DeferScopeProcessing(scope);
}
void orbit_api_async_string(const char* str, uint64_t id, orbit_api_color color) {
if (str == nullptr) return;
TracingScope scope(orbit_api::kString, /*name*/ nullptr, id, color);
auto& e = scope.encoded_event;
constexpr size_t chunk_size = orbit_api::kMaxEventStringSize - 1;
const char* end = str + strlen(str);
while (str < end) {
std::strncpy(e.event.name, str, chunk_size);
e.event.name[chunk_size] = 0;
TracingListener::DeferScopeProcessing(scope);
str += chunk_size;
}
}
static inline void TrackValue(orbit_api::EventType type, const char* name, uint64_t value,
orbit_api_color color) {
TracingScope scope(type, name, value, color);
scope.begin = orbit_base::CaptureTimestampNs();
scope.tid = static_cast<uint32_t>(orbit_base::GetCurrentThreadId());
TracingListener::DeferScopeProcessing(scope);
}
void orbit_api_track_int(const char* name, int value, orbit_api_color color) {
TrackValue(orbit_api::kTrackInt, name, orbit_api::Encode<uint64_t>(value), color);
}
void orbit_api_track_int64(const char* name, int64_t value, orbit_api_color color) {
TrackValue(orbit_api::kTrackInt64, name, orbit_api::Encode<uint64_t>(value), color);
}
void orbit_api_track_uint(const char* name, uint32_t value, orbit_api_color color) {
TrackValue(orbit_api::kTrackUint, name, orbit_api::Encode<uint64_t>(value), color);
}
void orbit_api_track_uint64(const char* name, uint64_t value, orbit_api_color color) {
TrackValue(orbit_api::kTrackUint64, name, orbit_api::Encode<uint64_t>(value), color);
}
void orbit_api_track_float(const char* name, float value, orbit_api_color color) {
TrackValue(orbit_api::kTrackFloat, name, orbit_api::Encode<uint64_t>(value), color);
}
void orbit_api_track_double(const char* name, double value, orbit_api_color color) {
TrackValue(orbit_api::kTrackDouble, name, orbit_api::Encode<uint64_t>(value), color);
}
namespace orbit_introspection {
void InitializeTracing() {
if (g_orbit_api_v0.initialized != 0) return;
g_orbit_api_v0.start = &orbit_api_start;
g_orbit_api_v0.stop = &orbit_api_stop;
g_orbit_api_v0.start_async = &orbit_api_start_async;
g_orbit_api_v0.stop_async = &orbit_api_stop_async;
g_orbit_api_v0.async_string = &orbit_api_async_string;
g_orbit_api_v0.track_int = &orbit_api_track_int;
g_orbit_api_v0.track_int64 = &orbit_api_track_int64;
g_orbit_api_v0.track_uint = &orbit_api_track_uint;
g_orbit_api_v0.track_uint64 = &orbit_api_track_uint64;
g_orbit_api_v0.track_float = &orbit_api_track_float;
g_orbit_api_v0.track_double = &orbit_api_track_double;
std::atomic_thread_fence(std::memory_order_release);
g_orbit_api_v0.initialized = 1;
g_orbit_api_v0.enabled = 1;
}
} // namespace orbit_introspection
| 36.263158 | 97 | 0.759335 | [
"vector"
] |
8803b532481188eb40be4644f48707cd42faa4bf | 3,413 | cpp | C++ | Engine 3D/Application.cpp | MAtaur00/DiamondEngine | be2fe32d6172611c19f7285565e3b7e07c5c1f08 | [
"MIT"
] | null | null | null | Engine 3D/Application.cpp | MAtaur00/DiamondEngine | be2fe32d6172611c19f7285565e3b7e07c5c1f08 | [
"MIT"
] | null | null | null | Engine 3D/Application.cpp | MAtaur00/DiamondEngine | be2fe32d6172611c19f7285565e3b7e07c5c1f08 | [
"MIT"
] | null | null | null | #include "Application.h"
#include <time.h>
#include "pcg/pcg_basic.h"
using namespace std;
Application::Application()
{
window = new ModuleWindow(this);
input = new ModuleInput(this);
renderer3D = new ModuleRenderer3D(this);
camera = new ModuleCamera3D(this);
imgui = new ModuleIMGui(this);
sceneIntro = new ModuleSceneIntro(this);
geometry = new ModuleGeometry(this);
import = new ModuleImport(this);
game_object = new ModuleGameObject(this);
resources = new ModuleResources(this);
picking = new ModulePicking(this);
module_time = new Time(this);
particle_manager = new ModuleParticleManager(this);
// The order of calls is very important!
// Modules will Init() Start() and Update in this order
// They will CleanUp() in reverse order
// Main Modules
AddModule(window);
AddModule(camera);
AddModule(input);
AddModule(particle_manager);
AddModule(sceneIntro);
AddModule(import);
AddModule(game_object);
AddModule(resources);
AddModule(imgui);
AddModule(picking);
AddModule(module_time);
AddModule(geometry);
// Renderer last!
AddModule(renderer3D);
}
Application::~Application()
{
list<Module*>::const_iterator item = list_modules.begin();
while (item != list_modules.end())
{
delete(*item);
list_modules.erase(item);
item = list_modules.begin();
}
}
bool Application::Init()
{
bool ret = true;
// Call Init() in all modules
list<Module*>::const_iterator item = list_modules.begin();
while(item != list_modules.end() && ret == true)
{
ret = (*item)->Init();
item++;
}
// After all Init calls we call Start() in all modules
LOG("Application Start --------------");
item = list_modules.begin();
while(item != list_modules.end() && ret == true)
{
ret = (*item)->Start();
item++;
}
pcg32_random_t RNG1;
pcg32_srandom(time(NULL), (intptr_t)&RNG1);
ms_timer.Start();
return ret;
}
// ---------------------------------------------
void Application::PrepareUpdate()
{
dt = (float)ms_timer.Read() / 1000.0f;
ms_timer.Start();
fps_log.push_back(1/dt);
if (fps_log.size() > 75)
{
fps_log.erase(fps_log.begin());
}
ms_log.push_back(dt * 1000);
if (ms_log.size() > 75)
{
ms_log.erase(ms_log.begin());
}
}
// ---------------------------------------------
void Application::FinishUpdate()
{
if (!renderer3D->vsync && toCap)
{
float dt = dt * 1000.0f;
float toVsync = dt;
if (capFrames > 0)
toVsync = 1000.0f / capFrames;
if (dt < toVsync)
SDL_Delay(toVsync - dt);
}
}
// Call PreUpdate, Update and PostUpdate on all modules
update_status Application::Update()
{
update_status ret = UPDATE_CONTINUE;
PrepareUpdate();
std::list<Module*>::const_iterator item = list_modules.begin();
while(item != list_modules.end() && ret == UPDATE_CONTINUE)
{
ret = (*item)->PreUpdate();
item++;
}
item = list_modules.begin();
while(item != list_modules.end() && ret == UPDATE_CONTINUE)
{
ret = (*item)->Update();
item++;
}
item = list_modules.begin();
while(item != list_modules.end() && ret == UPDATE_CONTINUE)
{
ret = (*item)->PostUpdate();
item++;
}
FinishUpdate();
return ret;
}
bool Application::CleanUp()
{
bool ret = true;
std::list<Module*>::const_iterator item = list_modules.begin();
while(item != list_modules.end() && ret == true)
{
ret = (*item)->CleanUp();
item++;
}
return ret;
}
void Application::AddModule(Module* mod)
{
list_modules.push_back(mod);
} | 19.174157 | 64 | 0.653384 | [
"geometry"
] |
88056ef2e029805c8e45c1a5805db9098a68070b | 13,148 | cc | C++ | test/syscalls/linux/ioctl.cc | xyzst/gvisor | 58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082 | [
"Apache-2.0"
] | 12,536 | 2018-05-02T09:57:54.000Z | 2022-03-31T14:25:15.000Z | test/syscalls/linux/ioctl.cc | xyzst/gvisor | 58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082 | [
"Apache-2.0"
] | 2,478 | 2018-05-02T14:01:30.000Z | 2022-03-31T19:57:47.000Z | test/syscalls/linux/ioctl.cc | xyzst/gvisor | 58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082 | [
"Apache-2.0"
] | 1,163 | 2018-05-02T10:03:44.000Z | 2022-03-29T17:15:01.000Z | // Copyright 2018 The gVisor Authors.
//
// 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 <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <netdb.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "test/syscalls/linux/ip_socket_test_util.h"
#include "test/syscalls/linux/unix_domain_socket_test_util.h"
#include "test/util/file_descriptor.h"
#include "test/util/signal_util.h"
#include "test/util/socket_util.h"
#include "test/util/test_util.h"
namespace gvisor {
namespace testing {
namespace {
bool CheckNonBlocking(int fd) {
int ret = fcntl(fd, F_GETFL, 0);
TEST_CHECK(ret != -1);
return (ret & O_NONBLOCK) == O_NONBLOCK;
}
bool CheckCloExec(int fd) {
int ret = fcntl(fd, F_GETFD, 0);
TEST_CHECK(ret != -1);
return (ret & FD_CLOEXEC) == FD_CLOEXEC;
}
class IoctlTest : public ::testing::Test {
protected:
void SetUp() override {
ASSERT_THAT(fd_ = open("/dev/null", O_RDONLY), SyscallSucceeds());
}
void TearDown() override {
if (fd_ >= 0) {
ASSERT_THAT(close(fd_), SyscallSucceeds());
fd_ = -1;
}
}
int fd() const { return fd_; }
private:
int fd_ = -1;
};
TEST_F(IoctlTest, BadFileDescriptor) {
EXPECT_THAT(ioctl(-1 /* fd */, 0), SyscallFailsWithErrno(EBADF));
}
TEST_F(IoctlTest, InvalidControlNumber) {
EXPECT_THAT(ioctl(STDOUT_FILENO, 0), SyscallFailsWithErrno(ENOTTY));
}
TEST_F(IoctlTest, IoctlWithOpath) {
SKIP_IF(IsRunningWithVFS1());
const FileDescriptor fd =
ASSERT_NO_ERRNO_AND_VALUE(Open("/dev/null", O_PATH));
int set = 1;
EXPECT_THAT(ioctl(fd.get(), FIONBIO, &set), SyscallFailsWithErrno(EBADF));
EXPECT_THAT(ioctl(fd.get(), FIONCLEX), SyscallFailsWithErrno(EBADF));
EXPECT_THAT(ioctl(fd.get(), FIOCLEX), SyscallFailsWithErrno(EBADF));
}
TEST_F(IoctlTest, FIONBIOSucceeds) {
EXPECT_FALSE(CheckNonBlocking(fd()));
int set = 1;
EXPECT_THAT(ioctl(fd(), FIONBIO, &set), SyscallSucceeds());
EXPECT_TRUE(CheckNonBlocking(fd()));
set = 0;
EXPECT_THAT(ioctl(fd(), FIONBIO, &set), SyscallSucceeds());
EXPECT_FALSE(CheckNonBlocking(fd()));
}
TEST_F(IoctlTest, FIONBIOFails) {
EXPECT_THAT(ioctl(fd(), FIONBIO, nullptr), SyscallFailsWithErrno(EFAULT));
}
TEST_F(IoctlTest, FIONCLEXSucceeds) {
EXPECT_THAT(ioctl(fd(), FIONCLEX), SyscallSucceeds());
EXPECT_FALSE(CheckCloExec(fd()));
}
TEST_F(IoctlTest, FIOCLEXSucceeds) {
EXPECT_THAT(ioctl(fd(), FIOCLEX), SyscallSucceeds());
EXPECT_TRUE(CheckCloExec(fd()));
}
TEST_F(IoctlTest, FIOASYNCFails) {
EXPECT_THAT(ioctl(fd(), FIOASYNC, nullptr), SyscallFailsWithErrno(EFAULT));
}
TEST_F(IoctlTest, FIOASYNCSucceeds) {
// Not all FDs support FIOASYNC.
const FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(
Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
int before = -1;
ASSERT_THAT(before = fcntl(s.get(), F_GETFL), SyscallSucceeds());
int set = 1;
EXPECT_THAT(ioctl(s.get(), FIOASYNC, &set), SyscallSucceeds());
int after_set = -1;
ASSERT_THAT(after_set = fcntl(s.get(), F_GETFL), SyscallSucceeds());
EXPECT_EQ(after_set, before | O_ASYNC) << "before was " << before;
set = 0;
EXPECT_THAT(ioctl(s.get(), FIOASYNC, &set), SyscallSucceeds());
ASSERT_THAT(fcntl(s.get(), F_GETFL), SyscallSucceedsWithValue(before));
}
/* Count of the number of SIGIOs handled. */
static volatile int io_received = 0;
void inc_io_handler(int sig, siginfo_t* siginfo, void* arg) { io_received++; }
TEST_F(IoctlTest, FIOASYNCNoTarget) {
auto pair =
ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());
// Count SIGIOs received.
io_received = 0;
struct sigaction sa;
sa.sa_sigaction = inc_io_handler;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
auto sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
// Actually allow SIGIO delivery.
auto mask_cleanup =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));
int set = 1;
EXPECT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
constexpr char kData[] = "abc";
ASSERT_THAT(WriteFd(pair->first_fd(), kData, sizeof(kData)),
SyscallSucceedsWithValue(sizeof(kData)));
EXPECT_EQ(io_received, 0);
}
TEST_F(IoctlTest, FIOASYNCSelfTarget) {
// FIXME(b/120624367): gVisor erroneously sends SIGIO on close(2), which would
// kill the test when pair goes out of scope. Temporarily ignore SIGIO so that
// that the close signal is ignored.
struct sigaction sa;
sa.sa_handler = SIG_IGN;
auto early_sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
auto pair =
ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());
// Count SIGIOs received.
io_received = 0;
sa.sa_sigaction = inc_io_handler;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
auto sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
// Actually allow SIGIO delivery.
auto mask_cleanup =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));
int set = 1;
EXPECT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
pid_t pid = getpid();
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());
constexpr char kData[] = "abc";
ASSERT_THAT(WriteFd(pair->first_fd(), kData, sizeof(kData)),
SyscallSucceedsWithValue(sizeof(kData)));
EXPECT_EQ(io_received, 1);
}
// Equivalent to FIOASYNCSelfTarget except that FIOSETOWN is called before
// FIOASYNC.
TEST_F(IoctlTest, FIOASYNCSelfTarget2) {
// FIXME(b/120624367): gVisor erroneously sends SIGIO on close(2), which would
// kill the test when pair goes out of scope. Temporarily ignore SIGIO so that
// that the close signal is ignored.
struct sigaction sa;
sa.sa_handler = SIG_IGN;
auto early_sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
auto pair =
ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());
// Count SIGIOs received.
io_received = 0;
sa.sa_sigaction = inc_io_handler;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
auto sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
// Actually allow SIGIO delivery.
auto mask_cleanup =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));
pid_t pid = -1;
EXPECT_THAT(pid = getpid(), SyscallSucceeds());
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());
int set = 1;
EXPECT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
constexpr char kData[] = "abc";
ASSERT_THAT(WriteFd(pair->first_fd(), kData, sizeof(kData)),
SyscallSucceedsWithValue(sizeof(kData)));
EXPECT_EQ(io_received, 1);
}
// Check that closing an FD does not result in an event.
TEST_F(IoctlTest, FIOASYNCSelfTargetClose) {
// Count SIGIOs received.
struct sigaction sa;
io_received = 0;
sa.sa_sigaction = inc_io_handler;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
auto sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
// Actually allow SIGIO delivery.
auto mask_cleanup =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));
for (int i = 0; i < 2; i++) {
auto pair = ASSERT_NO_ERRNO_AND_VALUE(
UnixDomainSocketPair(SOCK_SEQPACKET).Create());
pid_t pid = getpid();
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());
int set = 1;
EXPECT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
}
// FIXME(b/120624367): gVisor erroneously sends SIGIO on close.
SKIP_IF(IsRunningOnGvisor());
EXPECT_EQ(io_received, 0);
}
TEST_F(IoctlTest, FIOASYNCInvalidPID) {
auto pair =
ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());
int set = 1;
ASSERT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
pid_t pid = INT_MAX;
// This succeeds (with behavior equivalent to a pid of 0) in Linux prior to
// f73127356f34 "fs/fcntl: return -ESRCH in f_setown when pid/pgid can't be
// found", and fails with EPERM after that commit.
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid),
AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(ESRCH)));
}
TEST_F(IoctlTest, FIOASYNCUnsetTarget) {
auto pair =
ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());
// Count SIGIOs received.
io_received = 0;
struct sigaction sa;
sa.sa_sigaction = inc_io_handler;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
auto sa_cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGIO, sa));
// Actually allow SIGIO delivery.
auto mask_cleanup =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));
int set = 1;
EXPECT_THAT(ioctl(pair->second_fd(), FIOASYNC, &set), SyscallSucceeds());
pid_t pid = getpid();
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());
// Passing a PID of 0 unsets the target.
pid = 0;
EXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());
constexpr char kData[] = "abc";
ASSERT_THAT(WriteFd(pair->first_fd(), kData, sizeof(kData)),
SyscallSucceedsWithValue(sizeof(kData)));
EXPECT_EQ(io_received, 0);
}
using IoctlTestSIOCGIFCONF = SimpleSocketTest;
TEST_P(IoctlTestSIOCGIFCONF, ValidateNoArrayGetsLength) {
auto fd = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
// Validate that no array can be used to get the length required.
struct ifconf ifconf = {};
ASSERT_THAT(ioctl(fd->get(), SIOCGIFCONF, &ifconf), SyscallSucceeds());
ASSERT_GT(ifconf.ifc_len, 0);
}
// This test validates that we will only return a partial array list and not
// partial ifrreq structs.
TEST_P(IoctlTestSIOCGIFCONF, ValidateNoPartialIfrsReturned) {
auto fd = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
struct ifreq ifr = {};
struct ifconf ifconf = {};
ifconf.ifc_len = sizeof(ifr) - 1; // One byte too few.
ifconf.ifc_ifcu.ifcu_req = 𝔦
ASSERT_THAT(ioctl(fd->get(), SIOCGIFCONF, &ifconf), SyscallSucceeds());
ASSERT_EQ(ifconf.ifc_len, 0);
ASSERT_EQ(ifr.ifr_name[0], '\0'); // Nothing is returned.
ifconf.ifc_len = sizeof(ifreq);
ASSERT_THAT(ioctl(fd->get(), SIOCGIFCONF, &ifconf), SyscallSucceeds());
ASSERT_GT(ifconf.ifc_len, 0);
ASSERT_NE(ifr.ifr_name[0], '\0'); // An interface can now be returned.
}
TEST_P(IoctlTestSIOCGIFCONF, ValidateLoopbackIsPresent) {
auto fd = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
struct ifconf ifconf = {};
struct ifreq ifr[10] = {}; // Storage for up to 10 interfaces.
ifconf.ifc_req = ifr;
ifconf.ifc_len = sizeof(ifr);
ASSERT_THAT(ioctl(fd->get(), SIOCGIFCONF, &ifconf), SyscallSucceeds());
size_t num_if = ifconf.ifc_len / sizeof(struct ifreq);
// We should have at least one interface.
ASSERT_GE(num_if, 1);
// One of the interfaces should be a loopback.
bool found_loopback = false;
for (size_t i = 0; i < num_if; ++i) {
if (strcmp(ifr[i].ifr_name, "lo") == 0) {
// SIOCGIFCONF returns the ipv4 address of the interface, let's check it.
ASSERT_EQ(ifr[i].ifr_addr.sa_family, AF_INET);
// Validate the address is correct for loopback.
sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(&ifr[i].ifr_addr);
ASSERT_EQ(htonl(sin->sin_addr.s_addr), INADDR_LOOPBACK);
found_loopback = true;
break;
}
}
ASSERT_TRUE(found_loopback);
}
std::vector<SocketKind> IoctlSocketTypes() {
return {SimpleSocket(AF_UNIX, SOCK_STREAM, 0),
SimpleSocket(AF_UNIX, SOCK_DGRAM, 0),
SimpleSocket(AF_INET, SOCK_STREAM, 0),
SimpleSocket(AF_INET6, SOCK_STREAM, 0),
SimpleSocket(AF_INET, SOCK_DGRAM, 0),
SimpleSocket(AF_INET6, SOCK_DGRAM, 0)};
}
INSTANTIATE_TEST_SUITE_P(IoctlTest, IoctlTestSIOCGIFCONF,
::testing::ValuesIn(IoctlSocketTypes()));
} // namespace
TEST_F(IoctlTest, FIOGETOWNSucceeds) {
const FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(
Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
int get = -1;
ASSERT_THAT(ioctl(s.get(), FIOGETOWN, &get), SyscallSucceeds());
EXPECT_EQ(get, 0);
}
TEST_F(IoctlTest, SIOCGPGRPSucceeds) {
const FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(
Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
int get = -1;
ASSERT_THAT(ioctl(s.get(), SIOCGPGRP, &get), SyscallSucceeds());
EXPECT_EQ(get, 0);
}
} // namespace testing
} // namespace gvisor
| 31.304762 | 80 | 0.712656 | [
"vector"
] |
8806092e0cd895a90050395b8718344e0561c3e8 | 36,648 | cpp | C++ | third_party/cryptoTools/cryptoTools/Network/IOService.cpp | bfeng/CryptoGRU | 65f6fe9eba981fea65fc665ff16938bf3a593001 | [
"MIT"
] | 1 | 2022-01-12T03:18:55.000Z | 2022-01-12T03:18:55.000Z | third_party/cryptoTools/cryptoTools/Network/IOService.cpp | bfeng/CryptoGRU | 65f6fe9eba981fea65fc665ff16938bf3a593001 | [
"MIT"
] | null | null | null | third_party/cryptoTools/cryptoTools/Network/IOService.cpp | bfeng/CryptoGRU | 65f6fe9eba981fea65fc665ff16938bf3a593001 | [
"MIT"
] | null | null | null | #include <cryptoTools/Network/IOService.h>
#include <cryptoTools/Common/Defines.h>
#include <cryptoTools/Common/Finally.h>
#include <cryptoTools/Common/Log.h>
#include <cryptoTools/Common/Timer.h>
#include <cryptoTools/Network/Session.h>
#include <cryptoTools/Network/IoBuffer.h>
#include <cryptoTools/Network/Channel.h>
#include <cryptoTools/Network/SocketAdapter.h>
#include <stdio.h>
#include <algorithm>
#include <sstream>
namespace osuCrypto
{
Acceptor::Acceptor(IOService& ioService)
:
//mSocketChannelPairsRemovedFuture(mSocketChannelPairsRemovedProm.get_future()),
mPendingSocketsEmptyFuture(mPendingSocketsEmptyProm.get_future()),
mStoppedFuture(mStoppedPromise.get_future()),
mIOService(ioService),
mStrand(ioService.mIoService),
mHandle(ioService.mIoService),
mStopped(false),
mPort(0)
{
}
Acceptor::~Acceptor()
{
stop();
}
void Acceptor::bind(u32 port, std::string ip, boost::system::error_code& ec)
{
auto pStr = std::to_string(port);
mPort = port;
boost::asio::ip::tcp::resolver resolver(mIOService.mIoService);
boost::asio::ip::tcp::resolver::query
query(ip, pStr);
auto addrIter = resolver.resolve(query, ec);
if (ec)
{
return;
}
mAddress = *addrIter;
mHandle.open(mAddress.protocol());
mHandle.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
mHandle.bind(mAddress, ec);
if (mAddress.port() != port)
throw std::runtime_error("rt error at " LOCATION);
if (ec)
{
return;
//std::cout << "network address bind error: " << ec.message() << std::endl;
//throw std::runtime_error(ec.message());
}
//std::promise<void> mStoppedListeningPromise, mSocketChannelPairsRemovedProm;
//std::future<void> mStoppedListeningFuture, mSocketChannelPairsRemovedFuture;
mHandle.listen(boost::asio::socket_base::max_connections);
}
void Acceptor::start()
{
mStrand.dispatch([&]()
{
if (isListening())
{
mPendingSockets.emplace_back(mIOService.mIoService);
auto sockIter = mPendingSockets.end(); --sockIter;
//BoostSocketInterface* newSocket = new BoostSocketInterface(mIOService.mIoService);
mHandle.async_accept(sockIter->mSock, [sockIter, this](const boost::system::error_code& ec)
{
start();
if (!ec)
{
boost::asio::ip::tcp::no_delay option(true);
sockIter->mSock.set_option(option);
sockIter->mBuff.resize(sizeof(u32));
sockIter->mSock.async_receive(boost::asio::buffer((char*)sockIter->mBuff.data(), sockIter->mBuff.size()),
[sockIter, this](const boost::system::error_code& ec2, u64 bytesTransferred)
{
if (!ec2 && bytesTransferred == 4)
{
auto size = *(u32*)sockIter->mBuff.data();
sockIter->mBuff.resize(size);
sockIter->mSock.async_receive(boost::asio::buffer((char*)sockIter->mBuff.data(), sockIter->mBuff.size()),
mStrand.wrap([sockIter, this](const boost::system::error_code& ec3, u64 bytesTransferred2)
{
if (!ec3 && bytesTransferred2 == sockIter->mBuff.size())
{
asyncSetSocket(
std::move(sockIter->mBuff),
std::move(std::unique_ptr<BoostSocketInterface>(
new BoostSocketInterface(std::move(sockIter->mSock)))));
}
mPendingSockets.erase(sockIter);
if (stopped() && mPendingSockets.size() == 0)
mPendingSocketsEmptyProm.set_value();
}));
}
else
{
//std::cout << "async_accept error, failed to receive first header on connection handshake."
// << " Other party may have closed the connection. "
// << ((ec2 != 0) ? "Error code:" + ec2.message() : " received " + ToString(bytesTransferred) + " / 4 bytes") << " " << LOCATION << std::endl;
mStrand.dispatch([&, sockIter]()
{
mPendingSockets.erase(sockIter);
if (stopped() && mPendingSockets.size() == 0)
mPendingSocketsEmptyProm.set_value();
});
}
});
}
else
{
mStrand.dispatch([&, sockIter]()
{
mPendingSockets.erase(sockIter);
if (stopped() && mPendingSockets.size() == 0)
mPendingSocketsEmptyProm.set_value();
});
}
});
}
else
{
//mStrand.dispatch([&]()
//{
// if (stopped() && mPendingSockets.size() == 0)
// mPendingSocketsEmptyProm.set_value();
//});
}
});
}
void Acceptor::stop()
{
if (mStopped == false)
{
mStrand.dispatch([&]() {
if (mStopped == false)
{
mStopped = true;
mListening = false;
// stop listening.
//std::cout << IoStream::lock << " accepter stop() " << mPort << std::endl << IoStream::unlock;
mHandle.close();
// cancel any sockets which have not completed the handshake.
for (auto& pendingSocket : mPendingSockets)
pendingSocket.mSock.close();
// if there were no pending sockets, set the promise
if (mPendingSockets.size() == 0)
mPendingSocketsEmptyProm.set_value();
// no subscribers, we can set the promise now.
if (hasSubscriptions() == false)
mStoppedPromise.set_value();
}
});
// wait for the pending events.
std::chrono::seconds timeout(4);
std::future_status status = mPendingSocketsEmptyFuture.wait_for(timeout);
while (status == std::future_status::timeout)
{
status = mPendingSocketsEmptyFuture.wait_for(timeout);
std::cout << "waiting on acceptor to close "<< mPendingSockets.size() <<" pending socket" << std::endl;
}
mPendingSocketsEmptyFuture.get();
mStoppedFuture.get();
}
}
bool Acceptor::hasSubscriptions() const
{
for (auto& a : mGroups)
if (a.hasSubscriptions())
return true;
return false;
}
void Acceptor::stopListening()
{
if (isListening())
{
mStrand.dispatch([&]() {
if (hasSubscriptions() == false)
{
mListening = false;
//std::cout << IoStream::lock << "stop listening " << std::endl << IoStream::unlock;
mHandle.close();
if (stopped() && hasSubscriptions() == false)
mStoppedPromise.set_value();
}
});
}
}
void Acceptor::unsubscribe(SessionBase* session)
{
std::promise<void> p;
std::future<void> f(p.get_future());
auto iter = session->mGroup;
mStrand.dispatch([&, iter]() {
iter->mBase.reset();
if (iter->hasSubscriptions() == false)
{
iter->removeMapping();
mGroups.erase(iter);
}
// if no one else wants us to listen, stop listening
if (hasSubscriptions() == false)
stopListening();
p.set_value();
});
f.get();
}
void Acceptor::subscribe(std::shared_ptr<SessionBase>& session)
{
std::promise<void> p;
std::future<void> f = p.get_future();
session->mAcceptor = this;
mStrand.dispatch([&]() {
if (mStopped)
{
auto ePtr = std::make_exception_ptr(
std::runtime_error("can not subscribe to a stopped Acceptor."));
p.set_exception(ePtr);
}
else
{
mGroups.emplace_back();
auto iter = mGroups.end(); --iter;
iter->mBase = session;
session->mGroup = iter;
auto key = session->mName;
auto& collection = mUnclaimedGroups[key];
collection.emplace_back(iter);
auto deleteIter = collection.end(); --deleteIter;
iter->removeMapping = [&, deleteIter, key]()
{
collection.erase(deleteIter);
if (collection.size() == 0)
mUnclaimedGroups.erase(mUnclaimedGroups.find(key));
};
if (mListening == false)
{
mListening = true;
boost::system::error_code ec;
bind(session->mPort, session->mIP, ec);
if (ec) {
auto ePtr = std::make_exception_ptr(
std::runtime_error("network bind error: " + ec.message()));
p.set_exception(ePtr);
}
start();
}
p.set_value();
}
});
// may throw
f.get();
}
Acceptor::SocketGroupList::iterator Acceptor::getSocketGroup(const std::string & sessionName, u64 sessionID)
{
auto unclaimedSocketIter = mUnclaimedSockets.find(sessionName);
if (unclaimedSocketIter != mUnclaimedSockets.end())
{
auto& sockets = unclaimedSocketIter->second;
auto matchIter = std::find_if(sockets.begin(), sockets.end(),
[&](const SocketGroupList::iterator& g) { return g->mSessionID == sessionID; });
if (matchIter != sockets.end())
return *matchIter;
}
// there is no socket group for this session. lets create one.
mSockets.emplace_back();
auto socketIter = mSockets.end(); --socketIter;
socketIter->mName = sessionName;
socketIter->mSessionID = sessionID;
// add a mapping to indicate that this group is unclaimed
auto& group = mUnclaimedSockets[sessionName];
group.emplace_back(socketIter);
auto deleteIter = group.end(); --deleteIter;
socketIter->removeMapping = [&group, &socketIter, this, sessionName, deleteIter]() {
group.erase(deleteIter);
if (group.size() == 0) mUnclaimedSockets.erase(mUnclaimedSockets.find(sessionName));
};
return socketIter;
}
void Acceptor::cancelPendingChannel(ChannelBase* chl)
{
mStrand.dispatch([=]() {
auto iter = chl->mSession->mGroup;
auto chlIter = std::find_if(iter->mChannels.begin(), iter->mChannels.end(),
[&](const std::shared_ptr<ChannelBase>& c) { return c.get() == chl; });
if (chlIter != iter->mChannels.end())
{
auto ePtr = std::make_exception_ptr(SocketConnectError("Acceptor canceled the socket request. " LOCATION));
(*chlIter)->mOpenProm.set_exception(ePtr);
iter->mChannels.erase(chlIter);
if (iter->hasSubscriptions() == false)
{
iter->removeMapping();
mGroups.erase(iter);
if (hasSubscriptions() == false)
stopListening();
}
}
});
}
bool Acceptor::stopped() const
{
return mStopped;
}
std::string Acceptor::print() const
{
return std::string();
}
//bool Acceptor::userModeIsListening() const
//{
// return false;
//}
//std::atomic<int> ccc(0);
void Acceptor::asyncGetSocket(std::shared_ptr<ChannelBase> chl)
{
if (stopped()) throw std::runtime_error(LOCATION);
mStrand.dispatch([&, chl]() {
auto& sessionGroup = chl->mSession->mGroup;
auto& sessionName = chl->mSession->mName;
auto& sessionID = chl->mSession->mSessionID;
if (sessionID)
{
sessionGroup->add(chl, this);
if (sessionGroup->hasSubscriptions() == false)
{
sessionGroup->removeMapping();
mGroups.erase(sessionGroup);
if (hasSubscriptions() == false)
stopListening();
}
return;
}
auto socketGroup = mSockets.end();
auto unclaimedSocketIter = mUnclaimedSockets.find(sessionName);
if (unclaimedSocketIter != mUnclaimedSockets.end())
{
auto& groups = unclaimedSocketIter->second;
auto matchIter = std::find_if(groups.begin(), groups.end(),
[&](const SocketGroupList::iterator& g) { return g->hasMatchingSocket(chl); });
if (matchIter != groups.end())
socketGroup = *matchIter;
}
// add this channel to this group.
sessionGroup->add(chl, this);
// check if we have matching sockets.
if (socketGroup != mSockets.end())
{
// merge the group of sockets into the SessionGroup.
sessionGroup->merge(*socketGroup, this);
// erase the mapping for these sockets being unclaimed.
socketGroup->removeMapping();
sessionGroup->removeMapping();
// erase the sockets.
mSockets.erase(socketGroup);
// check if we can erase this session group (session closed).
if (sessionGroup->hasSubscriptions() == false)
{
mGroups.erase(sessionGroup);
if (hasSubscriptions() == false)
stopListening();
}
else
{
// If not then add this SessionGroup to the list of claimed
// sessions. Remove the unclaimed channel mapping
auto fullKey = sessionName + std::to_string(sessionID);
auto pair = mClaimedGroups.insert({ fullKey, sessionGroup });
auto s = pair.second;
auto location = pair.first;
if (s == false)
throw std::runtime_error(LOCATION);
sessionGroup->removeMapping = [&, location]() { mClaimedGroups.erase(location); };
}
}
});
}
void Acceptor::asyncSetSocket(
std::string name,
std::unique_ptr<BoostSocketInterface> s)
{
mStrand.dispatch([this, name, ss = s.release()]() {
std::unique_ptr<BoostSocketInterface> sock(ss);
auto names = split(name, '`');
if (names.size() != 4)
{
std::cout << "bad channel name: " << name << std::endl
<< "Dropping the connection" << std::endl;
return;
}
auto& sessionName = names[0];
auto sessionID = std::stoull(names[1]);
auto& remoteName = names[2];
auto& localName = names[3];
details::NamedSocket socket;
socket.mLocalName = localName;
socket.mRemoteName = remoteName;
socket.mSocket = std::move(sock);
auto fullKey = sessionName + std::to_string(sessionID);
auto claimedIter = mClaimedGroups.find(fullKey);
if (claimedIter != mClaimedGroups.end())
{
auto group = claimedIter->second;
group->add(std::move(socket), this);
if (group->hasSubscriptions() == false)
{
group->removeMapping();
mGroups.erase(group);
if (hasSubscriptions() == false)
stopListening();
}
return;
}
auto socketGroup = getSocketGroup(sessionName, sessionID);
GroupList::iterator sessionGroup = mGroups.end();
auto unclaimedLocalIter = mUnclaimedGroups.find(sessionName);
if (unclaimedLocalIter != mUnclaimedGroups.end())
{
auto& groups = unclaimedLocalIter->second;
auto matchIter = std::find_if(groups.begin(), groups.end(),
[&](const GroupList::iterator& g) { return g->hasMatchingChannel(socket); });
if (matchIter != groups.end())
sessionGroup = *matchIter;
}
// add the socket to the SocketGroup
socketGroup->mSockets.emplace_back(std::move(socket));
if (sessionGroup != mGroups.end())
{
// merge the sockets into the group of cahnnels.
sessionGroup->merge(*socketGroup, this);
// make these socketes as claimed and remove the container.
socketGroup->removeMapping();
sessionGroup->removeMapping();
mSockets.erase(socketGroup);
// check if we can erase this seesion group (session closed).
if (sessionGroup->hasSubscriptions() == false)
{
mGroups.erase(sessionGroup);
if (hasSubscriptions() == false)
stopListening();
}
else
{
// If not then add this SessionGroup to the list of claimed
// sessions. Remove the unclaimed channel mapping
auto pair = mClaimedGroups.insert({ fullKey, sessionGroup });
auto s = pair.second;
auto location = pair.first;
if (s == false)
throw std::runtime_error(LOCATION);
sessionGroup->removeMapping = [&, location]() { mClaimedGroups.erase(location); };
}
}
});
}
extern void split(const std::string &s, char delim, std::vector<std::string> &elems);
extern std::vector<std::string> split(const std::string &s, char delim);
IOService::IOService(u64 numThreads)
:
mIoService(),
mStrand(mIoService),
mWorker(new boost::asio::io_service::work(mIoService))
{
// Determine how many processors are on the system
//SYSTEM_INFO SystemInfo;
//GetSystemInfo(&SystemInfo);
// if they provided 0, the use the number of processors worker threads
numThreads = (numThreads) ? numThreads : std::thread::hardware_concurrency();
mWorkerThrds.resize(numThreads);
u64 i = 0;
// Create worker threads based on the number of processors available on the
// system. Create two worker threads for each processor
for (auto& thrd : mWorkerThrds)
{
// Create a server worker thread and pass the completion port to the thread
thrd = std::thread([&, i]()
{
setThreadName("io_Thrd_" + std::to_string(i));
mIoService.run();
//std::cout << "io_Thrd_" + std::to_string(i) << " closed" << std::endl;
});
++i;
}
}
IOService::~IOService()
{
// block until everything has shutdown.
stop();
}
void IOService::stop()
{
// Skip if its already shutdown.
if (mStopped == false)
{
mStopped = true;
// tell all the acceptor threads to stop accepting new connections.
for (auto& accptr : mAcceptors)
{
accptr.stop();
}
// delete all of their state.
mAcceptors.clear();
mWorker.reset(nullptr);
// we can now join on them.
for (auto& thrd : mWorkerThrds)
{
thrd.join();
}
// clean their state.
mWorkerThrds.clear();
}
}
void IOService::printErrorMessages(bool v)
{
mPrint = v;
}
void IOService::receiveOne(ChannelBase* channel)
{
////////////////////////////////////////////////////////////////////////////////
//// THis is within the stand. We have sequential access to the recv queue. ////
////////////////////////////////////////////////////////////////////////////////
IOOperation& op = *channel->mRecvQueue.front();
#ifdef CHANNEL_LOGGING
channel->mLog.push("starting recv #" + ToString(op.mIdx) + ", size = " + ToString(op.size()));
#endif
if (op.type() == IOOperation::Type::RecvData)
{
op.mBuffs[0] = boost::asio::buffer(&channel->mRecvSizeBuff, sizeof(u32));
std::array<boost::asio::mutable_buffer, 1>tt{ {op.mBuffs[0] } };
//boost::asio::async_read(*,
channel->mHandle->async_recv(
tt,
[&op, channel, this](const boost::system::error_code& ec, u64 bytesTransfered)
{
//////////////////////////////////////////////////////////////////////////
//// This is *** NOT *** within the stand. Dont touch the recv queue! ////
//////////////////////////////////////////////////////////////////////////
if (bytesTransfered != boost::asio::buffer_size(op.mBuffs[0]) || ec)
{
auto reason = ("rt error at " LOCATION "\n ec=" + ec.message() + ". else bytesTransfered != " + std::to_string(boost::asio::buffer_size(op.mBuffs[0])))
+ "\nThis could be from the other end closing too early or the connection being dropped.\n"
+ "Channel: " + channel->mLocalName
+ ", Session: " + channel->mSession->mName + " " + ToString(channel->mSession->mPort) + " "
+ ToString(channel->mSession->mMode == SessionMode::Server);
if (mPrint) std::cout << reason << std::endl;
channel->setRecvFatalError(reason);
return;
}
std::string msg;
// We support two types of receives. One where we provide the expected size of the message and one
// where we allow for variable length messages. op->other will be non null in the resize case and allow
// us to resize the ChannelBuffer which will hold the data.
// resize it. This could throw is the channel buffer chooses to.
if (channel->mRecvSizeBuff != op.size() && op.resize(channel->mRecvSizeBuff) == false)
{
msg = std::string() + "The provided buffer does not fit the received message. \n" +
" Expected: Container::size() * sizeof(Container::value_type) = " +
std::to_string(op.size()) + " bytes\n"
" Actual: " + std::to_string(channel->mRecvSizeBuff) + " bytes\n\n" +
"If sizeof(Container::value_type) % Actual != 0, this will throw or ResizableChannelBuffRef<Container>::resize(...) returned false.";
}
else
{
// set the buffer to point into the channel buffer storage location.
op.mBuffs[1] = boost::asio::buffer(op.data(), channel->mRecvSizeBuff);
}
auto recvMain = [&op, channel, this](const boost::system::error_code& ec, u64 bytesTransfered)
{
//////////////////////////////////////////////////////////////////////////
//// This is *** NOT *** within the stand. Dont touch the recv queue! ////
//////////////////////////////////////////////////////////////////////////
if (bytesTransfered != boost::asio::buffer_size(op.mBuffs[1]) || ec)
{
auto reason = ("Network error: " + ec.message() + "\nOther end may have crashed. Received incomplete message. at " LOCATION);
if (mPrint) std::cout << reason << std::endl;
channel->setRecvFatalError(reason);
return;
}
channel->mTotalRecvData += boost::asio::buffer_size(op.mBuffs[1]);
//// signal that the recv has completed.
//if (op.mException)
// op.mPromise->set_exception(op.mException);
//else
op.mPromise.set_value();
if (op.mCallback)
{
op.mCallback();
}
//delete op.mContainer;
channel->mRecvStrand.dispatch([channel, this, &op]()
{
////////////////////////////////////////////////////////////////////////////////
//// This is within the stand. We have sequential access to the recv queue. ////
////////////////////////////////////////////////////////////////////////////////
#ifdef CHANNEL_LOGGING
channel->mLog.push("completed recv #" + ToString(op.mIdx) + ", size = " + ToString(channel->mRecvSizeBuff));
#endif
//delete channel->mRecvQueue.front();
channel->mRecvQueue.pop_front();
// is there more messages to recv?
bool sendMore = (channel->mRecvQueue.size() != 0);
if (sendMore)
{
receiveOne(channel);
}
else if (channel->mRecvStatus == Channel::Status::Stopped)
{
channel->mRecvQueueEmptyProm.set_value();
channel->mRecvQueueEmptyProm = std::promise<void>();
}
});
};
if (msg.size())
{
if (mPrint) std::cout << msg << std::endl;
channel->setBadRecvErrorState(msg);
// give the user a chance to give us another location.
auto e_ptr = std::make_exception_ptr(BadReceiveBufferSize(msg, channel->mRecvSizeBuff, [&, channel, recvMain](u8* dest)
{
channel->clearBadRecvErrorState();
op.mBuffs[1] = boost::asio::buffer(dest, channel->mRecvSizeBuff);
bool error;
u64 bytesTransfered;
std::array<boost::asio::mutable_buffer, 1>tt{ {op.mBuffs[1] } };
channel->mHandle->recv(tt, error, bytesTransfered);
auto ec = error ? boost::system::errc::make_error_code(boost::system::errc::io_error) : boost::system::errc::make_error_code(boost::system::errc::success);
recvMain(ec, bytesTransfered);
}));
op.mPromise.set_exception(e_ptr);
op.mPromise = std::promise<void>();
}
else
{
std::array<boost::asio::mutable_buffer, 1>tt{ {op.mBuffs[1] } };
channel->mHandle->async_recv(tt, recvMain);
//boost::asio::async_read(*channel->mHandle,
// std::array<boost::asio::mutable_buffer, 1>{ op.mBuffs[1] }, recvMain);
}
});
}
else if (op.type() == IOOperation::Type::CloseRecv)
{
#ifdef CHANNEL_LOGGING
channel->mLog.push("recvClosed #" + ToString(op.mIdx));
#endif
//delete channel->mRecvQueue.front();
channel->mRecvQueue.pop_front();
channel->mRecvQueueEmptyProm.set_value();
}
else
{
std::cout << "error, unknown operation " << int(u8(op.type())) << std::endl;
std::terminate();
}
}
void IOService::sendOne(ChannelBase* socket)
{
////////////////////////////////////////////////////////////////////////////////
//// This is within the stand. We have sequential access to the send queue. ////
////////////////////////////////////////////////////////////////////////////////
IOOperation& op = *socket->mSendQueue.front();
#ifdef CHANNEL_LOGGING
socket->mLog.push("starting send #" + ToString(op.mIdx) + ", size = " + ToString(op.size()));
#endif
if (op.type() == IOOperation::Type::SendData)
{
socket->mSendSizeBuff = u32(op.size());
op.mBuffs[0] = boost::asio::buffer(&socket->mSendSizeBuff, sizeof(u32));
socket->mHandle->async_send(op.mBuffs, [&op, socket, this](boost::system::error_code ec, u64 bytesTransferred)
//boost::asio::async_write(
{
//////////////////////////////////////////////////////////////////////////
//// This is *** NOT *** within the stand. Dont touch the send queue! ////
//////////////////////////////////////////////////////////////////////////
if (ec)
{
auto reason = std::string("network send error: ") + ec.message() + "\n at " + LOCATION;
if (mPrint) std::cout << reason << std::endl;
socket->setSendFatalError(reason);
return;
}
// lets delete the other pointer as its either nullptr or a buffer that was allocated
//delete (ChannelBuffer*)op.mOther;
// make sure all the data sent. If this fails, look up whether WSASend guarantees that all the data in the buffers will be send.
if (bytesTransferred !=
boost::asio::buffer_size(op.mBuffs[0]) + boost::asio::buffer_size(op.mBuffs[1]))
{
auto reason = std::string("failed to send all data. Expected to send ")
+ ToString(boost::asio::buffer_size(op.mBuffs[0]) + boost::asio::buffer_size(op.mBuffs[1]))
+ " bytes but transfered " + ToString(bytesTransferred) + "\n"
+ " at " + LOCATION;
if (mPrint) std::cout << reason << std::endl;
socket->setSendFatalError(reason);
return;
}
socket->mOutstandingSendData -= socket->mSendSizeBuff;
// if this was a synchronous send, fulfill the promise that the message was sent.
op.mPromise.set_value();
// if they provided a callback, execute it.
if (op.mCallback)
{
op.mCallback();
}
//delete op.mContainer;
socket->mSendStrand.dispatch([&op, socket, this]()
{
////////////////////////////////////////////////////////////////////////////////
//// This is within the stand. We have sequential access to the send queue. ////
////////////////////////////////////////////////////////////////////////////////
#ifdef CHANNEL_LOGGING
socket->mLog.push("completed send #" + ToString(op.mIdx) + ", size = " + ToString(socket->mSendSizeBuff));
#endif
//delete socket->mSendQueue.front();
socket->mSendQueue.pop_front();
// Do we have more messages to be sent?
auto sendMore = socket->mSendQueue.size();
if (sendMore)
{
sendOne(socket);
}
else if (socket->mSendStatus == Channel::Status::Stopped)
{
socket->mSendQueueEmptyProm.set_value();
socket->mSendQueueEmptyProm = std::promise<void>();
}
});
});
}
else if (op.type() == IOOperation::Type::CloseSend)
{
// This is a special case which may happen if the channel calls stop()
// with async sends still queued up, we will get here after they get completes. fulfill the
// promise that all async send operations have been completed.
#ifdef CHANNEL_LOGGING
socket->mLog.push("sendClosed #" + ToString(op.mIdx));
#endif
//delete socket->mSendQueue.front();
socket->mSendQueue.pop_front();
socket->mSendQueueEmptyProm.set_value();
}
else
{
std::cout << "error, unknown operation " << std::endl;
std::terminate();
}
}
void IOService::dispatch(ChannelBase* socket, std::unique_ptr<IOOperation>op)
{
#ifdef CHANNEL_LOGGING
op->mIdx = socket->mOpIdx++;
#endif
switch (op->type())
{
case IOOperation::Type::RecvData:
case IOOperation::Type::CloseRecv:
{
// boost complains if generalized move symantics are used with a post(...) callback
auto opPtr = op.release();
// a strand is like a lock. Stuff posted (or dispatched) to a strand will be executed sequentially
socket->mRecvStrand.post([this, socket, opPtr]()
{
std::unique_ptr<IOOperation>op(opPtr);
// check to see if we should kick off a new set of recv operations. If the size >= 1, then there
// is already a set of recv operations that will kick off the newly queued recv when its turn comes around.
bool startRecving = (socket->mRecvQueue.size() == 0) && (socket->mRecvSocketSet || op->type() == IOOperation::Type::CloseRecv);
#ifdef CHANNEL_LOGGING
if (op->type() == IOOperation::Type::RecvData)
socket->mLog.push("queuing recv #" + ToString(op->mIdx) + ", size = " + ToString(op->size()) + ", start = " + ToString(startRecving));
else
socket->mLog.push("queuing recvClosing #" + ToString(op->mIdx) + ", start = " + ToString(startRecving));
#endif
// the queue must be guarded from concurrent access, so add the op within the strand
// queue up the operation.
socket->mRecvQueue.emplace_back(std::move(op));
if (startRecving)
{
// ok, so there isn't any recv operations currently underway. Lets kick off the first one. Subsequent recvs
// will be kicked off at the completion of this operation.
receiveOne(socket);
}
});
}
break;
case IOOperation::Type::SendData:
case IOOperation::Type::CloseSend:
{
//std::cout << " dis " << (op->type() == IOOperation::Type::SendData ? "SendData" : "CloseSend") << std::endl;
// boost complains if generalized move symantics are used with a post(...) callback
auto opPtr = op.release();
// a strand is like a lock. Stuff posted (or dispatched) to a strand will be executed sequentially
socket->mSendStrand.post([this, socket, opPtr]()
{
std::unique_ptr<IOOperation>op(opPtr);
// the queue must be guarded from concurrent access, so add the op within the strand
socket->mTotalSentData += op->size();
socket->mOutstandingSendData += op->size();
socket->mMaxOutstandingSendData = std::max((u64)socket->mOutstandingSendData, (u64)socket->mMaxOutstandingSendData);
// check to see if we should kick off a new set of send operations. If the size >= 1, then there
// is already a set of send operations that will kick off the newly queued send when its turn comes around.
auto startSending = (socket->mSendQueue.size() == 0) && (socket->mSendSocketSet || op->type() == IOOperation::Type::CloseSend);
#ifdef CHANNEL_LOGGING
if (op->type() == IOOperation::Type::SendData)
socket->mLog.push("queuing send #" + ToString(op->mIdx) +
", size = " + ToString(op->size()) + ", start = " + ToString(startSending));
else
socket->mLog.push("queuing sendClosing #" + ToString(op->mIdx) + ", start = " + ToString(startSending));
#endif
// add the operation to the queue.
socket->mSendQueue.emplace_back(std::move(op));
if (startSending)
{
// ok, so there isn't any send operations currently underway. Lets kick off the first one. Subsequent sends
// will be kicked off at the completion of this operation.
sendOne(socket);
}
});
}
break;
default:
std::cout << ("unknown IOOperation::Type") << std::endl;
std::terminate();
break;
}
}
void IOService::aquireAcceptor(std::shared_ptr<SessionBase>& session)
{
std::promise<std::list<Acceptor>::iterator> p;
std::future<std::list<Acceptor>::iterator> f = p.get_future();
mStrand.dispatch([&]()
{
// see if there already exists an acceptor that this endpoint can use.
auto acceptorIter = std::find_if(
mAcceptors.begin(),
mAcceptors.end(), [&](const Acceptor& acptr)
{
return acptr.mPort == session->mPort;
});
if (acceptorIter == mAcceptors.end())
{
// an acceptor does not exist for this port. Lets create one.
mAcceptors.emplace_back(*this);
acceptorIter = mAcceptors.end(); --acceptorIter;
acceptorIter->mPort = session->mPort;
//std::cout << "creating acceptor on " + ToString(session->mPort) << std::endl;
}
p.set_value(acceptorIter);
});
auto acceptorIter = f.get();
acceptorIter->subscribe(session);
}
void IOService::startSocket(ChannelBase * chl, std::unique_ptr<BoostSocketInterface> socket)
{
chl->mHandle = std::move(socket);
// a strand is like a lock. Stuff posted (or dispatched) to a strand will be executed sequentially
chl->mRecvStrand.post([this, chl]()
{
#ifdef CHANNEL_LOGGING
chl->mLog.push("initRecv , start = " + ToString(chl->mRecvQueue.size()));
#endif
// check to see if we should kick off a new set of recv operations. Since we are just now
// starting the channel, its possible that the async connect call returned and the caller scheduled a receive
// operation. But since the channel handshake just finished, those operations didn't start. So if
// the queue has anything in it, we should actually start the operation now...
if (chl->mRecvQueue.size())
{
// ok, so there isn't any recv operations currently underway. Lets kick off the first one. Subsequent recvs
// will be kicked off at the completion of this operation.
receiveOne(chl);
}
chl->mRecvSocketSet = true;
auto ii = ++chl->mOpenCount;
if (ii == 2)
chl->mOpenProm.set_value();
});
// a strand is like a lock. Stuff posted (or dispatched) to a strand will be executed sequentially
chl->mSendStrand.post([this, chl]()
{
// the queue must be guarded from concurrent access, so add the op within the strand
auto start = chl->mSendQueue.size();
#ifdef CHANNEL_LOGGING
chl->mLog.push("initSend , start = " + ToString(start));
#endif
// check to see if we should kick off a new set of send operations. Since we are just now
// starting the channel, its possible that the async connect call returned and the caller scheduled a send
// operation. But since the channel handshake just finished, those operations didn't start. So if
// the queue has anything in it, we should actually start the operation now...
if (start)
{
// ok, so there isn't any send operations currently underway. Lets kick off the first one. Subsequent sends
// will be kicked off at the completion of this operation.
sendOne(chl);
}
chl->mSendSocketSet = true;
auto ii = ++chl->mOpenCount;
if (ii == 2)
chl->mOpenProm.set_value();
});
}
void details::SessionGroup::add(NamedSocket s, Acceptor* a)
{
auto iter = std::find_if(mChannels.begin(), mChannels.end(),
[&](const std::shared_ptr<ChannelBase>& chl)
{
return chl->mLocalName == s.mLocalName &&
chl->mRemoteName == s.mRemoteName;
});
if (iter != mChannels.end())
{
a->mIOService.startSocket(iter->get(), std::move(s.mSocket));
mChannels.erase(iter);
}
else
{
mSockets.emplace_back(std::move(s));
}
}
void details::SessionGroup::add(const std::shared_ptr<ChannelBase>& chl, Acceptor* a)
{
auto iter = std::find_if(mSockets.begin(), mSockets.end(),
[&](const NamedSocket& s)
{
return chl->mLocalName == s.mLocalName &&
chl->mRemoteName == s.mRemoteName;
});
if (iter != mSockets.end())
{
a->mIOService.startSocket(chl.get(), std::move(iter->mSocket));
mSockets.erase(iter);
}
else
{
mChannels.emplace_back(chl);
}
}
bool details::SessionGroup::hasMatchingChannel(const NamedSocket & s) const
{
return mChannels.end() != std::find_if(mChannels.begin(), mChannels.end(),
[&](const std::shared_ptr<ChannelBase>& chl)
{
return chl->mLocalName == s.mLocalName &&
chl->mRemoteName == s.mRemoteName;
});
}
bool details::SocketGroup::hasMatchingSocket(const std::shared_ptr<ChannelBase>& chl) const
{
return mSockets.end() != std::find_if(mSockets.begin(), mSockets.end(),
[&](const NamedSocket& s)
{
return chl->mLocalName == s.mLocalName &&
chl->mRemoteName == s.mRemoteName;
});
}
void details::SessionGroup::merge(details::SocketGroup& merge, Acceptor* a)
{
if (mSockets.size())
throw std::runtime_error(LOCATION);
for (auto& s : merge.mSockets) add(std::move(s), a);
merge.mSockets.clear();
auto session = mBase.lock();
if (session)
{
if (merge.mSessionID == 0 ||
session->mName != merge.mName ||
session->mSessionID)
throw std::runtime_error(LOCATION);
session->mName = std::move(merge.mName);
session->mSessionID = merge.mSessionID;
}
}
}
| 30.187809 | 162 | 0.606036 | [
"vector"
] |
880936b49b0d2b232035dc274bc6837738efbfc5 | 20,226 | cpp | C++ | generated/src/NodeClient.cpp | overlords/mmx-node | 53b2ba95feb89a691a1dcf60ec0ac7a50bf082af | [
"Apache-2.0"
] | 1 | 2021-12-30T09:05:19.000Z | 2021-12-30T09:05:19.000Z | generated/src/NodeClient.cpp | overlords/mmx-node | 53b2ba95feb89a691a1dcf60ec0ac7a50bf082af | [
"Apache-2.0"
] | null | null | null | generated/src/NodeClient.cpp | overlords/mmx-node | 53b2ba95feb89a691a1dcf60ec0ac7a50bf082af | [
"Apache-2.0"
] | null | null | null |
// AUTO GENERATED by vnxcppcodegen
#include <mmx/package.hxx>
#include <mmx/NodeClient.hxx>
#include <mmx/Block.hxx>
#include <mmx/BlockHeader.hxx>
#include <mmx/ChainParams.hxx>
#include <mmx/Contract.hxx>
#include <mmx/Node_add_block.hxx>
#include <mmx/Node_add_block_return.hxx>
#include <mmx/Node_add_transaction.hxx>
#include <mmx/Node_add_transaction_return.hxx>
#include <mmx/Node_get_balance.hxx>
#include <mmx/Node_get_balance_return.hxx>
#include <mmx/Node_get_block.hxx>
#include <mmx/Node_get_block_return.hxx>
#include <mmx/Node_get_block_at.hxx>
#include <mmx/Node_get_block_at_return.hxx>
#include <mmx/Node_get_block_hash.hxx>
#include <mmx/Node_get_block_hash_return.hxx>
#include <mmx/Node_get_contract.hxx>
#include <mmx/Node_get_contract_return.hxx>
#include <mmx/Node_get_header_at.hxx>
#include <mmx/Node_get_header_at_return.hxx>
#include <mmx/Node_get_height.hxx>
#include <mmx/Node_get_height_return.hxx>
#include <mmx/Node_get_history_for.hxx>
#include <mmx/Node_get_history_for_return.hxx>
#include <mmx/Node_get_params.hxx>
#include <mmx/Node_get_params_return.hxx>
#include <mmx/Node_get_stxo_list.hxx>
#include <mmx/Node_get_stxo_list_return.hxx>
#include <mmx/Node_get_synced_height.hxx>
#include <mmx/Node_get_synced_height_return.hxx>
#include <mmx/Node_get_total_balance.hxx>
#include <mmx/Node_get_total_balance_return.hxx>
#include <mmx/Node_get_transaction.hxx>
#include <mmx/Node_get_transaction_return.hxx>
#include <mmx/Node_get_transactions.hxx>
#include <mmx/Node_get_transactions_return.hxx>
#include <mmx/Node_get_tx_height.hxx>
#include <mmx/Node_get_tx_height_return.hxx>
#include <mmx/Node_get_txo_info.hxx>
#include <mmx/Node_get_txo_info_return.hxx>
#include <mmx/Node_get_utxo_list.hxx>
#include <mmx/Node_get_utxo_list_return.hxx>
#include <mmx/Node_start_sync.hxx>
#include <mmx/Node_start_sync_return.hxx>
#include <mmx/ProofOfTime.hxx>
#include <mmx/ProofResponse.hxx>
#include <mmx/Transaction.hxx>
#include <mmx/addr_t.hpp>
#include <mmx/hash_t.hpp>
#include <mmx/stxo_entry_t.hxx>
#include <mmx/tx_entry_t.hxx>
#include <mmx/txio_key_t.hxx>
#include <mmx/txo_info_t.hxx>
#include <mmx/utxo_entry_t.hxx>
#include <vnx/Module.h>
#include <vnx/ModuleInterface_vnx_get_config.hxx>
#include <vnx/ModuleInterface_vnx_get_config_return.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info_return.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code_return.hxx>
#include <vnx/ModuleInterface_vnx_restart.hxx>
#include <vnx/ModuleInterface_vnx_restart_return.hxx>
#include <vnx/ModuleInterface_vnx_self_test.hxx>
#include <vnx/ModuleInterface_vnx_self_test_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config.hxx>
#include <vnx/ModuleInterface_vnx_set_config_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_stop.hxx>
#include <vnx/ModuleInterface_vnx_stop_return.hxx>
#include <vnx/TopicPtr.hpp>
#include <vnx/addons/HttpComponent_http_request.hxx>
#include <vnx/addons/HttpComponent_http_request_return.hxx>
#include <vnx/addons/HttpComponent_http_request_chunk.hxx>
#include <vnx/addons/HttpComponent_http_request_chunk_return.hxx>
#include <vnx/addons/HttpData.hxx>
#include <vnx/addons/HttpRequest.hxx>
#include <vnx/addons/HttpResponse.hxx>
#include <vnx/Generic.hxx>
#include <vnx/vnx.h>
namespace mmx {
NodeClient::NodeClient(const std::string& service_name)
: Client::Client(vnx::Hash64(service_name))
{
}
NodeClient::NodeClient(vnx::Hash64 service_addr)
: Client::Client(service_addr)
{
}
::vnx::Object NodeClient::vnx_get_config_object() {
auto _method = ::vnx::ModuleInterface_vnx_get_config_object::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_object_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<::vnx::Object>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
::vnx::Variant NodeClient::vnx_get_config(const std::string& name) {
auto _method = ::vnx::ModuleInterface_vnx_get_config::create();
_method->name = name;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<::vnx::Variant>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
void NodeClient::vnx_set_config_object(const ::vnx::Object& config) {
auto _method = ::vnx::ModuleInterface_vnx_set_config_object::create();
_method->config = config;
vnx_request(_method, false);
}
void NodeClient::vnx_set_config_object_async(const ::vnx::Object& config) {
auto _method = ::vnx::ModuleInterface_vnx_set_config_object::create();
_method->config = config;
vnx_request(_method, true);
}
void NodeClient::vnx_set_config(const std::string& name, const ::vnx::Variant& value) {
auto _method = ::vnx::ModuleInterface_vnx_set_config::create();
_method->name = name;
_method->value = value;
vnx_request(_method, false);
}
void NodeClient::vnx_set_config_async(const std::string& name, const ::vnx::Variant& value) {
auto _method = ::vnx::ModuleInterface_vnx_set_config::create();
_method->name = name;
_method->value = value;
vnx_request(_method, true);
}
::vnx::TypeCode NodeClient::vnx_get_type_code() {
auto _method = ::vnx::ModuleInterface_vnx_get_type_code::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_type_code_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<::vnx::TypeCode>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::vnx::ModuleInfo> NodeClient::vnx_get_module_info() {
auto _method = ::vnx::ModuleInterface_vnx_get_module_info::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_module_info_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::ModuleInfo>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
void NodeClient::vnx_restart() {
auto _method = ::vnx::ModuleInterface_vnx_restart::create();
vnx_request(_method, false);
}
void NodeClient::vnx_restart_async() {
auto _method = ::vnx::ModuleInterface_vnx_restart::create();
vnx_request(_method, true);
}
void NodeClient::vnx_stop() {
auto _method = ::vnx::ModuleInterface_vnx_stop::create();
vnx_request(_method, false);
}
void NodeClient::vnx_stop_async() {
auto _method = ::vnx::ModuleInterface_vnx_stop::create();
vnx_request(_method, true);
}
vnx::bool_t NodeClient::vnx_self_test() {
auto _method = ::vnx::ModuleInterface_vnx_self_test::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_self_test_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<vnx::bool_t>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::mmx::ChainParams> NodeClient::get_params() {
auto _method = ::mmx::Node_get_params::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_params_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::ChainParams>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
uint32_t NodeClient::get_height() {
auto _method = ::mmx::Node_get_height::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_height_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<uint32_t>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
vnx::optional<uint32_t> NodeClient::get_synced_height() {
auto _method = ::mmx::Node_get_synced_height::create();
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_synced_height_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<vnx::optional<uint32_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::mmx::Block> NodeClient::get_block(const ::mmx::hash_t& hash) {
auto _method = ::mmx::Node_get_block::create();
_method->hash = hash;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_block_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::Block>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::mmx::Block> NodeClient::get_block_at(const uint32_t& height) {
auto _method = ::mmx::Node_get_block_at::create();
_method->height = height;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_block_at_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::Block>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::mmx::BlockHeader> NodeClient::get_header_at(const uint32_t& height) {
auto _method = ::mmx::Node_get_header_at::create();
_method->height = height;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_header_at_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::BlockHeader>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
vnx::optional<::mmx::hash_t> NodeClient::get_block_hash(const uint32_t& height) {
auto _method = ::mmx::Node_get_block_hash::create();
_method->height = height;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_block_hash_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<vnx::optional<::mmx::hash_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
::mmx::txo_info_t NodeClient::get_txo_info(const ::mmx::txio_key_t& key) {
auto _method = ::mmx::Node_get_txo_info::create();
_method->key = key;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_txo_info_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<::mmx::txo_info_t>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
vnx::optional<uint32_t> NodeClient::get_tx_height(const ::mmx::hash_t& id) {
auto _method = ::mmx::Node_get_tx_height::create();
_method->id = id;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_tx_height_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<vnx::optional<uint32_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
void NodeClient::add_block(std::shared_ptr<const ::mmx::Block> block) {
auto _method = ::mmx::Node_add_block::create();
_method->block = block;
vnx_request(_method, false);
}
void NodeClient::add_block_async(std::shared_ptr<const ::mmx::Block> block) {
auto _method = ::mmx::Node_add_block::create();
_method->block = block;
vnx_request(_method, true);
}
void NodeClient::add_transaction(std::shared_ptr<const ::mmx::Transaction> tx) {
auto _method = ::mmx::Node_add_transaction::create();
_method->tx = tx;
vnx_request(_method, false);
}
void NodeClient::add_transaction_async(std::shared_ptr<const ::mmx::Transaction> tx) {
auto _method = ::mmx::Node_add_transaction::create();
_method->tx = tx;
vnx_request(_method, true);
}
std::shared_ptr<const ::mmx::Transaction> NodeClient::get_transaction(const ::mmx::hash_t& id) {
auto _method = ::mmx::Node_get_transaction::create();
_method->id = id;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_transaction_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::Transaction>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::vector<std::shared_ptr<const ::mmx::Transaction>> NodeClient::get_transactions(const std::vector<::mmx::hash_t>& ids) {
auto _method = ::mmx::Node_get_transactions::create();
_method->ids = ids;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_transactions_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::vector<std::shared_ptr<const ::mmx::Transaction>>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::vector<::mmx::tx_entry_t> NodeClient::get_history_for(const std::vector<::mmx::addr_t>& addresses, const uint32_t& min_height) {
auto _method = ::mmx::Node_get_history_for::create();
_method->addresses = addresses;
_method->min_height = min_height;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_history_for_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::vector<::mmx::tx_entry_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::mmx::Contract> NodeClient::get_contract(const ::mmx::addr_t& address) {
auto _method = ::mmx::Node_get_contract::create();
_method->address = address;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_contract_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::mmx::Contract>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
uint64_t NodeClient::get_balance(const ::mmx::addr_t& address, const ::mmx::addr_t& contract) {
auto _method = ::mmx::Node_get_balance::create();
_method->address = address;
_method->contract = contract;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_balance_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<uint64_t>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
uint64_t NodeClient::get_total_balance(const std::vector<::mmx::addr_t>& addresses, const ::mmx::addr_t& contract) {
auto _method = ::mmx::Node_get_total_balance::create();
_method->addresses = addresses;
_method->contract = contract;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_total_balance_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<uint64_t>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::vector<::mmx::utxo_entry_t> NodeClient::get_utxo_list(const std::vector<::mmx::addr_t>& addresses) {
auto _method = ::mmx::Node_get_utxo_list::create();
_method->addresses = addresses;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_utxo_list_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::vector<::mmx::utxo_entry_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::vector<::mmx::stxo_entry_t> NodeClient::get_stxo_list(const std::vector<::mmx::addr_t>& addresses) {
auto _method = ::mmx::Node_get_stxo_list::create();
_method->addresses = addresses;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::mmx::Node_get_stxo_list_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::vector<::mmx::stxo_entry_t>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
void NodeClient::start_sync(const vnx::bool_t& force) {
auto _method = ::mmx::Node_start_sync::create();
_method->force = force;
vnx_request(_method, false);
}
void NodeClient::start_sync_async(const vnx::bool_t& force) {
auto _method = ::mmx::Node_start_sync::create();
_method->force = force;
vnx_request(_method, true);
}
std::shared_ptr<const ::vnx::addons::HttpResponse> NodeClient::http_request(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path) {
auto _method = ::vnx::addons::HttpComponent_http_request::create();
_method->request = request;
_method->sub_path = sub_path;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::HttpComponent_http_request_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::addons::HttpResponse>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
std::shared_ptr<const ::vnx::addons::HttpData> NodeClient::http_request_chunk(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path, const int64_t& offset, const int64_t& max_bytes) {
auto _method = ::vnx::addons::HttpComponent_http_request_chunk::create();
_method->request = request;
_method->sub_path = sub_path;
_method->offset = offset;
_method->max_bytes = max_bytes;
auto _return_value = vnx_request(_method, false);
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::HttpComponent_http_request_chunk_return>(_return_value)) {
return _result->_ret_0;
} else if(_return_value && !_return_value->is_void()) {
return _return_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::addons::HttpData>>();
} else {
throw std::logic_error("NodeClient: invalid return value");
}
}
} // namespace mmx
| 40.452 | 216 | 0.7566 | [
"object",
"vector"
] |
8816016016718b9fd36bf3eeea772120b004c317 | 13,632 | cpp | C++ | SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | 1 | 2022-03-29T18:51:49.000Z | 2022-03-29T18:51:49.000Z | SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | /* PkmnLib Pokemon
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <algorithm>
#include <cmath>
#include "Common/Cpp/Exceptions.h"
#include "Common/Qt/QtJsonTools.h"
#include "CommonFramework/Globals.h"
#include "PokemonSwSh_PkmnLib_Pokemon.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonSwSh{
namespace papkmnlib{
// default iv values, the "average" IV is 26, since there'a a 4/6 chance to get 31 and 2/6 chance to get 0-31
#define default_iv 26
// default ev is 0, none of the pokemon are actually "trained"
#define default_ev 0
// the default level for a pokemon is 65
#define default_level 65
// default level for a legendary pokemon is 70
#define default_legendary_level 70
Pokemon::Pokemon(
uint16_t dex_id,
std::string name,
std::string ability,
Type type1,
Type type2,
uint8_t level,
uint8_t base_hp,
uint8_t base_atk,
uint8_t base_def,
uint8_t base_spatk,
uint8_t base_spdef,
uint8_t base_speed
)
: m_dex_id(dex_id)
, m_name(std::move(name))
, m_ability(std::move(ability))
, m_type1(type1)
, m_type2(type2)
, m_level(level)
, m_base_hp(base_hp)
, m_base_atk(base_atk)
, m_base_def(base_def)
, m_base_spatk(base_spatk)
, m_base_spdef(base_spdef)
, m_base_speed(base_speed)
{
load_moves();
// initialize the stats based on the defaults
m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv;
// initialize the default EVs as well
m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev;
// then we need to calculate our stats
calculate_stats();
}
Pokemon::Pokemon(
uint16_t dex_id,
std::string name,
std::string ability,
Type type1,
Type type2,
uint8_t level,
uint8_t base_hp,
uint8_t base_atk,
uint8_t base_def,
uint8_t base_spatk,
uint8_t base_spdef,
uint8_t base_speed,
uint32_t move1_id,
uint32_t move2_id,
uint32_t move3_id,
uint32_t move4_id,
uint32_t legendary_desparation_move_id,
uint32_t max_move1_id,
uint32_t max_move2_id,
uint32_t max_move3_id,
uint32_t max_move4_id,
uint32_t max_move5_id
)
: m_dex_id(dex_id)
, m_name(std::move(name))
, m_ability(std::move(ability))
, m_type1(type1)
, m_type2(type2)
, m_level(level)
, m_base_hp(base_hp)
, m_base_atk(base_atk)
, m_base_def(base_def)
, m_base_spatk(base_spatk)
, m_base_spdef(base_spdef)
, m_base_speed(base_speed)
{
m_move_id[0] = move1_id;
m_move_id[1] = move2_id;
m_move_id[2] = move3_id;
m_move_id[3] = move4_id;
m_move_id[4] = legendary_desparation_move_id;
m_max_move_id[0] = max_move1_id;
m_max_move_id[1] = max_move2_id;
m_max_move_id[2] = max_move3_id;
m_max_move_id[3] = max_move4_id;
m_max_move_id[4] = max_move5_id;
load_moves();
// initialize the stats based on the defaults
m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv;
// initialize the default EVs as well
m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev;
// then we need to calculate our stats
calculate_stats();
}
void Pokemon::calculate_stats(){
// this method calculates stats from whatever is internally stored, use the update methods
// if we want to modify IVs or EVs
// HP stat
m_max_hp = calc_hp(m_base_hp, m_iv_hp, m_ev_hp, m_level);
// make sure we store the current HP
m_current_hp = m_max_hp;
// physical stats
m_calc_atk = calc_stat(m_base_atk, m_iv_atk, m_ev_atk, m_level);
m_calc_def = calc_stat(m_base_def, m_iv_def, m_ev_def, m_level);
// special stats
m_calc_spatk = calc_stat(m_base_spatk, m_iv_spatk, m_ev_spatk, m_level);
m_calc_spdef = calc_stat(m_base_spdef, m_iv_spdef, m_ev_spdef, m_level);
// speed stat
m_calc_speed = calc_stat(m_base_speed, m_iv_speed, m_ev_speed, m_level);
}
void Pokemon::load_moves(){
for (size_t c = 0; c < 5; c++){
if (m_move_id[c] != 0){
m_move[c] = &id_to_move(m_move_id[c]);
m_pp[c] = m_move[c]->pp();
}
if (m_max_move_id[c] != 0){
m_max_move[c] = &id_to_move(m_max_move_id[c]);
}
}
do{
if (is_legendary()){
m_num_moves = 5;
break;
}
size_t c = 0;
for (; c < 4; c++){
if (m_move[c] == nullptr){
break;
}
}
m_num_moves = c;
}while (false);
}
void Pokemon::update_stats(bool is_iv, uint8_t HP, uint8_t Atk, uint8_t Def, uint8_t SpAtk, uint8_t SpDef, uint8_t Speed){
// this method updates internally what the IVs or EVs are and then recalculates stats
if (is_iv)
{
m_iv_hp = HP;
m_iv_atk = Atk;
m_iv_def = Def;
m_iv_spatk = SpAtk;
m_iv_spdef = SpDef;
m_iv_speed = Speed;
}
else
{
m_ev_hp = HP;
m_ev_atk = Atk;
m_ev_def = Def;
m_ev_spatk = SpAtk;
m_ev_spdef = SpDef;
m_ev_speed = Speed;
}
// then recalculate stats
calculate_stats();
}
void Pokemon::update_stats(
uint8_t iv_hp, uint8_t iv_atk, uint8_t iv_def, uint8_t iv_spatk, uint8_t iv_spdef, uint8_t iv_speed,
uint8_t ev_hp, uint8_t ev_atk, uint8_t ev_def, uint8_t ev_spatk, uint8_t ev_spdef, uint8_t ev_speed
){
// this method updates internally what the IVs and EVs are and then recalculates stats
// update the IVs
m_iv_hp = iv_hp;
m_iv_atk = iv_atk;
m_iv_def = iv_def;
m_iv_spatk = iv_spatk;
m_iv_spdef = iv_spdef;
m_iv_speed = iv_speed;
// update the EVs
m_ev_hp = ev_hp;
m_ev_atk = ev_atk;
m_ev_def = ev_def;
m_ev_spatk = ev_spatk;
m_ev_spdef = ev_spdef;
m_ev_speed = ev_speed;
// then recalculate stats
calculate_stats();
}
void Pokemon::reset_hp(){
m_current_hp = m_max_hp;
}
double Pokemon::hp_ratio() const{
return (double)m_current_hp / m_max_hp;
}
void Pokemon::set_hp_ratio(double hp_ratio){
m_current_hp = (uint16_t)(m_max_hp * hp_ratio);
}
#if 0
void Pokemon::take_damage(uint16_t damage){
m_current_hp = damage > m_current_hp
? 0
: m_current_hp - damage;
}
void Pokemon::heal(uint16_t points){
m_current_hp += points;
m_current_hp = std::min(m_current_hp, m_max_hp);
}
#endif
void Pokemon::assert_move_index(size_t index) const{
if (index < num_moves()){
return;
}
throw InternalProgramError(
nullptr, PA_CURRENT_FUNCTION,
"Move index out-of-range: mon = " + m_name + ", index = " + std::to_string(index)
);
}
size_t Pokemon::num_moves() const{
return m_num_moves;
}
const Move& Pokemon::move(size_t index) const{
assert_move_index(index);
return *m_move[index];
}
const Move& Pokemon::max_move(size_t index) const{
assert_move_index(index);
return *m_max_move[index];
}
void Pokemon::set_move(const Move& move, size_t index){
assert_move_index(index);
m_move[index] = &move;
}
void Pokemon::set_max_move(const Move& move, size_t index){
assert_move_index(index);
m_max_move[index] = &move;
}
uint32_t Pokemon::move_id(size_t index) const{
assert_move_index(index);
return m_move_id[index];
}
uint32_t Pokemon::max_move_id(size_t index) const{
assert_move_index(index);
return m_max_move_id[index];
}
uint8_t Pokemon::pp(size_t index) const{
assert_move_index(index);
return m_pp[index];
}
void Pokemon::update_pp(size_t index, int8_t movePP){
assert_move_index(index);
m_pp[index] = std::min(movePP, (int8_t)m_move[index]->pp());
}
#if 0
void Pokemon::reduce_pp(size_t index, int8_t amount){
assert_move_index(index);
m_pp[index] -= amount;
m_pp[index] = std::min(m_pp[index], (int8_t)m_move[index]->pp());
m_pp[index] = std::max(m_pp[index], (int8_t)0);
}
void Pokemon::reset_pp(){
for (size_t c = 0; c < 5; c++){
const Move* move = m_move[c];
m_pp[c] = move == nullptr ? 0 : move->pp();
}
}
#endif
void Pokemon::transform_from_ditto(const Pokemon& opponent){
if (m_name != "ditto"){
return;
}
double hp_ratio = (double)m_current_hp / m_max_hp;
bool dmaxed = m_is_dynamax;
*this = opponent;
m_pp[0] = 5;
m_pp[1] = 5;
m_pp[2] = 5;
m_pp[3] = 5;
set_hp_ratio(hp_ratio);
set_is_dynamax(dmaxed);
}
std::string Pokemon::dump() const{
std::string str = m_name + ": ";
str += "hp:" + std::to_string(m_current_hp) + "/" + std::to_string(m_max_hp);
str += ", dmax:" + std::to_string(m_is_dynamax);
str += "\n";
return str;
}
std::map<std::string, Pokemon> load_pokemon(const std::string& filepath, bool is_legendary){
QString path = RESOURCE_PATH() + QString::fromStdString(filepath);
QJsonObject json = read_json_file(path).object();
if (json.empty()){
throw FileException(
nullptr, PA_CURRENT_FUNCTION,
"Json is either empty or invalid.",
path.toStdString()
);
}
std::map<std::string, Pokemon> map;
uint8_t level;
int move_limit;
if (is_legendary){
level = default_legendary_level;
move_limit = 5;
}else{
level = default_level;
move_limit = 4;
}
for (auto iter = json.begin(); iter != json.end(); ++iter){
std::string slug = iter.key().toStdString();
QJsonObject obj = iter.value().toObject();
Type type1 = Type::none;
Type type2 = Type::none;
{
QJsonArray array = json_get_array_throw(obj, "types");
if (array.size() < 1){
throw FileException(nullptr, PA_CURRENT_FUNCTION, "Must have at least one type: " + slug, path.toStdString());
}
type1 = get_type_from_string(array[0].toString().toStdString());
if (array.size() > 1){
type2 = get_type_from_string(array[1].toString().toStdString());
}
}
uint32_t moves[5] = {0, 0, 0, 0, 0};
{
QJsonArray array = json_get_array_throw(obj, "moves");
if (array.size() > move_limit){
throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, path.toStdString());
}
for (int c = 0; c < array.size(); c++){
moves[c] = array[c].toInt();
}
}
uint32_t max_moves[5] = {0, 0, 0, 0, 0};
{
QJsonArray array = json_get_array_throw(obj, "max_moves");
if (array.size() > move_limit){
throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, path.toStdString());
}
for (int c = 0; c < array.size(); c++){
max_moves[c] = array[c].toInt();
}
}
QJsonArray base_stats = json_get_array_throw(obj, "base_stats");
if (base_stats.size() != 6){
throw FileException(nullptr, PA_CURRENT_FUNCTION, "Should be exactly 6 base stats: " + slug, path.toStdString());
}
map.emplace(
std::piecewise_construct,
std::forward_as_tuple(slug),
std::forward_as_tuple(
json_get_int_throw(obj, "id"),
slug,
json_get_string_throw(obj, "ability_id").toStdString(),
type1, type2,
level,
(uint8_t)base_stats[0].toInt(),
(uint8_t)base_stats[1].toInt(),
(uint8_t)base_stats[2].toInt(),
(uint8_t)base_stats[3].toInt(),
(uint8_t)base_stats[4].toInt(),
(uint8_t)base_stats[5].toInt(),
moves[0],
moves[1],
moves[2],
moves[3],
moves[4],
max_moves[0],
max_moves[1],
max_moves[2],
max_moves[3],
max_moves[4]
)
);
}
return map;
}
const std::map<std::string, Pokemon>& all_rental_pokemon(){
static std::map<std::string, Pokemon> pokemon = load_pokemon("PokemonSwSh/MaxLair/rental_pokemon.json", false);
return pokemon;
}
const std::map<std::string, Pokemon>& all_boss_pokemon(){
static std::map<std::string, Pokemon> pokemon = load_pokemon("PokemonSwSh/MaxLair/boss_pokemon.json", true);
return pokemon;
}
const Pokemon& get_pokemon(const std::string& slug){
{
const std::map<std::string, Pokemon>& database = all_rental_pokemon();
auto iter = database.find(slug);
if (iter != database.end()){
return iter->second;
}
}
{
const std::map<std::string, Pokemon>& database = all_boss_pokemon();
auto iter = database.find(slug);
if (iter != database.end()){
return iter->second;
}
}
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found: " + slug);
}
}
}
}
}
| 28.165289 | 127 | 0.593383 | [
"object"
] |
8818142d286d2170cb0bf2ba998c5238af523ff2 | 6,361 | hpp | C++ | c++/include/objmgr/seq_entry_ci.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/objmgr/seq_entry_ci.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/objmgr/seq_entry_ci.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #ifndef OBJMGR__SEQ_ENTRY_CI__HPP
#define OBJMGR__SEQ_ENTRY_CI__HPP
/* $Id: seq_entry_ci.hpp 278261 2011-04-19 16:39:35Z vasilche $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko, Eugene Vasilchenko
*
* File Description:
* Handle to Seq-entry object
*
*/
#include <corelib/ncbistd.hpp>
#include <objmgr/bioseq_set_handle.hpp>
#include <objmgr/seq_entry_handle.hpp>
#include <vector>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
/** @addtogroup ObjectManagerIterators
*
* @{
*/
class CSeq_entry_Handle;
class CSeq_entry_EditHandle;
class CBioseq_set_Handle;
class CBioseq_set_EditHandle;
class CSeq_entry_CI;
class CSeq_entry_I;
/////////////////////////////////////////////////////////////////////////////
///
/// CSeq_entry_CI --
///
/// Enumerate seq-entries in a given parent seq-entry or a bioseq-set
///
class NCBI_XOBJMGR_EXPORT CSeq_entry_CI
{
public:
/// Create an empty iterator
CSeq_entry_CI(void);
/// Create an iterator that enumerates Seq-entries
/// inside the given Seq-entry.
CSeq_entry_CI(const CSeq_entry_Handle& entry);
/// Create an iterator that enumerates Seq-entries
/// inside the given Bioseq-set.
CSeq_entry_CI(const CBioseq_set_Handle& set);
/// Check if iterator points to an object
DECLARE_OPERATOR_BOOL(m_Current);
bool operator ==(const CSeq_entry_CI& iter) const;
bool operator !=(const CSeq_entry_CI& iter) const;
/// Move to the next object in iterated sequence
CSeq_entry_CI& operator ++(void);
const CSeq_entry_Handle& operator*(void) const;
const CSeq_entry_Handle* operator->(void) const;
const CBioseq_set_Handle& GetParentBioseq_set(void) const;
private:
typedef vector< CRef<CSeq_entry_Info> > TSeq_set;
typedef TSeq_set::const_iterator TIterator;
void x_Initialize(const CBioseq_set_Handle& set);
void x_SetCurrentEntry(void);
friend class CBioseq_set_Handle;
CSeq_entry_CI& operator ++(int);
CBioseq_set_Handle m_Parent;
TIterator m_Iterator;
CSeq_entry_Handle m_Current;
};
/////////////////////////////////////////////////////////////////////////////
///
/// CSeq_entry_I --
///
/// Non const version of CSeq_entry_CI
///
/// @sa
/// CSeq_entry_CI
class NCBI_XOBJMGR_EXPORT CSeq_entry_I
{
public:
/// Create an empty iterator
CSeq_entry_I(void);
/// Create an iterator that enumerates seq-entries
/// related to the given seq-entrie
CSeq_entry_I(const CSeq_entry_EditHandle& entry);
/// Create an iterator that enumerates seq-entries
/// related to the given seq-set
CSeq_entry_I(const CBioseq_set_EditHandle& set);
/// Check if iterator points to an object
DECLARE_OPERATOR_BOOL(m_Current);
bool operator ==(const CSeq_entry_I& iter) const;
bool operator !=(const CSeq_entry_I& iter) const;
CSeq_entry_I& operator ++(void);
const CSeq_entry_EditHandle& operator*(void) const;
const CSeq_entry_EditHandle* operator->(void) const;
const CBioseq_set_EditHandle& GetParentBioseq_set(void) const;
private:
typedef vector< CRef<CSeq_entry_Info> > TSeq_set;
typedef TSeq_set::iterator TIterator;
void x_Initialize(const CBioseq_set_EditHandle& set);
void x_SetCurrentEntry(void);
friend class CBioseq_set_Handle;
/// Move to the next object in iterated sequence
CSeq_entry_I& operator ++(int);
CBioseq_set_EditHandle m_Parent;
TIterator m_Iterator;
CSeq_entry_EditHandle m_Current;
};
/////////////////////////////////////////////////////////////////////////////
// CSeq_entry_CI inline methods
/////////////////////////////////////////////////////////////////////////////
inline
CSeq_entry_CI::CSeq_entry_CI(void)
{
}
inline
bool CSeq_entry_CI::operator ==(const CSeq_entry_CI& iter) const
{
return m_Current == iter.m_Current;
}
inline
bool CSeq_entry_CI::operator !=(const CSeq_entry_CI& iter) const
{
return m_Current != iter.m_Current;
}
inline
const CSeq_entry_Handle& CSeq_entry_CI::operator*(void) const
{
return m_Current;
}
inline
const CSeq_entry_Handle* CSeq_entry_CI::operator->(void) const
{
return &m_Current;
}
inline
const CBioseq_set_Handle& CSeq_entry_CI::GetParentBioseq_set(void) const
{
return m_Parent;
}
/////////////////////////////////////////////////////////////////////////////
// CSeq_entry_I inline methods
/////////////////////////////////////////////////////////////////////////////
inline
CSeq_entry_I::CSeq_entry_I(void)
{
}
inline
bool CSeq_entry_I::operator ==(const CSeq_entry_I& iter) const
{
return m_Current == iter.m_Current;
}
inline
bool CSeq_entry_I::operator !=(const CSeq_entry_I& iter) const
{
return m_Current != iter.m_Current;
}
inline
const CSeq_entry_EditHandle& CSeq_entry_I::operator*(void) const
{
return m_Current;
}
inline
const CSeq_entry_EditHandle* CSeq_entry_I::operator->(void) const
{
return &m_Current;
}
inline
const CBioseq_set_EditHandle& CSeq_entry_I::GetParentBioseq_set(void) const
{
return m_Parent;
}
/* @} */
END_SCOPE(objects)
END_NCBI_SCOPE
#endif//OBJMGR__SEQ_ENTRY_CI__HPP
| 24.278626 | 77 | 0.660902 | [
"object",
"vector"
] |
88194dfb5fef3bd1c0b75842516649cffbed74c8 | 12,989 | cc | C++ | ui/base/ozone/touch_event_converter_ozone_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | ui/base/ozone/touch_event_converter_ozone_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/base/ozone/touch_event_converter_ozone_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 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 <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/message_loop.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/events/event.h"
#include "ui/base/ozone/touch_event_converter_ozone.h"
namespace {
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
} // namespace
namespace ui {
class MockTouchEventConverterOzone : public TouchEventConverterOzone,
public base::MessageLoop::Dispatcher {
public:
MockTouchEventConverterOzone(int a, int b);
virtual ~MockTouchEventConverterOzone() {};
void ConfigureReadMock(struct input_event* queue,
long read_this_many,
long queue_index);
unsigned size() { return dispatched_events_.size(); }
TouchEvent* event(unsigned index) { return dispatched_events_[index]; }
// Actually dispatch the event reader code.
void ReadNow() {
OnFileCanReadWithoutBlocking(read_pipe_);
base::RunLoop().RunUntilIdle();
}
virtual bool Dispatch(const base::NativeEvent& event) OVERRIDE;
private:
int read_pipe_;
int write_pipe_;
ScopedVector<TouchEvent> dispatched_events_;
DISALLOW_COPY_AND_ASSIGN(MockTouchEventConverterOzone);
};
MockTouchEventConverterOzone::MockTouchEventConverterOzone(int a, int b)
: TouchEventConverterOzone(a, b) {
pressure_min_ = 30;
pressure_max_ = 60;
int fds[2];
DCHECK(pipe(fds) >= 0) << "pipe() failed, errno: " << errno;
DCHECK(SetNonBlocking(fds[0]) == 0)
<< "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
DCHECK(SetNonBlocking(fds[1]) == 0)
<< "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
read_pipe_ = fds[0];
write_pipe_ = fds[1];
}
bool MockTouchEventConverterOzone::Dispatch(const base::NativeEvent& event) {
ui::TouchEvent* ev = new ui::TouchEvent(event);
dispatched_events_.push_back(ev);
return true;
}
void MockTouchEventConverterOzone::ConfigureReadMock(struct input_event* queue,
long read_this_many,
long queue_index) {
int nwrite = HANDLE_EINTR(write(write_pipe_,
queue + queue_index,
sizeof(struct input_event) * read_this_many));
DCHECK(nwrite ==
static_cast<int>(sizeof(struct input_event) * read_this_many))
<< "write() failed, errno: " << errno;
}
} // namespace ui
// Test fixture.
class TouchEventConverterOzoneTest : public testing::Test {
public:
TouchEventConverterOzoneTest() {}
// Overridden from testing::Test:
virtual void SetUp() OVERRIDE {
loop_ = new base::MessageLoop(base::MessageLoop::TYPE_UI);
device_ = new ui::MockTouchEventConverterOzone(-1, 2);
base::MessagePumpOzone::Current()->AddDispatcherForRootWindow(device_);
}
virtual void TearDown() OVERRIDE {
delete device_;
delete loop_;
}
ui::MockTouchEventConverterOzone* device() { return device_; }
private:
base::MessageLoop* loop_;
ui::MockTouchEventConverterOzone* device_;
DISALLOW_COPY_AND_ASSIGN(TouchEventConverterOzoneTest);
};
// TODO(rjkroege): Test for valid handling of time stamps.
TEST_F(TouchEventConverterOzoneTest, TouchDown) {
ui::MockTouchEventConverterOzone* dev = device();
struct input_event mock_kernel_queue[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684},
{{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3},
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
dev->ConfigureReadMock(mock_kernel_queue, 1, 0);
dev->ReadNow();
EXPECT_EQ(0u, dev->size());
dev->ConfigureReadMock(mock_kernel_queue, 2, 1);
dev->ReadNow();
EXPECT_EQ(0u, dev->size());
dev->ConfigureReadMock(mock_kernel_queue, 3, 3);
dev->ReadNow();
EXPECT_EQ(1u, dev->size());
ui::TouchEvent* event = dev->event(0);
EXPECT_FALSE(event == NULL);
EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp());
EXPECT_EQ(42, event->x());
EXPECT_EQ(51, event->y());
EXPECT_EQ(0, event->touch_id());
EXPECT_FLOAT_EQ(.5f, event->force());
EXPECT_FLOAT_EQ(0.f, event->rotation_angle());
}
TEST_F(TouchEventConverterOzoneTest, NoEvents) {
ui::MockTouchEventConverterOzone* dev = device();
dev->ConfigureReadMock(NULL, 0, 0);
EXPECT_EQ(0u, dev->size());
}
TEST_F(TouchEventConverterOzoneTest, TouchMove) {
ui::MockTouchEventConverterOzone* dev = device();
struct input_event mock_kernel_queue_press[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684},
{{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3},
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
struct input_event mock_kernel_queue_move1[] = {
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 50},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 43}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
struct input_event mock_kernel_queue_move2[] = {
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 42}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
// Setup and discard a press.
dev->ConfigureReadMock(mock_kernel_queue_press, 6, 0);
dev->ReadNow();
EXPECT_EQ(1u, dev->size());
dev->ConfigureReadMock(mock_kernel_queue_move1, 4, 0);
dev->ReadNow();
EXPECT_EQ(2u, dev->size());
ui::TouchEvent* event = dev->event(1);
EXPECT_FALSE(event == NULL);
EXPECT_EQ(ui::ET_TOUCH_MOVED, event->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp());
EXPECT_EQ(42, event->x());
EXPECT_EQ(43, event->y());
EXPECT_EQ(0, event->touch_id());
EXPECT_FLOAT_EQ(2.f / 3.f, event->force());
EXPECT_FLOAT_EQ(0.f, event->rotation_angle());
dev->ConfigureReadMock(mock_kernel_queue_move2, 2, 0);
dev->ReadNow();
EXPECT_EQ(3u, dev->size());
event = dev->event(2);
EXPECT_FALSE(event == NULL);
EXPECT_EQ(ui::ET_TOUCH_MOVED, event->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp());
EXPECT_EQ(42, event->x());
EXPECT_EQ(42, event->y());
EXPECT_EQ(0, event->touch_id());
EXPECT_FLOAT_EQ(2.f / 3.f, event->force());
EXPECT_FLOAT_EQ(0.f, event->rotation_angle());
}
TEST_F(TouchEventConverterOzoneTest, TouchRelease) {
ui::MockTouchEventConverterOzone* dev = device();
struct input_event mock_kernel_queue_press[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684},
{{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3},
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
struct input_event mock_kernel_queue_release[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
// Setup and discard a press.
dev->ConfigureReadMock(mock_kernel_queue_press, 6, 0);
dev->ReadNow();
EXPECT_EQ(1u, dev->size());
ui::TouchEvent* event = dev->event(0);
EXPECT_FALSE(event == NULL);
dev->ConfigureReadMock(mock_kernel_queue_release, 2, 0);
dev->ReadNow();
EXPECT_EQ(2u, dev->size());
event = dev->event(1);
EXPECT_FALSE(event == NULL);
EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp());
EXPECT_EQ(42, event->x());
EXPECT_EQ(51, event->y());
EXPECT_EQ(0, event->touch_id());
EXPECT_FLOAT_EQ(.5f, event->force());
EXPECT_FLOAT_EQ(0.f, event->rotation_angle());
}
TEST_F(TouchEventConverterOzoneTest, TwoFingerGesture) {
ui::MockTouchEventConverterOzone* dev = device();
ui::TouchEvent* ev0;
ui::TouchEvent* ev1;
struct input_event mock_kernel_queue_press0[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684},
{{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3},
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
// Setup and discard a press.
dev->ConfigureReadMock(mock_kernel_queue_press0, 6, 0);
dev->ReadNow();
EXPECT_EQ(1u, dev->size());
struct input_event mock_kernel_queue_move0[] = {
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
// Setup and discard a move.
dev->ConfigureReadMock(mock_kernel_queue_move0, 2, 0);
dev->ReadNow();
EXPECT_EQ(2u, dev->size());
struct input_event mock_kernel_queue_move0press1[] = {
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0},
{{0, 0}, EV_ABS, ABS_MT_SLOT, 1}, {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 686},
{{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3},
{{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 101},
{{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 102}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
// Move on 0, press on 1.
dev->ConfigureReadMock(mock_kernel_queue_move0press1, 9, 0);
dev->ReadNow();
EXPECT_EQ(4u, dev->size());
ev0 = dev->event(2);
ev1 = dev->event(3);
// Move
EXPECT_EQ(ui::ET_TOUCH_MOVED, ev0->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp());
EXPECT_EQ(40, ev0->x());
EXPECT_EQ(51, ev0->y());
EXPECT_EQ(0, ev0->touch_id());
EXPECT_FLOAT_EQ(.5f, ev0->force());
EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle());
// Press
EXPECT_EQ(ui::ET_TOUCH_PRESSED, ev1->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp());
EXPECT_EQ(101, ev1->x());
EXPECT_EQ(102, ev1->y());
EXPECT_EQ(1, ev1->touch_id());
EXPECT_FLOAT_EQ(.5f, ev1->force());
EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle());
// Stationary 0, Moves 1.
struct input_event mock_kernel_queue_stationary0_move1[] = {
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
dev->ConfigureReadMock(mock_kernel_queue_stationary0_move1, 2, 0);
dev->ReadNow();
EXPECT_EQ(5u, dev->size());
ev1 = dev->event(4);
EXPECT_EQ(ui::ET_TOUCH_MOVED, ev1->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp());
EXPECT_EQ(40, ev1->x());
EXPECT_EQ(102, ev1->y());
EXPECT_EQ(1, ev1->touch_id());
EXPECT_FLOAT_EQ(.5f, ev1->force());
EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle());
// Move 0, stationary 1.
struct input_event mock_kernel_queue_move0_stationary1[] = {
{{0, 0}, EV_ABS, ABS_MT_SLOT, 0}, {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 39},
{{0, 0}, EV_SYN, SYN_REPORT, 0}
};
dev->ConfigureReadMock(mock_kernel_queue_move0_stationary1, 3, 0);
dev->ReadNow();
EXPECT_EQ(6u, dev->size());
ev0 = dev->event(5);
EXPECT_EQ(ui::ET_TOUCH_MOVED, ev0->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp());
EXPECT_EQ(39, ev0->x());
EXPECT_EQ(51, ev0->y());
EXPECT_EQ(0, ev0->touch_id());
EXPECT_FLOAT_EQ(.5f, ev0->force());
EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle());
// Release 0, move 1.
struct input_event mock_kernel_queue_release0_move1[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_ABS, ABS_MT_SLOT, 1},
{{0, 0}, EV_ABS, ABS_MT_POSITION_X, 38}, {{0, 0}, EV_SYN, SYN_REPORT, 0}
};
dev->ConfigureReadMock(mock_kernel_queue_release0_move1, 4, 0);
dev->ReadNow();
EXPECT_EQ(8u, dev->size());
ev0 = dev->event(6);
ev1 = dev->event(7);
EXPECT_EQ(ui::ET_TOUCH_RELEASED, ev0->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp());
EXPECT_EQ(39, ev0->x());
EXPECT_EQ(51, ev0->y());
EXPECT_EQ(0, ev0->touch_id());
EXPECT_FLOAT_EQ(.5f, ev0->force());
EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle());
EXPECT_EQ(ui::ET_TOUCH_MOVED, ev1->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp());
EXPECT_EQ(38, ev1->x());
EXPECT_EQ(102, ev1->y());
EXPECT_EQ(1, ev1->touch_id());
EXPECT_FLOAT_EQ(.5f, ev1->force());
EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle());
// Release 1.
struct input_event mock_kernel_queue_release1[] = {
{{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_SYN, SYN_REPORT, 0},
};
dev->ConfigureReadMock(mock_kernel_queue_release1, 2, 0);
dev->ReadNow();
EXPECT_EQ(9u, dev->size());
ev1 = dev->event(8);
EXPECT_EQ(ui::ET_TOUCH_RELEASED, ev1->type());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp());
EXPECT_EQ(38, ev1->x());
EXPECT_EQ(102, ev1->y());
EXPECT_EQ(1, ev1->touch_id());
EXPECT_FLOAT_EQ(.5f, ev1->force());
EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle());
}
| 32.635678 | 80 | 0.66795 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.